添加依赖
<!--转pdf-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
测试方法
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
<dependencies>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-lygdj</artifactId>
</dependency>
<!--hutool工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.10</version>
</dependency>
<!--转pdf-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
<!-- <dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.18</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.18</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.12</version>
</dependency>
<!-- ------------------------------------------->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0-b170127.1453</version>
</dependency>
</dependencies>
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<File> files = pptx2Png(pptFile);
png2Pdf(files,"D:\\file\\ppt1.pdf");
}
public static List<File> ppt2Png(File pptFile) {
List<File> 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<File> pptx2Png(File pptxFile) {
List<File> 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<File> 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
放不了,有缘人可以直接问我要
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>jacob</artifactId>
<version>1.18</version>
</dependency>
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 <= count; j++) {
try {
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< outFiles.length;i++){
if(outFiles[i]== null){
count2 --;
}
}
String outFiles2[] = null;
outFiles2 = new String[count2];
int j = 0;
for(int i = 0 ; i< outFiles.length;i++){
if(outFiles[i]!= null){
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 < files.length; i++) {
if (files[i] != null && !("").equals(files[i])) {
String file = files[i];
PdfReader reader = new PdfReader(file);
int n = reader.getNumberOfPages();
//pages += n;
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
}
}
} catch (Exception e) {
System.out.println("合并表单出错");
e.printStackTrace();
} finally {
document.close();
}
for (int i = 0; i < fileValue.length; i++) {
if (fileValue[i] != null) {
new File(fileValue[i]).delete();
}
}
return jsonArray.toString();
}
}