doc或docx(word)或image类型文件批量转PDF脚本

打印 上一主题 下一主题

主题 943|帖子 943|积分 2829

doc或docx(word)或image类型文件批量转PDF脚本

1.实际生产环境中遇到文件展示只能适配PDF版本的文件,奈何一万个文件有七千个都是word或者image类型的,由此搞个脚本批量转换下上传至OSS,为前端提供数据支撑。
2.环境准备,这里使用的是aspose-words-18.6-jdk16-crack.jar工具包,资源包就不提供了,网上百度一下即可。
3.javaMaven项目,jdk1.8.maven3.6

4.使用aspose-words-18.6-jdk16-crack.jar工具包会产生水印,需要配置resources下去除水印配置:
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <License>
  3.     <Data>
  4.         <Products>
  5.             <Product>Aspose.Total for Java</Product>
  6.             <Product>Aspose.Words for Java</Product>
  7.         </Products>
  8.         <EditionType>Enterprise</EditionType>
  9.         <SubscriptionExpiry>20991231</SubscriptionExpiry>
  10.         <LicenseExpiry>20991231</LicenseExpiry>
  11.         <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  12.     </Data>
  13.     <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
  14. </License>
复制代码
license.xml5.工具类编写:
  1. package org.utiles.dongl.tools;
  2. import com.aspose.words.License;
  3. import com.aspose.words.SaveFormat;
  4. import com.itextpdf.text.*;
  5. import com.itextpdf.text.pdf.PdfWriter;
  6. import org.apache.log4j.Logger;
  7. import org.utiles.dongl.comment.WordTranPDF;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.util.*;
  13. import java.util.List;
  14. /**
  15. * @ClassName: FileTranPDFTool
  16. * @Description TODO
  17. * @Author: 东霖
  18. * @Date: 2022/7/23 10:50
  19. * @Version 1.0
  20. **/
  21. public class FileTranPDFTool {
  22.     private static Logger logger = Logger.getLogger(FileTranPDFTool.class);
  23.     public static boolean getLicense() {
  24.         boolean result = false;
  25.         try {
  26.             InputStream is = WordTranPDF.class.getClassLoader().getResourceAsStream("\\license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
  27.             License aposeLic = new License();
  28.             aposeLic.setLicense(is);
  29.             result = true;
  30.         } catch (Exception e) {
  31.             e.printStackTrace();
  32.         }
  33.         return result;
  34.     }
  35.     /**
  36.      * ImageToPDF
  37.      * 支持类型:jpg/tif/..
  38.      *
  39.      * @param source
  40.      * @param target
  41.      */
  42.     public static void ImageToPDF(String source, String target) {
  43.         Document document = new Document();
  44.         //设置文档页边距
  45.         document.setMargins(0, 0, 0, 0);
  46.         FileOutputStream fos = null;
  47.         try {
  48.             fos = new FileOutputStream(target);
  49.             PdfWriter.getInstance(document, fos);
  50.             //打开文档
  51.             document.open();
  52.             //获取图片的宽高
  53.             Image image = Image.getInstance(source);
  54.             float imageHeight = image.getScaledHeight();
  55.             float imageWidth = image.getScaledWidth();
  56.             //设置页面宽高与图片一致
  57.             Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
  58.             document.setPageSize(rectangle);
  59.             //图片居中
  60.             image.setAlignment(Image.ALIGN_CENTER);
  61.             //新建一页添加图片
  62.             document.newPage();
  63.             document.add(image);
  64.         } catch (Exception ioe) {
  65.             System.out.println(ioe.getMessage());
  66.         } finally {
  67.             //关闭文档
  68.             document.close();
  69.             try {
  70.                 fos.flush();
  71.                 fos.close();
  72.             } catch (IOException e) {
  73.                 e.printStackTrace();
  74.             }
  75.         }
  76.     }
  77.     /**
  78.      * word 文档类型转pdf
  79.      *
  80.      * @param inPath
  81.      * @param outPath
  82.      * @return
  83.      */
  84.     public static boolean doc2pdf(String inPath, String outPath) {
  85.         if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
  86.             return false;
  87.         }
  88.         FileOutputStream os = null;
  89.         try {
  90.             File file = new File(outPath); // 新建一个空白pdf文档
  91.             os = new FileOutputStream(file);
  92.             com.aspose.words.Document doc = new com.aspose.words.Document(inPath); // Address是将要被转化的word文档
  93. //            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
  94.             doc.save(os, SaveFormat.DOCX);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
  95.             // EPUB, XPS, SWF 相互转换
  96.         } catch (Exception e) {
  97.             e.printStackTrace();
  98.             return false;
  99.         } finally {
  100.             if (os != null) {
  101.                 try {
  102.                     os.flush();
  103.                     os.close();
  104.                 } catch (IOException e) {
  105.                     e.printStackTrace();
  106.                 }
  107.             }
  108.         }
  109.         return true;
  110.     }
  111.     /**
  112.      * 遍历指定目录取文件名称
  113.      *
  114.      * @param foldPath 文件目录绝对路径
  115.      * @return
  116.      */
  117.     public static List<String> listFileName(String foldPath) {
  118.         List<String> listFiles = new ArrayList<>();
  119.         //创建文件对象
  120.         File f = new File(foldPath);
  121.         //列出文件名称存入数组
  122.         File[] files = f.listFiles();
  123.         for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
  124.             listFiles.add(files[i].getName());
  125.         }
  126.         return listFiles;
  127.     }
  128.     /**
  129.      * 删除指定文件
  130.      * @param filePath
  131.      * @return
  132.      */
  133.     public static boolean deleteByFilePath(String filePath) {
  134.         File file = new File(filePath);
  135.         return file.delete();
  136.     }
  137.     /**
  138.      * 遍历指定目录取文件名称并接入路径
  139.      *
  140.      * @param oldPath 遍历文件目录绝对路径,也是要删除的文件目录
  141.      * @return
  142.      */
  143.     public static Map<String, String> listFileNameAndPath(String oldPath) {
  144.         Map<String, String> listFiles = new HashMap();
  145.         //创建文件对象
  146.         File f = new File(oldPath);
  147.         //列出文件名称存入数组
  148.         File[] files = f.listFiles();
  149.         for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
  150.             listFiles.put(files[i].getPath(), files[i].getName());
  151.         }
  152.         return listFiles;
  153.     }
  154.     /**
  155.      * 获取指定文件目录文件大小为0Size的
  156.      * @param foldPath
  157.      * @return
  158.      */
  159.     public static Integer getFileSize(String foldPath,String newFoldPath) {
  160.         int j=1;
  161.         //创建文件对象
  162.         File file = new File(foldPath);
  163.         File[] files = file.listFiles();
  164.         for (int i = 0; i < files.length; i++) {
  165.             if (files[i].length()==0){
  166.                 Boolean aBoolean = WriteToFileExample.moveFileToTarget("D:\\OSS\\ghwb\\ghksj_1_copy\\《金东区卫生健康事业发展“十四五”规划》.pdf", newFoldPath+files[i].getName(),null);
  167.                 if (aBoolean==true){
  168.                     j++;
  169.                     logger.info("移动:"+files[i].getPath()+"到"+newFoldPath);
  170.                 }
  171.                 System.out.println(files[i].getPath());
  172.             }
  173.         }
  174.         return j;
  175.     }
  176.     /**
  177.      * 文件对比删除重复文件
  178.      * @param oldFileNames
  179.      * @param newPath 对比文件目录
  180.      * @return
  181.      */
  182.     public static Integer deleteByFileName(Map<String, String> oldFileNames, String newPath) {
  183.         int j = 0;
  184.         List<String> newListNames = listFileName(newPath);
  185.         for (Map.Entry<String, String> entry : oldFileNames.entrySet()) {
  186.             for (int i = 0; i < newListNames.size(); i++) {
  187.                 String value = entry.getValue();
  188.                 String s = newListNames.get(i);
  189.                 if (value.substring(0,value.lastIndexOf(".")).equals(s.substring(0,s.lastIndexOf(".")))) {
  190.                     boolean b = deleteByFilePath(entry.getKey());
  191.                     if (b==true){
  192.                         logger.info("成功删除指定文件:"+entry.getKey()+",共计:"+j+"个");
  193.                         j++;
  194.                     }else{
  195.                         logger.error("指定文件不存在:"+entry.getKey());
  196.                     }
  197.                 }
  198.             }
  199.         }
  200.         return j;
  201.     }
  202.     public static void main(String[] args) {
  203.         //文件对比删除
  204.         Map<String, String> map = listFileNameAndPath("D:\\OSS\\ghwb\\word");
  205.         int b = deleteByFileName(map, "D:\\OSS\\ghwb\\ghksj - 副本");
  206.         //word转pdf
  207.         doc2pdf("D:\\OSS\\ghwb\\13c5ad939a0b2001.doc",
  208.                 "D:\\OSS\\ghwb\\doc2docx\\13c5ad939a0b2001.docx");
  209.         //移动文件size为0的数据到指定文件夹
  210. //        getFileSize("D:\\OSS\\ghwb\\ghksj_3_copy","D:\\OSS\\ghwb\\test");
  211.     }
  212. }
复制代码
WordORImageTranPDF 6.逻辑代码:
  1. package org.utiles.dongl.comment;
  2. import org.apache.log4j.Logger;
  3. import org.utiles.dongl.tools.FileTranPDFTool;
  4. import org.utiles.dongl.tools.WriteToFileExample;
  5. import java.io.*;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import static org.utiles.dongl.tools.FileTranPDFTool.doc2pdf;
  9. /**
  10. * @ClassName: WordTranPDF
  11. * @Description TODO
  12. * @Author: 东霖
  13. * @Date: 2022/7/22 8:55
  14. * @Version 1.0
  15. **/
  16. public class WordTranPDF {
  17.     private static Logger logger = Logger.getLogger(WordTranPDF.class);
  18.     /**
  19.      * 获取指定文件路径下所有文件对象
  20.      *
  21.      * @param inFilePath
  22.      * @return
  23.      */
  24.     public static Map<String, String> getFilePathName(String inFilePath,String replacePathOld
  25.             ,String replacePathNew,String wjjl,String pdfToPath) {
  26.         Map<String, String> fileList = new HashMap();
  27.         //创建文件对象
  28.         File f = new File(inFilePath);
  29.         //列出文件名称存入数组
  30.         File[] files = f.listFiles();
  31.         for (int i = 0; i < files.length; i++) {
  32.             if (files[i].getName().endsWith("docx") || files[i].getName().endsWith("doc")
  33.                     || files[i].getName().endsWith("wps") || files[i].getName().endsWith("rtf"))
  34.             {
  35. //                String str=files[i].getPath().substring(0,files[i].getPath().lastIndexOf(".")+1)+"pdf";
  36.                 String str=files[i].getPath().substring(0,files[i].getPath().lastIndexOf(".")+1)+"docx";
  37.                 fileList.put(files[i].getPath()+"&"+"word",str.replace(replacePathOld,replacePathNew));
  38. //                logger.info("当前文件路径为:"+files[i].getPath());
  39.             } else if (files[i].getName().endsWith(".png") || files[i].getName().endsWith(".jpg") || files[i].getName().endsWith(".gif")
  40.                     || files[i].getName().endsWith(".jpeg") || files[i].getName().endsWith(".tif"))
  41.             {
  42.                 String str=files[i].getPath().substring(0,files[i].getPath().lastIndexOf(".")+1)+"pdf";
  43.                 fileList.put(files[i].getPath()+"&"+"image", str.replace(replacePathOld,replacePathNew));
  44. //                logger.info("当前文件路径为:"+files[i].getPath());
  45.             }else if(files[i].getName().endsWith(".pdf")) {
  46.                 WriteToFileExample.moveFileToTarget(files[i].getPath(),pdfToPath+files[i].getName(),"");
  47.                 logger.info("移动:"+files[i].getPath()+"到"+pdfToPath);
  48.             }else{
  49.                 WriteToFileExample.writeFileSQL("当前文件无法转换:"+files[i].getPath(),wjjl);
  50.             }
  51.         }
  52.         return fileList;
  53.     }
  54.     public static void start(Map<String, String> hashMap) throws InterruptedException {
  55.         long old = System.currentTimeMillis();
  56.         int j = 0;
  57.         for (Map.Entry<String, String> entry : hashMap.entrySet()) {
  58. //            doc2pdf(entry.getKey(),entry.getValue());
  59.             String[] split = entry.getKey().split("&");
  60.             if(split[1].equals("word")){
  61.                 System.out.println(entry.getValue());
  62.                 doc2pdf(split[0],entry.getValue());
  63.                 Thread.sleep(Long.parseLong("15"));
  64.             }else if (split[1].equals("image")){
  65.                 FileTranPDFTool.ImageToPDF(split[0],entry.getValue());
  66.                 Thread.sleep(Long.parseLong("15"));
  67.             }else {
  68. //                break;
  69.             }
  70.             j++;
  71.             logger.info("转换第:"+j+"个!"+"文件名称为:"+entry.getKey());
  72.         }
  73.         long now = System.currentTimeMillis();
  74.         logger.info("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
  75.         logger.info("共转换:" + j + "个文件!");
  76.     }
  77.     public static void main(String[] args) throws InterruptedException {
  78.         /**
  79.          * inFilePath: 需要转换的文件夹路径
  80.          * replacePathOld: 抓换后的文件要写入新文件,直接替换文件的上级目录关键字即可
  81.          * replacePathNew: 新的文件父路径
  82.          * wjjl: 不能转换的文件记录位置及记录名称
  83.          * pdfToPath:当文件中已有pdf不用抓换的需配置文件留存方向。会从原文件目录移动至新文件目录
  84.          */
  85.         Map<String, String> filePathName = getFilePathName("D:\\OSS\\ghwb\\doc11",
  86.                 "doc11","doc2docx",
  87.                 "D:\\OSS\\ghwb\"+System.currentTimeMillis()+".txt"
  88.         ,"D:\\OSS\\yjbg\\gjxxzx\\ghksj_copy\");
  89.         start(filePathName);
  90.     }
  91. }
复制代码
View Code 7.上述就是word或者image类型的批量脚本,可以在工具类中单元测试之后在使用批量逻辑代码。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

魏晓东

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表