【发布时间】:2011-03-02 15:08:45
【问题描述】:
如何将 Word 文档转换为 PDF,其中文档包含各种内容,例如表格。尝试使用 iText 时,原始文档与转换后的 PDF 看起来不同。是否有我可以使用的开源 API/库,而不是调用可执行文件?
【问题讨论】:
如何将 Word 文档转换为 PDF,其中文档包含各种内容,例如表格。尝试使用 iText 时,原始文档与转换后的 PDF 看起来不同。是否有我可以使用的开源 API/库,而不是调用可执行文件?
【问题讨论】:
这是一项相当艰巨的任务,如果您想要完美的结果(不使用 Word 就不可能),那就更难了>更新:我错了,见下文)。
您的基本选项如下:
更新 - 2016-02-11 这是我关于此主题的博客文章的精简副本,其中概述了支持 Java 中的 Word-to-PDF 的现有产品。
Converting Microsoft Office (Word, Excel) documents to PDFs in Java
我知道的三个可以渲染 Office 文档的产品:
yeokm1/docs-to-pdf-converter 不定期维护,纯 Java,开源 将多个库绑定在一起来执行转换。
xdocreport 积极开发,纯 Java,开源 它是一种 Java API,可将使用 MS Office (docx) 或 OpenOffice (odt)、LibreOffice (odt) 创建的 XML 文档与 Java 模型合并以生成报告并将其转换为其他格式(PDF、XHTML ...)。
Snowbound Imaging SDK 闭源,纯 Java Snowbound 似乎是 100% 的 Java 解决方案,成本超过 2,500 美元。它包含描述如何在评估下载中转换文档的示例。
OpenOffice API 开源,不是纯 Java - 需要安装 Open Office OpenOffice 是一个支持 Java API 的原生 Office 套件。这支持阅读 Office 文档和编写 PDF 文档。 SDK 包含一个文档转换示例(examples/java/DocumentHandling/DocumentConverter.java)。要编写 PDF,您需要通过“writer_pdf_Export”编写器而不是“MS Word 97”编写器。 或者您可以使用包装 API JODConverter。
JDocToPdf - 于 2016 年 2 月 11 日去世 使用 Apache POI 读取 Word 文档,使用 iText 编写 PDF。完全免费,100% Java,但有一些 limitations。
【讨论】:
我同意将 OpenOffice 列为具有 Java API 的 word/pdf 文档的高保真导入/导出工具的海报,它也可以跨平台工作。 OpenOffice 导入/导出过滤器非常强大,可以在转换为包括 PDF 在内的各种格式期间保留大多数格式。 Docmosis 和 JODReports 的增值让生活比直接学习 OpenOffice API 更轻松,因为 UNO api 的风格和与崩溃相关的错误,这可能具有挑战性。
【讨论】:
您可以为此目的使用 JODConverter。它可用于在不同的办公格式之间转换文档。如:
关于它的更多细节可以在这里找到: http://www.artofsolving.com/opensource/jodconverter
【讨论】:
unoconv,这是一个在 UNIX 中工作的 python 工具。 虽然我使用 Java 在 UNIX 中调用 shell,但它对我来说非常适合。我的源代码:UnoconvTool.java。据说 JODConverter 和 unoconv 都使用 open office/libre office。
docx4j/docxreport、POI、PDFBox 都不错,但在转换中缺少一些格式。
【讨论】:
查看docs-to-pdf-converter on github。它是专为将文档转换为 pdf 而设计的轻量级解决方案。
为什么?
我想要一个可以转换 Microsoft Office 文档的简单程序 到 PDF 但没有像 LibreOffice 这样的依赖项或昂贵的 专有解决方案。查看如何转换代码和库 每个单独的格式都分散在网络上,我决定 将所有这些解决方案组合到一个程序中。一路上,我 由于我也遇到了代码,所以决定也添加 ODT 支持。
【讨论】:
您可以使用 Cloudmersive 本机 Java 库。它每月最多可免费进行 50,000 次转换,并且根据我的经验,它比 iText 或基于 Apache POI 的方法等其他方法具有更高的保真度。这些文档实际上看起来与 Microsoft Word 中的一样,这对我来说是关键。顺便说一句,它还可以做 XLSX、PPTX 以及遗留的 DOC、XLS 和 PPT 到 PDF 的转换。
这是代码的样子,首先添加你的导入:
import com.cloudmersive.client.invoker.ApiClient;
import com.cloudmersive.client.invoker.ApiException;
import com.cloudmersive.client.invoker.Configuration;
import com.cloudmersive.client.invoker.auth.*;
import com.cloudmersive.client.ConvertDocumentApi;
然后转换一个文件:
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
ConvertDocumentApi apiInstance = new ConvertDocumentApi();
File inputFile = new File("/path/to/input.docx"); // File to perform the operation on.
try {
byte[] result = apiInstance.convertDocumentDocxToPdf(inputFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertDocumentApi#convertDocumentDocxToPdf");
e.printStackTrace();
}
您可以从门户免费获得document conversion API key。
【讨论】:
使用JACOB调用Office Word是一个100%完美的解决方案。但它只支持Windows平台,因为需要安装Office Word。
使用 JACOB API 调用 Office Word 将 doc/docx 转换为 pdf。
public void convertDocx2pdf(String docxFilePath) {
File docxFile = new File(docxFilePath);
String pdfFile = docxFilePath.substring(0, docxFilePath.lastIndexOf(".docx")) + ".pdf";
if (docxFile.exists()) {
if (!docxFile.isDirectory()) {
ActiveXComponent app = null;
long start = System.currentTimeMillis();
try {
ComThread.InitMTA(true);
app = new ActiveXComponent("Word.Application");
Dispatch documents = app.getProperty("Documents").toDispatch();
Dispatch document = Dispatch.call(documents, "Open", docxFilePath, false, true).toDispatch();
File target = new File(pdfFile);
if (target.exists()) {
target.delete();
}
Dispatch.call(document, "SaveAs", pdfFile, 17);
Dispatch.call(document, "Close", false);
long end = System.currentTimeMillis();
logger.info("============Convert Finished:" + (end - start) + "ms");
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
throw new RuntimeException("pdf convert failed.");
} finally {
if (app != null) {
app.invoke("Quit", new Variant[] {});
}
ComThread.Release();
}
}
}
}
【讨论】:
已经 2019 年了,我不敢相信仍然没有最简单和最方便的方法可以将 Java 世界中最流行的 Micro$oft Word 文档转换为 Adobe PDF 格式。
我几乎尝试了上述答案中提到的所有方法,我发现最好的也是唯一能满足我要求的方法是使用 OpenOffice 或 LibreOffice。其实我不太清楚它们之间的区别,似乎它们都提供了soffice命令行。
我的要求是:
首先想到的是doc-to-pdf-converter,但它缺乏维护,最近一次更新发生在4年前,我不会使用nobody-maintain-solution。 Xdocreport 似乎是一个有前途的选择,但它只能转换docx,而不是doc 二进制文件,这对我来说是强制性的。使用 Java 调用 OpenOffice API 看起来不错,但是对于这么简单的需求来说太复杂了。
最后我找到了最好的解决方案:使用 OpenOffice 命令行完成工作:
Runtime.getRuntime().exec("soffice --convert-to pdf -outdir . /path/some.doc");
我一直相信最短的代码就是最好的代码(当然应该是可以理解的),就是这样。
【讨论】:
Docx4j 是开源,是用于将 Docx 转换为 pdf 且没有任何对齐或字体问题的最佳 API。
Maven 依赖项:
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-Internal</artifactId>
<version>8.0.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>8.0.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-MOXy</artifactId>
<version>8.0.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.0.0</version>
</dependency>
代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
public class DocToPDF {
public static void main(String[] args) {
try {
InputStream templateInputStream = new FileInputStream("D:\\\\Workspace\\\\New\\\\Sample.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
String outputfilepath = "D:\\\\Workspace\\\\New\\\\Sample.pdf";
FileOutputStream os = new FileOutputStream(outputfilepath);
Docx4J.toPDF(wordMLPackage,os);
os.flush();
os.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
【讨论】:
Spire.Doc for Java,它是一个专业的Java API,使Java应用程序无需使用Microsoft Office即可创建、转换、操作和打印Word文档。您可以轻松地将Word转换为PDF,只需几行代码如下。
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.ToPdfParameterList;
public class WordToPDF {
public static void main(String[] args) {
//Create Document object
Document doc = new Document();
//Load the file from disk.
doc.loadFromFile("Sample.docx");
//create an instance of ToPdfParameterList.
ToPdfParameterList ppl=new ToPdfParameterList();
//embeds full fonts by default when IsEmbeddedAllFonts is set to true.
ppl.isEmbeddedAllFonts(true);
//set setDisableLink to true to remove the hyperlink effect for the result PDF page.
//set setDisableLink to false to preserve the hyperlink effect for the result PDF page.
ppl.setDisableLink(true);
//Set the output image quality as 40% of the original image. 80% is the default setting.
doc.setJPEGQuality(40);
//Save to file.
doc.saveToFile("output/ToPDF.pdf",FileFormat.PDF);
}
}
运行上面的sn-ps代码后,原Word文档的所有格式都可以完美复制成PDF。
【讨论】: