我有一个 HTML,想将其转换为内存中的 pdf,但找不到好的库来将 HTML 转换为 PDF。
我已经尝试使用
ITextRenderer
和 Jsoup
但抛出异常 Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 3; The markup in the document preceding the root element must be well-formed.
这是我的代码
Document document = Jsoup.parse(template, "UTF-8");
document.outputSettings().syntax(Document.OutputSettings.Syntax.html);
ByteArrayOutputStream binaryOutput = new ByteArrayOutputStream();
renderer.setDocumentFromString(document.html());
renderer.layout();
renderer.createPDF(binaryOutput);
您正在寻找一种渲染 HTML 并将其存储为 PDF 的方法。 在这个问题中,人们尝试渲染 XML(它接近 HTML,而且肯定是 XHTML)以最终将其转换为 PDF: Java 将 XML 文档渲染为 PDF
但是出现错误消息: 该错误与您未显示的输入文档有关。根元素之前的文档应该/可以如下所示:
<?xml version="1.0"?>
<!-- comment -->
<?processinginstruction whatever parameters?>
<rootElement/>
所以
<rootElement/>
之前的所有内容都是您的错误消息所指向的内容。我猜您正在查看一个 HTML 文档,它可能包含 JSoup HTML 解析器正在努力处理的内容。除非您与我们分享该文件,否则您必须自己弄清楚。
您可以尝试使用这个包:com.itextpdf.html2pdf.HtmlConverter
有了这个,你所要做的就是:
HtmlConverter.convertToPdf(tempFileHtml, tempFilePdf);
并将其导出。对于格式错误的 xml/html 来说,它没有太多问题。我使用了它,我对所获得的结果感到满意:)
将 HTML 转换为 PDF 的流行工具是 IronPDF for Java(也适用于 .NET)。
在
pom.xml
中添加以下内容(将版本更改为最新版本):
<dependencies>
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2022.11.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
我能够渲染像素完美的 PDF,看起来与我的 HTML 完全相同。一个例子是:
import com.ironsoftware.ironpdf.*;
// Render the HTML as a PDF. Stored in myPdf as type PdfDocument;
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1> ~Hello World~ </h1> Made with IronPDF!");
// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_saved.pdf"));
// Or with a local file:
myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
// Even works with Webpages:
myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
myPdf.saveAs(Paths.get("url.pdf"));
免责声明,我隶属于 IronPDF,并且非常乐意回答您对该软件的任何问题。
一些可用于通过 Java 将 HTML 转换为 PDF 的库: https://templated.io/blog/how-to-convert-html-to-pdf-with-java/