springboot各种格式转pdf 您所在的位置:网站首页 exelce转pdf springboot各种格式转pdf

springboot各种格式转pdf

#springboot各种格式转pdf| 来源: 网络整理| 查看: 265

添加依赖

com.documents4j documents4j-local 1.0.3 com.documents4j documents4j-transformer-msoffice-word 1.0.3 com.itextpdf itextpdf 5.5.10

测试方法

package com.ruoyi.mlogin.util; import com.documents4j.api.DocumentType; import com.documents4j.api.IConverter; import com.documents4j.job.LocalConverter; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfWriter; import java.io.*; import java.net.MalformedURLException; /** * @author cai * @version 1.0 * @date 2021/1/4 14:58 */ public class Topdf { /** * 转pdf doc docx xls xlsx * @param path */ public void docTopdf(String path) { File inputWord = new File("C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.docx"); File outputFile = new File("C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.pdf"); try { InputStream docxInputStream = new FileInputStream(inputWord); OutputStream outputStream = new FileOutputStream(outputFile); IConverter converter = LocalConverter.builder().build(); String fileTyle=path.substring(path.lastIndexOf("."),path.length());//获取文件类型 if(".docx".equals(fileTyle)){ converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute(); }else if(".doc".equals(fileTyle)){ converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute(); }else if(".xls".equals(fileTyle)){ converter.convert(docxInputStream).as(DocumentType.XLS).to(outputStream).as(DocumentType.PDF).execute(); }else if(".xlsx".equals(fileTyle)){ converter.convert(docxInputStream).as(DocumentType.XLSX).to(outputStream).as(DocumentType.PDF).execute(); } outputStream.close(); System.out.println("pdf转换成功"); } catch (Exception e) { e.printStackTrace(); } } /** * * 生成pdf文件 * 需要转换的图片路径的数组 */ public static void main(String[] args) { try { String imagesPath = "C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.jpg"; File file = new File("C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.pdf"); // 第一步:创建一个document对象。 Document document = new Document(); document.setMargins(0, 0, 0, 0); // 第二步: // 创建一个PdfWriter实例, PdfWriter.getInstance(document, new FileOutputStream(file)); // 第三步:打开文档。 document.open(); // 第四步:在文档中增加图片。 if (true) { Image img = Image.getInstance(imagesPath); img.setAlignment(Image.ALIGN_CENTER); // 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效 document.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); document.newPage(); document.add(img); //下面是对应一个文件夹的图片 // File files = new File(imagesPath); // String[] images = files.list(); // int len = images.length; // // for (int i = 0; i < len; i++) // { // if (images[i].toLowerCase().endsWith(".bmp") // || images[i].toLowerCase().endsWith(".jpg") // || images[i].toLowerCase().endsWith(".jpeg") // || images[i].toLowerCase().endsWith(".gif") // || images[i].toLowerCase().endsWith(".png")) { // String temp = imagesPath + "\\" + images[i]; // Image img = Image.getInstance(temp); // img.setAlignment(Image.ALIGN_CENTER); // // 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效 // document.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); // document.newPage(); // document.add(img); // } // } // 第五步:关闭文档。 document.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (BadElementException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } }

ppt转pdf

com.ruoyi ruoyi-common com.ruoyi ruoyi-system com.ruoyi ruoyi-lygdj cn.hutool hutool-all 5.3.10 com.documents4j documents4j-local 1.0.3 com.documents4j documents4j-transformer-msoffice-word 1.0.3 org.apache.poi poi 4.1.1 org.apache.poi poi-ooxml 4.1.1 org.apache.poi poi-scratchpad 4.1.1 com.itextpdf itextpdf 5.5.13.1 org.apache.pdfbox fontbox 2.0.18 org.apache.pdfbox pdfbox 2.0.18 com.itextpdf itext-asian 5.2.0 org.apache.xmlgraphics batik-bridge 1.12 javax.xml.bind jaxb-api 2.3.0 javax.activation activation 1.1 org.glassfish.jaxb jaxb-runtime 2.3.0-b170127.1453 package com.ruoyi.mlogin.util; import com.itextpdf.text.Document; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfWriter; import org.apache.poi.hslf.usermodel.*; import org.apache.poi.openxml4j.util.ZipSecureFile; import org.apache.poi.xslf.usermodel.*; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; public class Ppttopdf { public static void main(String[] args) { //输入ppt的路径 File pptFile = new File("D:\\file\\ppt1.pptx"); List files = pptx2Png(pptFile); png2Pdf(files,"D:\\file\\ppt1.pdf"); } public static List ppt2Png(File pptFile) { List pngFileList = new ArrayList(); long startTime = System.currentTimeMillis(); FileInputStream is = null; // 将ppt文件转换成每一帧的图片 HSLFSlideShow ppt = null; try { ZipSecureFile.setMinInflateRatio(-1.0d); is = new FileInputStream(pptFile); ppt = new HSLFSlideShow(is); int idx = 1; Dimension pageSize = ppt.getPageSize(); double image_rate = 1.0; int imageWidth = (int) Math.floor(image_rate * pageSize.getWidth()); int imageHeight = (int) Math.floor(image_rate * pageSize.getHeight()); for (HSLFSlide slide : ppt.getSlides()) { BufferedImage img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = img.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); // clear the drawing area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, imageWidth, imageHeight)); graphics.scale(image_rate, image_rate); //防止中文乱码 for (HSLFShape shape : slide.getShapes()) { if (shape instanceof HSLFTextShape) { HSLFTextShape hslfTextShape = (HSLFTextShape) shape; for (HSLFTextParagraph hslfTextParagraph : hslfTextShape) { for (HSLFTextRun hslfTextRun : hslfTextParagraph) { hslfTextRun.setFontFamily("宋体"); } } } } FileOutputStream out = null; try { slide.draw(graphics); File pngFile = new File(pptFile.getPath().replace(".ppt", String.format("-%04d.png", idx++))); out = new FileOutputStream(pngFile); ImageIO.write(img, "png", out); pngFileList.add(pngFile); } catch (Exception e) { System.out.println(e); } finally { try { if (out != null) { out.flush(); out.close(); } if (graphics != null) { graphics.dispose(); } if (img != null) { img.flush(); } } catch (IOException e) { //LOGGER.error("ppt2Png close exception", e); System.out.println(e); } } } } catch (Exception e) { //LOGGER.error("ppt2Png exception", e); System.out.println(e); } finally { try { if (is != null) { is.close(); } if (ppt != null) { ppt.close(); } } catch (Exception e) { //LOGGER.error("ppt2Png exception", e); System.out.println(e); } } long endTime = System.currentTimeMillis(); // LOGGER.info("ppt2Png的时间:{}", endTime - startTime); //ystem.out.println(e); return pngFileList; } public static List pptx2Png(File pptxFile) { List pngFileList = new ArrayList(); long startTime = System.currentTimeMillis(); FileInputStream is = null; // 将ppt文件转换成每一帧的图片 XMLSlideShow pptx = null; try { ZipSecureFile.setMinInflateRatio(-1.0d); is = new FileInputStream(pptxFile); pptx = new XMLSlideShow(is); int idx = 1; Dimension pageSize = pptx.getPageSize(); double image_rate = 1.0; int imageWidth = (int) Math.floor(image_rate * pageSize.getWidth()); int imageHeight = (int) Math.floor(image_rate * pageSize.getHeight()); for (XSLFSlide xslfSlide : pptx.getSlides()) { BufferedImage img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = img.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); // clear the drawing area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, imageWidth, imageHeight)); graphics.scale(image_rate, image_rate); //防止中文乱码 for (XSLFShape shape : xslfSlide.getShapes()) { if (shape instanceof XSLFTextShape) { XSLFTextShape xslfTextShape = (XSLFTextShape) shape; for (XSLFTextParagraph xslfTextParagraph : xslfTextShape) { for (XSLFTextRun xslfTextRun : xslfTextParagraph) { xslfTextRun.setFontFamily("宋体"); } } } } FileOutputStream out = null; try { xslfSlide.draw(graphics); File pngFile = new File(pptxFile.getPath().replace(".pptx", String.format("-%04d.png", idx++))); out = new FileOutputStream(pngFile); ImageIO.write(img, "png", out); pngFileList.add(pngFile); } catch (Exception e) { //LOGGER.error("pptx2Png exception", e); System.out.println(e); } finally { try { if (out != null) { out.flush(); out.close(); } if (graphics != null) { graphics.dispose(); } if (img != null) { img.flush(); } } catch (IOException e) { //LOGGER.error("pptx2Png close exception", e); System.out.println(e); } } } } catch (Exception e) { //LOGGER.error("pptx2Png exception", e); System.out.println(e); } finally { try { if (is != null) { is.close(); } if (pptx != null) { pptx.close(); } } catch (Exception e) { //LOGGER.error("pptx2Png exception", e); System.out.println(e); } } long endTime = System.currentTimeMillis(); //LOGGER.info("pptx2Png耗时:{}", endTime - startTime); return pngFileList; } public static File png2Pdf(List pngFiles, String pdfFilePath) { Document document = new Document(); File inPdfFile = null; long startTime = System.currentTimeMillis(); try { //String inFilePath = pdfFilePath.replace(".pdf", ".in.pdf"); inPdfFile = new File(pdfFilePath); PdfWriter.getInstance(document, new FileOutputStream(inPdfFile)); document.open(); pngFiles.forEach(pngFile -> { try { Image png = Image.getInstance(pngFile.getCanonicalPath()); png.scalePercent(50); document.add(png); } catch (Exception e) { //LOGGER.error("png2Pdf exception", e); System.out.println(e); } }); document.close(); // 添加水印 // boolean ret = PDFWatermarkUtil.addWatermark(inFilePath, pdfFilePath, watermarkPath); /* if (ret) { File pdfFile = new File(pdfFilePath); return pdfFile; }*/ } catch (Exception e) { //LOGGER.error(String.format("png2Pdf %s exception", pdfFilePath), e); System.out.println(e); } finally { if (document.isOpen()) { document.close(); } /*if (inPdfFile != null) { inPdfFile.delete(); }*/ long endTime = System.currentTimeMillis(); //LOGGER.info("png2Pdf耗时:{}", endTime - startTime); System.out.println(endTime - startTime); } return null; } }

上面的excel转pdf不行 下面展示 首先可以尝试用aspose-cells 再maven中引一下依赖 网上有一些文章可以抄 这个超级简单。

另外一种是jacob包

值得注意的是这个匹配的是1.8如果是1.6的就得引1.143之类的 另外需要jacob.dll文件,版本对应文件名,超级难找,csdn都要钱钱的 jacob-1.18-x64.dll jacob-1.14.3-x64.dll 放不了,有缘人可以直接问我要

com.hynnet jacob 1.18 package com.ruoyi.util; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Variant; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; import org.apache.pdfbox.multipdf.PDFMergerUtility; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; public class ExceltoPdf { // public static void main(String[] args) { // excelToPDF("D:\\工作簿2.xlsx","D:\\3.pdf"); // } public static void excelToPDF(String sourceFilePath, String destinPDFFilePath) { ComThread.InitSTA(); Dispatch sheet = null; Dispatch sheets = null; //建立ActiveX部件 ActiveXComponent excelCom = new ActiveXComponent("Excel.Application"); //定义所有pdf的数组 String outFiles[] = null; excelCom.setProperty("Visible", new Variant(false)); //返回wrdCom.Documents的Dispatch Dispatch wordbooks = excelCom.getProperty("Workbooks").toDispatch(); //调用excelCom.Documents.Open方法打开指定的excel文档,返回excelDoc //Dispatch wordbook = Dispatch.invoke(wordbooks, "Open", Dispatch.Method, new Object[] { sourceFilePath ,new Variant(false) ,new Variant(true)}, new int[3]).toDispatch(); Dispatch wordbook = Dispatch.call(wordbooks, "Open", sourceFilePath, false,true).toDispatch(); sheets= Dispatch.get(wordbook, "Sheets").toDispatch(); int count = Dispatch.get(sheets, "Count").getInt(); System.out.println("---------合并的excel的sheet个数:"+count+"个-----------"); outFiles = new String[count]; for (int j = 1; j String outFile = ""; sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get,new Object[] { new Integer(j) }, new int[1]).toDispatch(); String sheetname = Dispatch.get(sheet, "name").toString(); Dispatch.call(sheet, "Activate"); Dispatch.call(sheet, "Select"); outFile = destinPDFFilePath.substring(0,destinPDFFilePath.length()-4) + sheetname + j +".pdf"; Dispatch.call(wordbook, "ExportAsFixedFormat", 0, destinPDFFilePath); Dispatch.call(wordbook, "Close", false); excelCom.invoke("Quit"); outFiles[j] = outFile; }catch (Exception ex) { //ex.printStackTrace(); System.out.println("--------pdf合成---------"); } } /*Dispatch.call(wordbook, "Close",new Variant(false)); System.out.println("---------转换pdf成功---------"); excelCom.invoke("Quit",new Variant[]{});*/ ComThread.Release(); MergePdf mp = new MergePdf(); PDFMergerUtility mergePdf = new PDFMergerUtility(); // 合并正文附件的pdf和表单的pdf // 遍历 去掉 有问题的 文件 int count2 = outFiles.length; for(int i = 0 ; i count2 --; } } String outFiles2[] = null; outFiles2 = new String[count2]; int j = 0; for(int i = 0 ; i outFiles2[j] = outFiles[i]; j++; } } //mp.mergePdfFiles(outFiles2, destinPDFFilePath); // 删除pdf for (String otf : outFiles2) { if(otf != null && !otf.equals("")){ File file = new File(otf); if(file.exists()){ file.delete(); } } } } } package com.ruoyi.util; import com.alibaba.fastjson.JSONArray; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; import java.io.File; import java.io.FileOutputStream; public class MergePdf { public String mergePdfFiles(String[] files, String newfile) { Document document = null; String[] fileValue = new String[files.length]; JSONArray jsonArray = new JSONArray(); try { document = new Document(new PdfReader(files[0]).getPageSize(1)); PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile)); document.open(); //int pages = 0; for (int i = 0; i String file = files[i]; PdfReader reader = new PdfReader(file); int n = reader.getNumberOfPages(); //pages += n; for (int j = 1; j System.out.println("合并表单出错"); e.printStackTrace(); } finally { document.close(); } for (int i = 0; i new File(fileValue[i]).delete(); } } return jsonArray.toString(); } }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有