将 html 文件转换为 pdf 文件。我有 html 文件、css 文件和 js 文件在一个文件夹中,我如何将 index.html 转换为在 java 中使用 itext 创建 pdf。谁能帮我解决这个问题。有没有示例项目?
问问题
3550 次
2 回答
0
您可以使用 iTextPdf 库或飞碟(它又使用 iText 库)。我更喜欢 Flying Saucer,因为它可以将几乎所有的 css 样式从 html 转换为 pdf,而 iTextPdf 在 css 兼容方面非常有限。这是我使用飞碟将 HTML 转换为 PDF 的静态方法:
public static void convertHtml2Pdf(String htmlPath, String pdfPath) throws FileNotFoundException, IOException, com.lowagie.text.DocumentException {
final ITextRenderer iTextRenderer = new ITextRenderer();
iTextRenderer.setDocument(htmlPath);
iTextRenderer.layout();
/** The generated pdf will be written to the file. */
final FileOutputStream fileOutputStream =
new FileOutputStream(new File(pdfPath));
/** Creating the pdf */
iTextRenderer.createPDF(fileOutputStream);
fileOutputStream.close();
}
于 2014-10-05T11:47:30.493 回答
0
HtmlConverter
有一个为此用例调用的内置帮助程序类。如果你有 HTML,那么很容易像这样将它转换为 PDF。
将以下依赖项添加到您的项目中。
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.14</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>3.0.3</version>
</dependency>
然后在您的代码中,您可以像这样将 HTML 文件转换为 PDF。
HtmlConverter.convertToPdf(new File("./simple-input.html"),new File("simple-output.pdf"));
如果你想从 HTML 字符串中读取,那么你可以做这样的事情。
HtmlConverter.convertToPdf("<h1>Hello String Content!</h1>", fileOutputStream);
我在我的博客上有一些关于iText HTML to PDF in Java with Examples 的详细信息。
于 2021-10-13T13:30:01.353 回答