Springboot WORD转换为PDF——Aspose方式

朱雀 2023-10-10 20:57 96阅读 0赞

Springboot WORD转换为PDF——Aspose方式

一、准备相关资源

1.下载转换的Aspose资源包

网盘地址
提取码:dddc

2. 下载License文件去除水印

网盘地址
提取码:yesg

二、配置maven

1. 将下载下来的jar包放在项目根目录中

在这里插入图片描述

2.将下载下来的license.xml放在根目录的resources下

在这里插入图片描述

3. 配置pom.xml

  1. <dependency>
  2. <groupId>com.aspose</groupId>
  3. <artifactId>aspose-words</artifactId>
  4. <version>15.8.0</version>
  5. <scope>system</scope>
  6. <systemPath>${
  7. project.basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
  8. </dependency>

三、编写代码

  1. public class Word2PdfAsposeUtil {
  2. public static boolean getLicense() {
  3. boolean result = false;
  4. InputStream is = null;
  5. try {
  6. ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  7. org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:license.xml");
  8. is = resources[0].getInputStream();
  9. // Resource resource = new ClassPathResource("license.xml");
  10. // is = resource.getInputStream();
  11. //InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
  12. License aposeLic = new License();
  13. aposeLic.setLicense(is);
  14. result = true;
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. } finally {
  18. if (is != null) {
  19. try {
  20. is.close();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. }
  26. return result;
  27. }
  28. /**
  29. * word 转pdf
  30. *
  31. * @param inPath word路径
  32. * @param outPath pdf路径
  33. * @return
  34. */
  35. public static boolean doc2pdf(String inPath, String outPath) {
  36. if (!getLicense()) {
  37. // 验证License 若不验证则转化出的pdf文档会有水印产生
  38. return false;
  39. }
  40. FileOutputStream os = null;
  41. try {
  42. long old = System.currentTimeMillis();
  43. File file = new File(outPath); // 新建一个空白pdf文档
  44. os = new FileOutputStream(file);
  45. Document doc = new Document(inPath); // Address是将要被转化的word文档
  46. doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
  47. // EPUB, XPS, SWF 相互转换
  48. long now = System.currentTimeMillis();
  49. System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
  50. } catch (Exception e) {
  51. e.printStackTrace();
  52. return false;
  53. } finally {
  54. if (os != null) {
  55. try {
  56. os.flush();
  57. os.close();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. return false;
  61. }
  62. }
  63. }
  64. return true;
  65. }

四、编写main方法测试

  1. public static void main(String[] args) {
  2. doc2pdf("E:\\123\\1.docx","E:\\123\\1.pdf");
  3. }

发表评论

表情:
评论列表 (有 0 条评论,96人围观)

还没有评论,来说两句吧...

相关阅读