使用 Apache POI 和 Pdfbox 从.docx创建 PDF 时丢失样式



代码创建一个.docx,然后从中创建PDF。打开时,边距和样式与.docx不匹配,但主要问题是文本已移动并且缺少某些图像。创建 PDF 的代码:

InputStream doc = new FileInputStream(new File(sourcePath + name));
XWPFDocument document = new XWPFDocument(doc);
PdfOptions options = PdfOptions.getDefault();
OutputStream out = new FileOutputStream(new File(destinationPath + name.replace("." + MimeUtil2.getExtension(name), "") + ".pdf"));
PdfConverter.getInstance().convert(document, out, options);

关于丢失的图像我不知道,我尝试添加边距,在实例化文档和创建 PdfOptions 之间添加以下代码:

CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
CTPageMar pageMar = sectPr.addNewPgMar();
pageMar.setLeft(BigInteger.valueOf(720L));
pageMar.setTop(BigInteger.valueOf(1440L));
pageMar.setRight(BigInteger.valueOf(720L));
pageMar.setBottom(BigInteger.valueOf(1440L));

但不要工作。

我找到了一种修改边距的方法:在创建.docx时添加上面的相同代码,它似乎可以工作。但这并不能解决丢失图像和移动文本的问题。此外,它使代码更丑陋并且感觉不对,因为样式是在之后正确添加的(在.docx的编写中(。

如何保留.docx样式或添加样式以使PDF最接近.docx?

Java 1.8 , Apache POI 3.15 和 Pdfbox 2.0.9 .

我设法找到了一个解决方案,但仅适用于Windows(可能很容易转换为在Linux中使用,但我没有研究它(。我的问题是.docx看起来与打印的PDF不完全相同。我使用OfficeToPDF并用java调用它。命令行是这样的:

[path-to-officetopdf]/officetopdf.exe [source]myFile.docx [destination]myNewPDF.pdf

对于任何可能担心的人,这就是您使用 java 执行 shell 命令的方式:

import java.io.BufferedReader;
import java.io.InputStreamReader;
public static String executeShellCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";           
while ((line = reader.readLine())!= null) {
output.append(line + "n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}

我希望这可以帮助某人,如果我找到了使用 Linux 制作它的方法,我会发布它。

最新更新