其实还有一种spire转化PDF,不过这种是收费的还有限制只能导出3个sheet页数据也有限制
1.使用jacob
1.1引入依赖
<!--jacob依赖-->
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.19</version>
<scope>system</scope>
<!--本地的jacob.jar的路径-->
<systemPath>D:/kaifa/jacob-1.20/jacob-1.20/jacob.jar</systemPath>
</dependency>
1.2 工具类
package com.qiang;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* @ClassName: OfficeToPDF
* @author yinzl
* @date 2020-05-23
* 调用Microsoft excel,必须安装Microsoft Offcie 2007以上版本
* 需要引入jar包:jacob.jar,解压jacob_1.19.zip ,将文件jacob-1.19-x64.dll 放到jdk安装目录bin文件夹下, jdk要求1.8
* 如果出现不能设置类 PageSetup 的 PaperSize 属性的问题,是因为打印机设置中没有任何打印机的原因,使得页面设置失败,在添加任意打印机后,程序运行正常
*
*/
public class OfficeToPDF {
private static final Integer WORD_TO_PDF_OPERAND = 17;
private static final Integer PPT_TO_PDF_OPERAND = 32;
private static final Integer EXCEL_TO_PDF_OPERAND = 0;
public static void doc2pdf(String srcFilePath, String pdfFilePath) throws Exception {
ActiveXComponent app = null;
Dispatch doc = null;
try {
ComThread.InitSTA();
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
Object[] obj = new Object[]{
srcFilePath,
new Variant(false),
new Variant(false),//是否只读
new Variant(false),
new Variant("pwd")
};
doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
// Dispatch.put(doc, "Compatibility", false); //兼容性检查,为特定值false不正确
Dispatch.put(doc, "RemovePersonalInformation", false);
Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, WORD_TO_PDF_OPERAND); // word保存为pdf格式宏,值为17
}catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (doc != null) {
Dispatch.call(doc, "Close", false);
}
if (app != null) {
app.invoke("Quit", 0);
}
ComThread.Release();
}
}
public static void ppt2pdf(String srcFilePath, String pdfFilePath) throws Exception {
ActiveXComponent app = null;
Dispatch ppt = null;
try {
ComThread.InitSTA();
app = new ActiveXComponent("PowerPoint.Application");
Dispatch ppts = app.getProperty("Presentations").toDispatch();
/*
* call
* param 4: ReadOnly
* param 5: Untitled指定文件是否有标题
* param 6: WithWindow指定文件是否可见
* */
ppt = Dispatch.call(ppts, "Open", srcFilePath, true,true, false).toDispatch();
Dispatch.call(ppt, "SaveAs", pdfFilePath, PPT_TO_PDF_OPERAND); // ppSaveAsPDF为特定值32
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (ppt != null) {
Dispatch.call(ppt, "Close");
}
if (app != null) {
app.invoke("Quit");
}
ComThread.Release();
}
}
public static boolean excel2Pdf(String inFilePath, String outFilePath) throws Exception {
ActiveXComponent ax = null;
Dispatch excel = null;
try {
ComThread.InitSTA();
ax = new ActiveXComponent("Excel.Application");
ax.setProperty("Visible", new Variant(false));
ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch excels = ax.getProperty("Workbooks").toDispatch();
Object[] obj = new Object[]{
inFilePath,
new Variant(false),
new Variant(false)
};
excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
//将excel表格 设置成A3的大小
Dispatch sheets = Dispatch.call(excel, "Worksheets").toDispatch();
Dispatch sheet = Dispatch.call(sheets, "Item", new Integer(1)).toDispatch();
Dispatch pageSetup = Dispatch.call(sheet, "PageSetup").toDispatch();
//Dispatch.put(pageSetup, "PaperSize", new Integer(8));//A3是8,A4是9,A5是11等等
//该行代码报错:不能设置类 PageSetup 的 PaperSize 属性,暂时关闭
// 转换格式
Object[] obj2 = new Object[]{
new Variant(EXCEL_TO_PDF_OPERAND), // PDF格式=0
outFilePath,
new Variant(0) //0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件
};
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method,obj2, new int[1]);
} catch (Exception es) {
es.printStackTrace();
return false;
// throw es;
} finally {
if (excel != null) {
Dispatch.call(excel, "Close", new Variant(false));
}
if (ax != null) {
ax.invoke("Quit", new Variant[] {});
ax = null;
}
ComThread.Release();
}
return true;
}
public static void main(String[] args){
String inFilePath = "D:\\temp\\456dda29f26f45e2878c99b5af5d489b.xlsx";
String outFilePath = "D:\\temp\\test.pdf";
try {
OfficeToPDF.excel2Pdf(inFilePath,outFilePath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1.3 测试 拿出提前准备好的excel文件
1.4运行
@Test
public void test5() throws Exception {
long old = System.currentTimeMillis();
String inFilePath="C:\\Users\\ex_lizhq5\\Downloads\\用户-导出.xlsx";
OfficeToPDF.excel2Pdf(inFilePath,"C:\\Users\\ex_lizhq5\\Downloads\\用户-导出.pdf");
long now = System.currentTimeMillis();
//共耗时:33.234秒 33.4
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
}
1.6结果
2.使用aspose
2.1引入依赖
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>20.7</version>
<classifier>jdk17</classifier>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-slides</artifactId>
<version>20.7</version>
<classifier>jdk16</classifier>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>20.7</version>
</dependency>
<repositories>
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>
</repositories>
2.2 编写工具类
package com.qiang;
import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
public class PdfUtil {
public static File Pdf(ArrayList<String> imageUrllist,
String mOutputPdfFileName) {
//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(mOutputPdfFileName)); // pdf写入
doc.open();// 打开文档
for (int i = 0; i < imageUrllist.size(); i++) { // 循环图片List,将图片加入到pdf中
doc.newPage(); // 在pdf创建一页
Image png1 = Image.getInstance(imageUrllist.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(mOutputPdfFileName); // 输出流
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
return mOutputPdfFile; // 反回文件输出流
}
public static int getPercent(float h, float w) {
int p = 0;
float p2 = 0.0f;
if (h > w) {
p2 = 297 / h * 100;
} else {
p2 = 210 / w * 100;
}
p = Math.round(p2);
return p;
}
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;
}
/**
* 图片文件转PDF
* @param filepath
* @param request
* @return
*/
public static String imgOfPdf(String filepath, HttpServletRequest request) {
boolean result = false;
String pdfUrl = "";
String fileUrl = "";
try {
ArrayList<String> imageUrllist = new ArrayList<String>(); // 图片list集合
imageUrllist.add(request.getSession().getServletContext()
.getRealPath(File.separator + filepath)); // 添加图片文件路径
String fles = filepath.substring(0, filepath.lastIndexOf("."));
pdfUrl = request.getSession().getServletContext()
.getRealPath(File.separator +fles + ".pdf"); // 输出pdf文件路径
fileUrl =fles+".pdf";
result = true;
if (result == true) {
File file = PdfUtil.Pdf(imageUrllist, pdfUrl);// 生成pdf
file.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
return fileUrl;
}
public static void doc2pdf(String Address, String outPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
long old = System.currentTimeMillis();
File file = new File(outPath); // 新建一个空白pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(Address); // Address是将要被转化的word文档
doc.save(
os,
SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML,
// OpenDocument, PDF, EPUB, XPS, SWF
// 相互转换
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = PdfUtil.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;
}
public static String docOfPdf(String filePath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return "PDF格式转化失败";
}
try {
long old = System.currentTimeMillis();
//获取路径参数
String filePath1 = filePath;
String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
String pdfSPath = filePath2+".pdf";
filePath2 = pdfSPath; // 输出pdf文件路径
File file = new File(filePath2); // 新建一个空白pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(filePath1); // Address是将要被转化的word文档
doc.save(
os,
SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML,
// OpenDocument, PDF, EPUB, XPS, SWF
// 相互转换
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
os.close();
return pdfSPath;
} catch (Exception e) {
e.printStackTrace();
}
return "PDF格式转化失败";
}
public static boolean getLicense1() {
boolean result = false;
try {
InputStream is = PdfUtil.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;
}
/**
* @param excelPath
* @param pdfPath
*/
public static String exceOfPdf(String filePath) {
if (!getLicense1()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return "PDF格式转化失败";
}
try {
long old = System.currentTimeMillis();
//获取路径参数
String filePath1 = filePath;
String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
String pdfSPath = filePath2+".pdf";
filePath2 = pdfSPath; // 输出pdf文件路径
//文件操作
File file = new File(filePath2); // 新建一个空白pdf文档
FileOutputStream os = new FileOutputStream(file);
Workbook wb = new Workbook(filePath1);// 原始excel路径
FileOutputStream fileOS = new FileOutputStream(file);
wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
fileOS.close();
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
return pdfSPath;
} catch (Exception e) {
e.printStackTrace();
}
return "PDF格式转化失败";
}
public static boolean getLicense2() {
boolean result = false;
try {
InputStream is = PdfUtil.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;
}
/**
*
* @param args
*/
//public static void ppt2pdf(String Address) {
public static String pptOfpdf(String filePath, HttpServletRequest request){
// 验证License
if (!getLicense2()) {
return "PDF格式转化失败";
}
try {
long old = System.currentTimeMillis();
//File file = new File("C:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/webapps/generic/web/file/pdf1.pdf");// 输出pdf路径
//com.aspose.slides.Presentation pres = new com.aspose.slides.Presentation(Address);//输入pdf路径
String filePath1 = request.getSession().getServletContext().getRealPath(File.separator + filePath);
String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
String pdfPathString = filePath2 + ".pdf";
filePath2 = request.getSession().getServletContext()
.getRealPath(File.separator + filePath2 + ".pdf"); // 输出pdf文件路径
//文件操作
File file = new File(filePath2); // 新建一个空白pdf文档
com.aspose.slides.Presentation pres = new com.aspose.slides.Presentation(filePath1);//输入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 pdfPathString;
} catch (Exception e) {
e.printStackTrace();
}
return "PDF格式转化失败";
}
}
2.3 准备生成好的excel文件,还是上面那个
2.4 测试
@Test
public void test3() throws IOException {
String inFilePath="C:\\Users\\ex_lizhq5\\Downloads\\用户-导出 (2).xlsx";
//String outFilePath="D://wcmis_file/email/井控安全风险分级管控台账(2022年5月).pdf";
//OfficeToPDF.excel2Pdf(inFilePath,outFilePath);
//aspose 56s 56.869
PdfUtil.exceOfPdf(inFilePath);
// long old = System.currentTimeMillis();
// IFileConvert fileConvert = FileConvertEnum.getFileConvert("EXCEL");
// String pdfUri = fileConvert.fileToPdf("C:\\Users\\ex_lizhq5\\Downloads\\用户-导出.xlsx");
// long now = System.currentTimeMillis();
//
// System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
}
2.5 结果