JAVA 将word、execl、ptt、txt、图片等文件转为pdf文件、合并为一个pdf文件,并统一pdf文件页面样式
准备
1.jar包

2.对应的dll文件放到jdk或jre的bin目录下:
代码
import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageRotateAngle;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.graphics.PdfStringFormat;
import com.spire.pdf.graphics.PdfTextAlignment;
import com.spire.pdf.graphics.PdfTrueTypeFont;
import com.spire.pdf.graphics.PdfVerticalAlignment;
import java.awt.Font;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class PDFUtil {
private static List<String> list=new ArrayList<>();
private static List<String> dellist=new ArrayList<>();
public static void trans(String filePath, String pdfPath,String type) {
try {
toPdf(filePath,pdfPath, type);
} catch (Exception e) {
e.printStackTrace();
}
}
//转换
private static void toPdf(String filePath, String pdfPath,String type) {
if("word".equals(type)){
word2PDF(filePath,pdfPath);
}else if("excel".equals(type)){
excel2PDF(filePath,pdfPath);
}else if("ppt".equals(type)){
ppt2PDF(filePath,pdfPath);
}else if("photo".equals(type)){
convert(filePath,pdfPath);
}
}
private static void word2PDF(String inputFile, String pdfFile) {
ActiveXComponent app = new ActiveXComponent("Word.Application");
try {
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Open", new Object[]{inputFile, false, true}).toDispatch();
Dispatch.call(doc, "ExportAsFixedFormat", new Object[]{pdfFile, 17});
Dispatch.call(doc, "Close", new Object[]{false});
} catch (Exception e) {
e.printStackTrace();
System.out.println("转换出错:"+pdfFile);
}finally {
app.invoke("Quit");
}
}
private static boolean getLicense() {
boolean result = false;
try {
InputStream license = PDFUtil.class.getClassLoader().getResourceAsStream("\\license.xml");// license路径
License aposeLic = new License();
aposeLic.setLicense(license);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void excel2PDF(String excelPath, String pdfPath) {
long old = System.currentTimeMillis();
// 验证License
if (!getLicense()) {
return;
}
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
File excelFile = new File(excelPath);
if (excelFile.exists()) {
fileInputStream = new FileInputStream(excelFile);
Workbook workbook = new Workbook(fileInputStream);
File pdfFile = new File(pdfPath);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);//把内容放在一张PDF 页面上;
//pdfSaveOptions.setOnePagePerSheet(false);//把内容放在一张PDF 页面上;
FileOutputStream fileOS = new FileOutputStream(pdfFile);
workbook.save(fileOS, pdfSaveOptions);// 只放一张纸;我的专为横向了
long now = System.currentTimeMillis();
} else {
System.out.println("文件不存在");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//图片转pdf
public static void convert(String source, String target) {
Document document = new Document();
//设置文档页边距
document.setMargins(40,57,74,57);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(target);
PdfWriter.getInstance(document, fos);
//打开文档
document.open();
//获取图片的宽高
Image image = Image.getInstance(source);
float imageHeight=image.getScaledHeight();
float imageWidth=image.getScaledWidth();
//设置页面宽高与图片一致
Rectangle rectangle = new Rectangle(imageWidth+114, imageHeight+114);
document.setPageSize(rectangle);
//图片居中
image.setAlignment(Image.ALIGN_CENTER);
//新建一页添加图片
document.newPage();
document.add(image);
} catch (Exception ioe) {
System.out.println(ioe.getMessage());
} finally {
//关闭文档
document.close();
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void ppt2PDF(String inputFile, String pdfFile) {
ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");
try {
Dispatch ppts = app.getProperty("Presentations").toDispatch();
Dispatch ppt = Dispatch.call(ppts, "Open", new Object[]{inputFile, true, true, false}).toDispatch();
Dispatch.call(ppt, "SaveAs", new Object[]{pdfFile, 32});
Dispatch.call(ppt, "Close");
app.invoke("Quit");
} catch (Exception e) {
e.printStackTrace();
System.out.println("转换出错:"+inputFile);
}finally {
app.invoke("Quit");
}
}
public static void winTest(List<String> FileList,String savepath) throws Exception {
//文件转为pdf文件
for (String str : FileList) {
String substr = str.substring(str.lastIndexOf(".")+1);
String substr1 = str.substring(0,str.lastIndexOf("."))+".pdf";
if(substr.equals("doc") || substr.equals("docx") || substr.equals("txt")) {
trans(str, substr1 , "word");
dellist.add(substr1);
}else if(substr.equals("xls") || substr.equals("xlsx")) {
trans(str, substr1 , "excel");
dellist.add(substr1);
}else if(substr.equals("ppt") || substr.equals("pptx")) {
trans(str, substr1 , "ppt");
dellist.add(substr1);
}else if(substr.equals("bmp") || substr.equals("jpg") || substr.equals("png") || substr.equals("tif") || substr.equals("gif") ||
substr.equals("psd") || substr.equals("pcx") || substr.equals("tga") || substr.equals("exif") || substr.equals("fpx") || substr.equals("svg") ||
substr.equals("cdr") || substr.equals("pcd") || substr.equals("dxf") || substr.equals("ufo") || substr.equals("eps") || substr.equals("ai") ||
substr.equals("raw") || substr.equals("WMF") || substr.equals("webp") || substr.equals("avif")) {
trans(str, substr1 , "photo");
dellist.add(substr1);
}
list.add(substr1);
}
//合并pdf文件
String[] files = list.toArray( new String[]{});
mergePdfFiles(files, savepath);
//修改、统一页面样式
setPageStyle(savepath);
//删除合并之前生成的单个pdf
delFile(dellist);
}
public static void delFile(List<String> filePaths) {
for (String str : filePaths) {
try {
String filePath = str;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
} catch (Exception e) {
System.out.println(str+"删除文件操作出错");
e.printStackTrace();
}
}
}
public static void setPageStyle(String savepath) {
//创建PdfDocument实例
PdfDocument originalDoc = new PdfDocument();
//加载PDF文件
originalDoc.loadFromFile(savepath);
//创建一个新的PdfDocument实例
PdfDocument newDoc = new PdfDocument();
newDoc.getPages().add();
//遍历所有PDF 页面
//Dimension2D dimension2D = new Dimension();
for (int i = 0; i < originalDoc.getPages().getCount(); i++) {
PdfPageBase page = originalDoc.getPages().get(i);
//获取页面旋转角度
//int rotateAngle = page.getRotation().getValue();
//判断pdf的纸张方向
if((page.getSize().getHeight())<(page.getSize().getWidth())) {
//旋转页面270度
page.setRotation((PdfPageRotateAngle.fromValue(PdfPageRotateAngle.Rotate_Angle_270.getValue())));
//设置新文档页边距为10
PdfMargins margins = new PdfMargins(10);
//设置新文档页面大小为A4
PdfPageBase newPage = newDoc.getPages().add(PdfPageSize.A4, margins);
//调整画布,设置内容也根据页面的大小进行缩放
double wScale = (PdfPageSize.A4.getWidth() - 20) / page.getSize().getHeight();
double hScale = (PdfPageSize.A4.getHeight() - 20) / page.getSize().getWidth();
newPage.getCanvas().scaleTransform(wScale, hScale);
//复制原文档的内容到新文档
newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());
}else {
//设置新文档页边距为10
PdfMargins margins = new PdfMargins(10);
//设置新文档页面大小为A4
PdfPageBase newPage = newDoc.getPages().add(PdfPageSize.A4, margins);
//调整画布,设置内容也根据页面的大小进行缩放
double wScale = (PdfPageSize.A4.getWidth() - 20) / page.getSize().getWidth();
double hScale = (PdfPageSize.A4.getHeight() - 20) / page.getSize().getHeight();
newPage.getCanvas().scaleTransform(wScale, hScale);
//复制原文档的内容到新文档
newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());
}
}
//保存PDF
newDoc.saveToFile(savepath);
newDoc.getPages().remove(newDoc.getPages().get(0));
newDoc.saveToFile(savepath);
PdfDocument pdf = newDoc;
pdf.getPages().add();
//创建字体
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN, 10),true);
//遍历文档中的页
for (int i = 0; i < pdf.getPages().getCount(); i++) {
Dimension2D pageSize = pdf.getPages().get(i).getSize();
float y = (float) pageSize.getHeight() - 40;
//初始化页码域
PdfPageNumberField number = new PdfPageNumberField();
//初始化总页数域
PdfPageCountField count = new PdfPageCountField();
//创建复合域
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.getBlack(), "第{0}页 共{1}页", number, count);
//设置复合域内文字对齐方式
compositeField.setStringFormat(new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top));
//测量文字大小
Dimension2D textSize = font.measureString(compositeField.getText());
//设置复合域的在PDF页面上的位置及大小
compositeField.setBounds(new Rectangle2D.Float(((float) pageSize.getWidth() - (float) textSize.getWidth())/2, y, (float) textSize.getWidth(), (float) textSize.getHeight()));
//将复合域添加到PDF页面
compositeField.draw(pdf.getPages().get(i).getCanvas());
}
//移除第一个页
pdf.getPages().remove(pdf.getPages().get(pdf.getPages().getCount()-1));
//保存为另外一个文档
pdf.saveToFile(savepath);
}
public static boolean mergePdfFiles(String[] files, String newfile) {
boolean retValue = false;
Document document = null;
try {
document = new Document(new PdfReader(files[0]).getPageSize(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
document.open();
for (int i = 0; i < files.length; i++) {
PdfReader reader = new PdfReader(files[i]);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
}
retValue = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
document.close();
}
return retValue;
}
}
测试
public static void main(String[] args) throws Exception {
List<String> list1=new ArrayList<>();
//添加文件文件地址
list1.add("D:/123.txt");
//winTest("文件集合","pdf保存地址")
PDFUtil.winTest(list1,"D:/testPdf.pdf");
}