javapackage top.zhoudeshui.utils;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class WPSConvertUtils {
private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;
public static String convertToPDF(String inputFilePath, String outputDirOrFilePath) {
File inputFile = new File(inputFilePath);
if (!inputFile.exists()) {
System.out.println("原文件不存在!");
return null;
}
String kind = getFileSuffix(inputFile.getName());
// 检查文件是否为PDF
if (kind.equals("pdf")) {
try {
Path source = new File(inputFilePath).toPath();
Path target = new File(outputDirOrFilePath).toPath();
// 检查源文件是否存在
if (!Files.exists(source)) {
System.err.println("Source file does not exist: " + source);
return null;
}
// 如果目标是目录,创建一个以源文件名命名的新文件
if (Files.isDirectory(target)) {
target = target.resolve(source.getFileName());
}
// 确保目标目录存在
Path targetParent = target.getParent();
if (targetParent != null && !Files.exists(targetParent)) {
Files.createDirectories(targetParent);
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
return target.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
String baseName = inputFile.getName().substring(0, inputFile.getName().lastIndexOf("."));
File outputDirOrFile = new File(outputDirOrFilePath);
String outputFilePath;
// 检查输出路径是否包含.pdf
if (outputDirOrFilePath.endsWith(".pdf")) {
// 输出路径已经包含.pdf,直接使用该文件名
File pdfFile = new File(outputDirOrFilePath);
// 确保文件的父目录存在,如果不存在则创建
if (!pdfFile.getParentFile().exists() && !pdfFile.getParentFile().mkdirs()) {
System.out.println("创建目录失败,请检查目录权限!");
return null;
}
outputFilePath = outputDirOrFilePath;
} else {
// 输出路径不包含.pdf,使用源文件的基本名称作为输出文件名
if (!outputDirOrFile.exists() && !outputDirOrFile.mkdirs()) {
System.out.println("创建目录失败,请检查目录权限!");
return null;
}
outputFilePath = new File(outputDirOrFile, baseName + ".pdf").getAbsolutePath();
}
// 根据文件类型调用相应的转换方法
if (kind.equals("doc") || kind.equals("docx") || kind.equals("txt")) {
if (!wordToPDF(inputFilePath, outputFilePath)) return null;
} else if (kind.equals("ppt") || kind.equals("pptx") || kind.equals("pptm") || kind.equals("ppsx")) {
if (!pptToPDF(inputFilePath, outputFilePath)) return null;
} else if (kind.equals("xls") || kind.equals("xlsx")) {
if (!exToPDF(inputFilePath, outputFilePath)) return null;
} else if (kind.equals("png") || kind.equals("jpg") || kind.equals("jpeg")) {
if (!imageToPDF(inputFilePath, outputFilePath)) return null;
} else {
System.out.println("不支持的文件格式!");
return null;
}
return outputFilePath;
}
private static String getFileSuffix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
}
private static boolean wordToPDF(String inputFile, String pdfFile) {
try {
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("KWPS.Application");
app.setProperty("Visible", new Variant(false));
app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF);
Dispatch.call(doc, "Close", false);
app.invoke("Quit", 0);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ComThread.Release();
}
}
private static boolean exToPDF(String inputFile, String pdfFile) {
try {
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("KET.Application");
app.setProperty("Visible", new Variant(false));
app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch excels = app.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.invoke(excels, "Open", Dispatch.Method, new Object[]{inputFile, new Variant(false), new Variant(false)}, new int[9]).toDispatch();
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[]{new Variant(0), pdfFile, new Variant(xlTypePDF)}, new int[1]);
Dispatch.call(excel, "Close", new Variant(false));
app.invoke("Quit");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ComThread.Release();
}
}
private static boolean pptToPDF(String inputFile, String pdfFile) {
try {
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("KWPP.Application");
Dispatch ppts = app.getProperty("Presentations").toDispatch();
Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true, false).toDispatch();
Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, new Object[]{pdfFile, new Variant(ppSaveAsPDF)}, new int[1]);
Dispatch.call(ppt, "Close");
app.invoke("Quit");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ComThread.Release();
}
}
/**
* 将图片转换为PDF
*
* @param inputFile 图片文件路径
* @param pdfFile 输出PDF文件路径
* @return 是否转换成功
*/
public static boolean imageToPDF(String inputFile, String pdfFile) {
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4); // 创建一个A4页面
document.addPage(page);
// 加载图片并创建一个PDF图像对象
PDImageXObject pdImage = PDImageXObject.createFromFile(inputFile, document);
// 计算图片缩放比例以适应页面
float originalWidth = pdImage.getWidth();
float originalHeight = pdImage.getHeight();
float scaleX = PDRectangle.A4.getWidth() / originalWidth;
float scaleY = PDRectangle.A4.getHeight() / originalHeight;
float scale = Math.min(scaleX, scaleY); // 取较小的缩放比例以完全适应页面
// 开始在页面上绘制内容
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
// 将图片绘制到页面上,居中并按比例缩放
float x = (PDRectangle.A4.getWidth() - originalWidth * scale) / 2;
float y = (PDRectangle.A4.getHeight() - originalHeight * scale) / 2;
contentStream.drawImage(pdImage, x, y, originalWidth * scale, originalHeight * scale);
}
// 保存PDF文件
document.save(pdfFile);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
WPSConvertUtils wpsConvertUtils = new WPSConvertUtils();
String output = wpsConvertUtils.convertToPDF("E:\\r.jpg", "E:\\aaasdsabc\\asdasdasdasdasdasdas-adasds.png");
System.out.println("PDF文件输出路径: " + output);
}
}
本文作者:周得水
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!