在我们工作中各种文件转为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; } }