当前位置:   article > 正文

documents4j-word excel ..转pdf格式_documents4j word转pdf

documents4j word转pdf

 官网地址:documents4j - Java 的文档格式转换器

本文中使用的是本地转换器

草率的看了一眼文档,说明使用本地转换器需要在本机有ms work、ms excel (此处部署在linux时需要安装)。

本文使用的documents4j依赖(若有其他格式的文件需要转换则需要引入其他转换器)

  1. <dependency>
  2. <groupId>com.documents4j</groupId>
  3. <artifactId>documents4j-local</artifactId>
  4. <version>1.1.1</version>
  5. </dependency>
  6. <!--word-->
  7. <dependency>
  8. <groupId>com.documents4j</groupId>
  9. <artifactId>documents4j-transformer-msoffice-word</artifactId>
  10. <version>1.1.1</version>
  11. </dependency>
  12. <!--excel-->
  13. <dependency>
  14. <groupId>com.documents4j</groupId>
  15. <artifactId>documents4j-transformer-msoffice-excel</artifactId>
  16. <version>1.1.1</version>
  17. </dependency>

工具类中还有jpg、png转换pdf以及纯文本格式的文件使用的是 itextpdf(有需要也可以看一下这部分)

<dependency>
   <groupId>fr.opensagres.xdocreport</groupId>
   <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
   <version>1.0.6</version>
</dependency>
<dependency>
   <groupId>com.itextpdf.tool</groupId>
   <artifactId>xmlworker</artifactId>
   <version>5.5.11</version>
</dependency>

  1. import java.io.*;
  2. import com.aams.base.AamsOperatingException;
  3. import com.documents4j.api.DocumentType;
  4. import com.documents4j.api.IConverter;
  5. import com.documents4j.job.LocalConverter;
  6. import com.itextpdf.text.*;
  7. import com.itextpdf.text.Document;
  8. import com.itextpdf.text.pdf.PdfWriter;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. public class FileTransformUtil {
  12. private Logger log = LoggerFactory.getLogger(FileTransformUtil.class);
  13. public InputStream getPdfStream(String fileEnd, String fileName, InputStream fileInput) throws Exception {
  14. // 输出的PDF流
  15. ByteArrayOutputStream output = new ByteArrayOutputStream();
  16. //纯文本和图片的采用的是itextpdf的方式 有兴趣的也可以使用documents4j完成一下(这里因为写的比较早所以就没改本人也懒的换了)
  17. if ("xml".equalsIgnoreCase(fileEnd) || "html".equalsIgnoreCase(fileEnd) || "txt".equalsIgnoreCase(fileEnd)) {
  18. // 创建PDF文档对象 页大小为A4
  19. Document document = new Document(PageSize.A4, 20, 20, 20, 20);
  20. // 创建PDF写入器
  21. PdfWriter.getInstance(document, output);
  22. // 打开文档对象
  23. document.open();
  24. //读取xml中的内容
  25. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//输出流
  26. byte[] bytes = new byte[1024];
  27. int len;
  28. while ((len = fileInput.read(bytes)) != -1) {
  29. outputStream.write(bytes, 0, len);//将读到的字节写入输出流
  30. }
  31. fileInput.close();
  32. String content=outputStream.toString();
  33. outputStream.close();
  34. this.createPdfContent(document,content);
  35. document.close();
  36. output.close();
  37. return new ByteArrayInputStream(output.toByteArray());
  38. }
  39. else if ("jpg".equalsIgnoreCase(fileEnd) || "png".equalsIgnoreCase(fileEnd)) {
  40. // 创建PDF文档对象 页大小为A4
  41. Document document = new Document(PageSize.A4, 20, 20, 20, 20);
  42. // 创建PDF写入器
  43. PdfWriter.getInstance(document, output);
  44. // 打开文档对象
  45. document.open();
  46. //添加图片
  47. this.createStreamPic(document,fileInput);
  48. document.close();
  49. fileInput.close();
  50. output.close();
  51. return new ByteArrayInputStream(output.toByteArray());
  52. }
  53. else if ("docx".equalsIgnoreCase(fileEnd) || "doc".equalsIgnoreCase(fileEnd) || "xlsx".equalsIgnoreCase(fileEnd) || "xls".equalsIgnoreCase(fileEnd)) {
  54. try {
  55. //本地转换器转换文件
  56. IConverter converter = LocalConverter.builder().build();
  57. if(fileEnd.equals("doc")){
  58. //指定要转格式的文件
  59. converter.convert(fileInput)
  60. //当前文件的格式
  61. .as(DocumentType.DOC)
  62. //输出--这里直接输出到流中 (如果是直接写在本地的可以直接 FileOutPutStream(new File("位置")))
  63. .to(output)
  64. //输出的格式
  65. .as(DocumentType.PDF).execute();
  66. }
  67. else if(fileEnd.equals("docx")){
  68. converter.convert(fileInput)
  69. .as(DocumentType.DOCX)
  70. .to(output)
  71. .as(DocumentType.PDF).execute();
  72. }
  73. else if(fileEnd.equals("xlsx")){
  74. converter.convert(fileInput)
  75. .as(DocumentType.XLSX)
  76. .to(output)
  77. .as(DocumentType.PDF).execute();
  78. }
  79. else if(fileEnd.equals("xls")){
  80. converter.convert(fileInput)
  81. .as(DocumentType.XLS)
  82. .to(output)
  83. .as(DocumentType.PDF).execute();
  84. }
  85. output.close();
  86. fileInput.close();
  87. return new ByteArrayInputStream(output.toByteArray());
  88. } catch (Exception e) {
  89. log.error("[documents4J] word转pdf失败:{}", e.toString());
  90. }finally {
  91. if(output != null){
  92. output.close();
  93. }
  94. }
  95. }
  96. return null;
  97. }
  98. private void createPdfContent(Document document,String text) throws AamsOperatingException {
  99. try {
  100. Paragraph paragraph1 = new Paragraph();
  101. Chunk timeChunk = new Chunk(text);
  102. paragraph1.add(timeChunk);
  103. document.add(paragraph1);
  104. } catch (Exception e) {
  105. throw new AamsOperatingException(e.getMessage());
  106. }
  107. }
  108. private void createStreamPic(Document document, InputStream inputStream) throws AamsOperatingException {
  109. this.createStreamPic(document, inputStream, 0, 0);
  110. }
  111. /**
  112. * @param height 高
  113. * @param width 宽
  114. * @param inputStream 图片流
  115. * pdf中添加图片
  116. **/
  117. private void createStreamPic(Document document, InputStream inputStream, float height, float width) throws AamsOperatingException {
  118. try {
  119. int n;
  120. byte[] buffer = new byte[4096];
  121. ByteArrayOutputStream imgOutPut = new ByteArrayOutputStream();
  122. while (-1 != (n = inputStream.read(buffer))) {
  123. imgOutPut.write(buffer, 0, n);
  124. }
  125. Image image = Image.getInstance(imgOutPut.toByteArray());
  126. height = height != 0 ? height : image.getHeight();
  127. width = width != 0 ? width : image.getWidth();
  128. int percent = getPercent(height, width);
  129. image.setAlignment(Image.MIDDLE);
  130. image.scalePercent(percent);
  131. document.add(image);
  132. }catch (Exception e){
  133. throw new AamsOperatingException(e.getMessage());
  134. }
  135. }
  136. private void createUrlPic(Document document, String path) throws AamsOperatingException {
  137. this.createUrlPic(document, path, 0, 0);
  138. }
  139. /**
  140. *@param height 高
  141. *@param width 宽
  142. *@param path 图片地址
  143. * pdf中添加图片
  144. **/
  145. private void createUrlPic(Document document, String path, float height, float width) throws AamsOperatingException {
  146. try {
  147. Image image = Image.getInstance(path);
  148. height = height != 0 ? height : image.getHeight();
  149. width = width != 0 ? width : image.getWidth();
  150. int percent = getPercent(height, width);
  151. image.setAlignment(Image.MIDDLE);
  152. image.scalePercent(percent);
  153. document.add(image);
  154. } catch (Exception e) {
  155. throw new AamsOperatingException(e.getMessage());
  156. }
  157. }
  158. //图片比例设置
  159. private static int getPercent(float height, float weight) {
  160. float percent = 0.0F;
  161. if (height > weight) {
  162. percent = PageSize.A4.getHeight() / height * 100;
  163. } else {
  164. percent = PageSize.A4.getWidth() / weight * 100;
  165. }
  166. return Math.round(percent);
  167. }
  168. /**
  169. * main方法中截是测试使用
  170. * */
  171. // public static void main(String[] args){
  172. // ByteArrayOutputStream output = new ByteArrayOutputStream();
  173. // // 创建PDF文档对象 页大小为A4
  174. // Document document = new Document(PageSize.A4, 20, 20, 20, 20);
  175. System.err.println("123");
  176. // try {
  177. //
  178. // // 创建PDF写入器
  179. // PdfWriter.getInstance(document, output);
  180. // // 打开文档对象
  181. // document.open();
  182. //
  183. // InputStream is = new FileInputStream(new File("D:\\123.xml"));
  184. // ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//输出流
  185. // byte[] bytes = new byte[1024];
  186. // int len;
  187. // while ((len = is.read(bytes)) != -1) {
  188. // outputStream.write(bytes, 0, len);//将读到的字节写入输出流
  189. // }
  190. // is.close();
  191. // String content=outputStream.toString();
  192. // outputStream.close();
  193. //
  194. //
  195. //
  196. //
  197. // Paragraph paragraph1 = new Paragraph();
  198. // Chunk timeChunk = new Chunk(content);
  199. //
  200. // paragraph1.add(timeChunk);
  201. // document.add(paragraph1);
  202. // document.close();
  203. // output.close();
  204. // FileOutputStream fileOutputStream = new FileOutputStream("D:\\123.pdf");
  205. // fileOutputStream.write(output.toByteArray());
  206. // }catch (Exception e){
  207. // System.err.println(e);
  208. // }
  209. // }
  210. //public static void main(String[] args) throws FileNotFoundException {
  211. // String fileEnd = "xlsx";
  212. // try {
  213. FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\333.pdf"));
  214. // ByteArrayOutputStream output = new ByteArrayOutputStream();
  215. // InputStream fileInput = new FileInputStream(new File("D:\\qqqq.xlsx"));
  216. //
  217. // IConverter converter = LocalConverter.builder().build();
  218. //
  219. // if(fileEnd.equals("doc")){
  220. // converter.convert(fileInput)
  221. // .as(DocumentType.DOC)
  222. // .to(output)
  223. // .as(DocumentType.PDF).execute();
  224. //
  225. // } else if(fileEnd.equals("docx")){
  226. // converter.convert(fileInput)
  227. // .as(DocumentType.DOCX)
  228. // .to(output)
  229. // .as(DocumentType.PDF).execute();
  230. // }
  231. // else if(fileEnd.equals("xlsx")){
  232. // converter.convert(fileInput)
  233. // .as(DocumentType.XLSX)
  234. // .to(output)
  235. // .as(DocumentType.PDF).execute();
  236. // }
  237. // else if(fileEnd.equals("xls")){
  238. // converter.convert(fileInput)
  239. // .as(DocumentType.XLS)
  240. // .to(output)
  241. // .as(DocumentType.PDF).execute();
  242. // }
  243. // output.close();
  244. // fileInput.close();
  245. // FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\daqyqqqq.pdf"));
  246. // fileOutputStream.write(output.toByteArray());
  247. // fileOutputStream.close();
  248. // } catch (Exception e) {
  249. // System.err.println(e);
  250. // }finally {
  251. // }
  252. //
  253. //}
  254. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/265971
推荐阅读
相关标签
  

闽ICP备14008679号