如何将包含各种内容(例如表格)的Word文档转换为PDF格式?在尝试使用iText时,生成的PDF文件与原始文档不同。有没有开源API/库可供使用,而不是调用可执行文件?
xdocreport 活跃开发,纯Java,开源 它是一个Java API,用于合并使用MS Office(docx)或OpenOffice(odt),LibreOffice(odt)创建的XML文档,并与Java模型一起生成报告,如果需要,可以将其转换为其他格式(PDF,XHTML等)。
Snowbound Imaging SDK 闭源,纯Java Snowbound似乎是一个100%的Java解决方案,售价超过2500美元。它包含有关如何在评估下载中转换文档的示例。
OpenOffice API 开源,非纯Java - 需要安装Open Office OpenOffice是一个本地办公套件,支持Java API。这支持读取Office文档和编写PDF文档。SDK包含一个文档转换示例(examples/java/DocumentHandling/DocumentConverter.java)。要编写PDF,您需要传递“writer_pdf_Export”写入器,而不是“MS Word 97”写入器。 或者您可以使用封装API JODConverter。
JDocToPdf - 已于2016-02-11停止更新 使用Apache POI读取Word文档并使用iText编写PDF。完全免费,100% Java,但有一些限制。
Docx4j是开源的API,最适合将Docx转换为PDF,无需考虑任何对齐或字体问题。
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();
}
}
}
Runtime.getRuntime().exec("soffice --convert-to pdf -outdir . /path/some.doc");
我一直相信代码越短越好(当然,它必须是易懂的),就是这样。
请查看github上的docs-to-pdf-converter。这是一个专门用于将文档转换为PDF的轻量级解决方案。
为什么?
我想要一个简单的程序,可以将Microsoft Office文档转换为PDF,但不需要像LibreOffice或昂贵的专有解决方案那样依赖其他软件。考虑到将每个单独格式的代码和库都散布在Web上,我决定将所有这些解决方案合并成一个单一的程序。在此过程中,我还决定添加ODT支持,因为我也遇到了该代码。
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();
}
使用 JACOB 调用 Office Word 是一个完美的解决方案。但它只支持在 Windows 平台上,因为需要安装 Office Word。
Using JACOB API call Office Word to convert doc/docx to 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();
}
}
}
}
我同意那些将OpenOffice列为具有Java API的高保真度导入/导出Word/PDF文档的工具,并且它还可以跨平台使用。OpenOffice的导入/导出过滤器非常强大,在转换为各种格式(包括PDF)时能够保留大部分格式。Docmosis和JODReports的附加值使得生活比直接学习OpenOffice API更容易,因为UNO API的风格和与崩溃相关的错误可能会带来挑战。
unoconv是一个在UNIX系统中运行的Python工具。 当我使用Java调用UNIX shell时,它对我来说非常完美。我的源代码:UnoconvTool.java。据说JODConverter和unoconv都使用开放办公室/自由办公室。
docx4j/docxreport、POI、PDFBox都很好,但它们在转换中缺少一些格式。
https://gotenberg.dev/docs/about
,它提供了强大和完美的API来将DOCX
文件转换为PDF
。它还提供了Docker容器,可以在我们的环境中运行 :-) - srr7