Java实现xlsx doc ppt png 转pdf

在我们工作中各种文件转为pdf进行预览这是一个非常常见的需求,我这里将我在工作的使用的解决方法分享出来

需要引入的jar包和linux相关的字体文件可以私信我

相关代码:

public class OfficeUtil {

   private static final List<String> wordFileType = Arrays.asList("doc", "docx");

   private static final List<String> excelFileType = Arrays.asList("xlsx", "xls");

   private static final List<String> imageFileType = Arrays.asList("png", "jpg");

   private static final List<String> pptFileType = Arrays.asList("ppt", "pptx");
   private static final String textType = "txt";

   /**
    * office文件转pdf
    *
    * @param suffix     文件后缀名
    * @param sourcePath 源文件绝对路径
    * @param pdfPath    pdf文件绝对路径
    * @return
    */
   public static void officeToPdf(String suffix, String sourcePath, String pdfPath) throws Exception {
      font();
      //判断后缀
      if (wordFileType.contains(suffix)) {
         wordToPdf(sourcePath, pdfPath);
      } else if (excelFileType.contains(suffix)) {
         excelToPdf(sourcePath, pdfPath);
      } else if (imageFileType.contains(suffix)) {
         imageToPdf(Arrays.asList(sourcePath), pdfPath);
      } else if (pptFileType.contains(suffix)) {
         pptTopdf(sourcePath, pdfPath);
      } else if (textType.equals(suffix)) {
         PdfUtil.text2pdf(sourcePath, pdfPath);
      }
   }

   /**
    * office文件转pdf
    *
    * @param suffix      文件后缀名
    * @param inputStream 源文件流
    * @param pdfPath     pdf文件绝对路径
    * @return
    */
   public static void officeToPdf(String suffix, InputStream inputStream, String pdfPath) throws Exception {
      font();
      //判断后缀
      if (wordFileType.contains(suffix)) {
         wordToPdf(inputStream, pdfPath);
      } else if (excelFileType.contains(suffix)) {
         excelToPdf(inputStream, pdfPath);
      } else if (imageFileType.contains(suffix)) {
         imageToPdf(inputStream, pdfPath);
      } else if (pptFileType.contains(suffix)) {
         pptTopdf(inputStream, pdfPath);
      } else if (textType.equals(suffix)) {
         PdfUtil.text2pdf(inputStream, pdfPath);
      }
   }
   
   /**
    * word转pdf(绝对路径)
    *
    * @param wordPath
    * @param pdfPath
    * @return
    * @throws Exception
    */
   public static String wordToPdf(String wordPath, String pdfPath) {
      FileOutputStream os = null;
      try {
         if (!getLicense()) {
            System.out.println("License验证不通过...");
            return null;
         }
         //生成一个空的PDF文件
         File file = new File(pdfPath);
         os = new FileOutputStream(file);

         //要转换的word文件
         LoadOptions loadOptions = new LoadOptions();
         loadOptions.setEncoding(StandardCharsets.UTF_8);
         Document doc = new Document(wordPath, loadOptions);
         doc.save(os, SaveFormat.PDF);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (os != null) {
            try {
               os.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }

      return null;
   }

   /**
    * word转pdf(绝对路径)
    *
    * @param inputStream
    * @param pdfPath
    * @return
    * @throws Exception
    */
   public static String wordToPdf(InputStream inputStream, String pdfPath) {
      FileOutputStream os = null;
      try {
         if (!getLicense()) {
            System.out.println("License验证不通过...");
            return null;
         }
         //生成一个空的PDF文件
         File file = new File(pdfPath);
         os = new FileOutputStream(file);

         //要转换的word文件
         LoadOptions loadOptions = new LoadOptions();
         loadOptions.setEncoding(StandardCharsets.UTF_8);
         Document doc = new Document(inputStream, loadOptions);
         doc.save(os, SaveFormat.PDF);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (os != null) {
            try {
               os.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }

      return null;
   }


   public static void convertExcelToPdf(String inputFilePath, String outputFilePath) {
      try {
         // 加载 Excel 文件
         Workbook workbook = new Workbook(inputFilePath);

         // 将 Excel 转成 PDF
         PdfSaveOptions options = new PdfSaveOptions();
         options.setOnePagePerSheet(true);
         workbook.save(outputFilePath, options);
         System.out.println("______________________");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }



   /**
    * excel 转为pdf 绝对路径。
    *
    * @param excelPath excel文件
    * @param pdfPath   pdf 输出文件目录
    */
   public static void excelToPdf(String excelPath, String pdfPath) {
      if (!getLicense1()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
         return;
      }
      FileOutputStream fileOS = null;
      try {
         Workbook wb = new Workbook(excelPath);// 原始excel路径

         fileOS = new FileOutputStream(pdfPath);
         PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
         pdfSaveOptions.setOnePagePerSheet(true);
         int[] autoDrawSheets = {3};
         //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
         autoDraw(wb, autoDrawSheets);
         int[] showSheets = {0};
         //隐藏workbook中不需要的sheet页。
         printSheetPage(wb, showSheets);
         wb.save(fileOS, pdfSaveOptions);
         fileOS.flush();
         System.out.println("chengg");
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (fileOS != null) {
            try {
               fileOS.close();
            } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
         }
      }
   }

   /**
    * excel 转为pdf 绝对路径。
    *
    * @param inputStream excel文件流
    * @param pdfPath     pdf 输出文件目录
    */
   public static void excelToPdf(InputStream inputStream, String pdfPath) {
      if (!getLicense1()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
         return;
      }
      FileOutputStream fileOS = null;
      try {
         Workbook wb = new Workbook(inputStream);// 原始excel路径

         fileOS = new FileOutputStream(pdfPath);
         PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
         pdfSaveOptions.setOnePagePerSheet(true);
         int[] autoDrawSheets = {3};
         //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
         autoDraw(wb, autoDrawSheets);
         int[] showSheets = {0};
         //隐藏workbook中不需要的sheet页。
         printSheetPage(wb, showSheets);
         wb.save(fileOS, pdfSaveOptions);
         fileOS.flush();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (fileOS != null) {
            try {
               fileOS.close();
            } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
         }
      }
   }


   /**
    * 图片文件转PDF
    *
    * @param imagePaths 图片绝对路径list集合
    * @return
    */
   /**
    * 图片转PDF
    *
    * @param imagePathList
    * @param pdfPath
    * @return
    */
   public static String imageToPdf(List<String> imagePathList,
                           String pdfPath) {
      //Document doc = new Document(PageSize.A4, 20, 20, 20, 20); // new一个pdf文档
      com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
      try {
         PdfWriter.getInstance(doc, new FileOutputStream(pdfPath)); // pdf写入
         doc.open();// 打开文档
         for (int i = 0; i < imagePathList.size(); i++) { // 循环图片List,将图片加入到pdf中
            doc.newPage(); // 在pdf创建一页
            Image png1 = Image.getInstance(imagePathList.get(i)); // 通过文件路径获取image
            float heigth = png1.getHeight();
            float width = png1.getWidth();
            int percent = getPercent2(heigth, width);
            png1.setAlignment(Image.MIDDLE);
            png1.scalePercent(percent + 3);// 表示是原来图像的比例;
            doc.add(png1);
         }
         doc.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (DocumentException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      File mOutputPdfFile = new File(pdfPath); // 输出流
      if (!mOutputPdfFile.exists()) {
         mOutputPdfFile.deleteOnExit();
         return null;
      }
      try {
         mOutputPdfFile.createNewFile();
      } catch (IOException e) {
         e.printStackTrace();
      }

      return mOutputPdfFile.getName(); // 反回文件输出流
   }
   /**
    * 图片文件转PDF
    *
    * @param imagePaths 图片绝对路径list集合
    * @return
    */
   /**
    * 图片转PDF
    *
    * @param inputStream
    * @param pdfPath
    * @return
    */
   public static String imageToPdf(InputStream inputStream,
                           String pdfPath) {
      try {
         // 创建新的 Document 对象
         com.itextpdf.text.Document document = new com.itextpdf.text.Document();

         // 创建 PdfWriter 对象将生成的 PDF 写入到文件中
         PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
         // 打开 Document 对象
         document.open();
         // 读取图片流
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         byte[] buffer = new byte[4096];
         int bytesRead;
         while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
         }
         byte[] bytes = byteArrayOutputStream.toByteArray();
         // 创建 Image 对象
         Image image = Image.getInstance(bytes);
         float heigth = image.getHeight();
         float width = image.getWidth();
         int percent = getPercent2(heigth, width);
         image.setAlignment(Image.MIDDLE);
         image.scalePercent(percent + 3);// 表示是原来图像的比例;
         // 将图片添加到文档
         document.add(image);
         // 关闭 Document 对象
         document.close();
         System.out.println("图片已成功转换为 PDF!");
      } catch (Exception e) {
         e.printStackTrace();
      }

      return null; // 反回文件输出流
   }


   private static void font() {
      //获取当前java运行
      String os = System.getProperty("os.name");
      if (os != null && os.toLowerCase().startsWith("windows")) {
         //  log.info("当前是windows");

      } else if (os != null && os.toLowerCase().startsWith("linux")) {
         //  log.info("当前是linux系统");
         FontSettings.getDefaultInstance().setFontsFolder(File.separator + "usr"
               + File.separator + "share" + File.separator + "fonts" + File.separator, true);

      }
   }

   /**
    * 返回当前环境,并返回地址
    *
    * @return
    */
   public static String getEnvAttribute(String pdfPath) {
      String newFilePath=pdfPath;
      String os = System.getProperty("os.name").toLowerCase();
      if (os.contains("win")) {
         System.out.println("当前环境是 Windows");
         newFilePath="D:"+newFilePath;
      } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
         System.out.println("当前环境是 Linux");
      } else {
         System.out.println("无法确定当前环境");
      }
      return newFilePath.replace("/", File.separator).replace("\\", File.separator);
   }

   /**
    * PPT转PDF
    *
    * @param
    */
   public static String pptTopdf(String pptPath, String pdfPath) {
      // 验证License
      if (!getLicense2()) {
         return "PDF格式转化失败";
      }
      try {
         long old = System.currentTimeMillis();

         //文件操作
         File file = new File(pdfPath); // 新建一个空白pdf文档
         com.aspose.slides.Presentation pres = new com.aspose.slides.Presentation(pptPath);//输入pdf路径

         FileOutputStream fileOS = new FileOutputStream(file);
         pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
         fileOS.close();

         long now = System.currentTimeMillis();
         System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + file.getPath()); //转化过程耗时
         return file.getName();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return "PDF格式转化失败";
   }

   /**
    * PPT转PDF
    *带进度
    * @param
    */
   public static String pptTopdf(InputStream inputStream, String pdfPath) {
      // 验证License
      if (!getLicense2()) {
         return "PDF格式转化失败";
      }
      try {
         long old = System.currentTimeMillis();

         //文件操作
         File file = new File(pdfPath); // 新建一个空白pdf文档
         com.aspose.slides.Presentation pres = new com.aspose.slides.Presentation(inputStream);//输入pdf路径

         int totalSlides = pres.getSlides().size();
         int completedSlides = 0;


         // 开始转换
         for (int i = 0; i < totalSlides; i++) {
            // 在这里处理每一页的转换逻辑
            completedSlides++;

            // 打印进度
            double progress = (double) completedSlides / totalSlides * 100;
            System.out.println("Conversion progress: " + progress + "%");
         }

         FileOutputStream fileOS = new FileOutputStream(file);
         pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf, new PdfOptions());
         fileOS.close();

         long now = System.currentTimeMillis();
         //转化过程耗时
         System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + file.getPath());
         return file.getName();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return "PDF格式转化失败";
   }


   /**
    * 设置打印的sheet 自动拉伸比例
    *
    * @param wb
    * @param page 自动拉伸的页的sheet数组
    */
   public static void autoDraw(Workbook wb, int[] page) {
      if (null != page && page.length > 0) {
         for (int i = 0; i < page.length; i++) {
            wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
            wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
         }
      }
   }

   /**
    * 隐藏workbook中不需要的sheet页。
    *
    * @param wb
    * @param page 显示页的sheet数组
    */
   public static void printSheetPage(Workbook wb, int[] page) {
      for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
         wb.getWorksheets().get(i).setVisible(false);
      }
      if (null == page || page.length == 0) {
         wb.getWorksheets().get(0).setVisible(true);
      } else {
         for (int i = 0; i < page.length; i++) {
            wb.getWorksheets().get(i).setVisible(true);
         }
      }
   }


   public static int getPercent2(float h, float w) {
      int p = 0;
      float p2 = 0.0f;
      p2 = 530 / w * 100;
      p = Math.round(p2);
      return p;
   }

   /**
    * 获取license 去除水印
    *
    * @return
    */
   public static boolean getLicense() {
      boolean result = false;

      try {
//    "classpath:/license.xml"
         InputStream is = OfficeUtil.class.getClassLoader()
               .getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
         License aposeLic = new License();
         aposeLic.setLicense(is);
         result = true;

      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
   }

   /**
    * 获取license 去除水印
    *
    * @return
    */
   public static boolean getLicense1() {
      boolean result = false;
      try {
         InputStream is = OfficeUtil.class.getClassLoader()
               .getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
         com.aspose.cells.License aposeLic = new com.aspose.cells.License();
         aposeLic.setLicense(is);
         result = true;
      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
   }

   /**
    * 获取license 去除水印
    *
    * @return
    */
   public static boolean getLicense2() {
      boolean result = false;
      try {
         InputStream is = OfficeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
         com.aspose.slides.License aposeLic = new com.aspose.slides.License();
         aposeLic.setLicense(is);
         result = true;

      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
   }

}

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
实现文件分类,你需要先定义一些分类的标准或规则,比如按文件类型、按文件大小、按文件名称等等。这里以按文件类型分类为例,给出Python代码示例: ```python import os import shutil # 定义文件分类的规则,这里按文件类型分类 rules = { "文档": [".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx", ".pdf", ".txt"], "图片": [".jpg", ".jpeg", ".png", ".gif", ".bmp"], "音频": [".mp3", ".wav", ".wma"], "视频": [".mp4", ".avi", ".rmvb", ".mkv"], } # 定义文件夹分类的目标路径 base_path = "E:/Downloads" target_paths = { "文档": os.path.join(base_path, "Documents"), "图片": os.path.join(base_path, "Pictures"), "音频": os.path.join(base_path, "Music"), "视频": os.path.join(base_path, "Videos"), } # 遍历目标文件夹中的所有文件 for filename in os.listdir(base_path): filepath = os.path.join(base_path, filename) # 判断是否为文件 if os.path.isfile(filepath): # 获取文件扩展名 ext = os.path.splitext(filename)[-1] # 根据规则分类文件 for target_path, exts in rules.items(): if ext in exts: # 如果分类目录不存在则创建 if not os.path.exists(target_paths[target_path]): os.mkdir(target_paths[target_path]) # 移动文件到分类目录 shutil.move(filepath, os.path.join(target_paths[target_path], filename)) break ``` 以上代码将遍历指定目录中的所有文件,根据文件类型规则分类后移动到对应的目标目录中。你可以根据自己的需求,修改代码中的分类规则和目标路径。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赚钱买高仿AJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值