HTML 转 PDF 在 Java 中

Darrius Serrant
Darrius Serrant
2022年十二月28日
更新 2024年十二月10日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

本教程指导Java开发人员如何使用IronPDF库将HTML内容转换为像素完美的PDF(便携式文档格式)文档。

*IronPDF是一个功能齐全的PDF转换器和PDF处理库。 IronPDF 适用于 .NETJava 编程语言。 本教程涵盖了在Java应用程序中使用该库将HTML内容(文件、标记等)进行转换。 在 HTML to PDF .NET 教程中可以找到在 .NET 应用程序中将 HTML 转换为 PDF 的教程。


概述


入门

立即在您的项目中开始使用IronPDF,并享受免费试用。

第一步:
green arrow pointer


1. 安装 IronPDF PDF 库用于 Java

有两种方法可以在 Java 项目中集成IronPDF库:

  1. 将 IronPDF 添加为 Maven 配置的 Java 项目中的依赖项

  2. 下载IronPDF JAR文件并手动添加到项目类路径中。

    以下部分将简要介绍两种安装方法。

选项1:将IronPDF安装为Maven依赖项

要在使用 Maven 的 Java 项目中安装 IronPDF,请将以下构件添加到 Java 项目的 pom.xml 文件的依赖项部分。

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>com.ironsoftware</artifactId>
   <version>2025.4.4</version>
</dependency>

第一个工件引用了IronPDF库的最新版本。 第二个工件引用了[SL4J](https://www.slf4j.org/" target="_blank" rel="nofollow noopener noreferrer)实现。 此依赖项是为了让 IronPDF 的渲染引擎在执行期间生成日志消息而必需的。 软件工程师可以用其他日志提供程序(例如[Logback](https://logback.qos.ch/" target="_blank" rel="nofollow noopener noreferrer)和[Log4J](https://logging.apache.org/log4j/2.x/" target="_blank" rel="nofollow noreferrer noopener))替换此依赖项; 或者如果他们不需要或不希望记录日志,则可以完全省略它。

在 Java 项目的根目录下的终端中运行mvn install命令以下载前面提到的库。

选项2:手动安装IronPDF JAR

不愿使用Maven或任何其他依赖管理系统的开发人员需要下载IronPDF库JAR文件 (以及可选的[SL4J](https://mvnrepository.com/artifact/org.slf4j/slf4j-simple" target="_blank" rel="nofollow noopener noreferrer) 实现)并手动将其添加到项目的类路径中。

直接从 IronPDF JAR 下载(或从 Maven 仓库)下载 IronPDF JAR 文件。


操作指南和代码示例

2. 将HTML转换为PDF

本节展示了IronPDF的旗舰HTML到PDF渲染功能。

PdfDocument 类是使用 IronPDF 的所有 PDF 文档渲染和操作功能的入口点。 该类包含一组强大的方法,用于将 HTML 转换为 PDF 文档,支持以下三种用例:从 HTML 字符串/标记转换、从 HTML 文件转换以及从 URL 转换。 本节将简要介绍每个用例,并提供链接以获取更多信息。

2.1 导入IronPDF包

IronPDF的所有转换和处理组件都包含在com.ironsoftware.ironpdf包中。

在 Java 源文件的顶部包含以下导入语句(在使用 IronPDF 的地方),以使这些组件在应用程序的源代码中可访问。

// Import statement for IronPDF for Java
import com.ironsoftware.ironpdf.*;
JAVA

2.2. 设置许可证密钥(可选)

IronPDF for Java 免费使用。 然而,对于免费用户,它会在 PDF 文档上添加一个平铺的背景水印(如下图所示)。

Html To Pdf 23 related to 2.2. 设置许可证密钥(可选)

在 ironpdf.com/java/licensing/ 获取许可证密钥,即可转换和处理无水印的 PDF 文档。

要使用 IronPDF 生成没有水印的 PDF,库必须使用有效的许可密钥。 下面的代码行用于配置库的许可密钥。

// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");
JAVA

在生成 PDF 文件或自定义文件内容之前,应设置许可密钥。 我们建议您在其他所有代码行之前调用setLicenseKey方法。

从 IronPDF 许可页面购买许可证密钥,或联系我们获取免费试用许可证密钥

2.3 设置日志文件位置(可选)

默认情况下(并假设安装了一个SLF4J提供程序),IronPDF会将日志消息生成到一个名为IronPdfEngine.log的文本文件中,该文件位于Java应用程序的根目录。

若要为日志文件指定不同的名称和位置,请使用Settings.setLogPath方法:

// Set a log path
Settings.setLogPath(Paths.get("IronPdfEngine.log"));
JAVA

请注意:必须在使用任何 PDF 转换和操作方法之前调用 Settings.setLogPath

2.4. 从HTML字符串创建PDF

PdfDocument.renderHtmlAsPdf 将HTML内容字符串转换为PDF文档。

以下代码示例使用单个标题元素来生成一个新文件。

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
pdf.saveAs("htmlstring_to_pdf.pdf");
JAVA
Html To Pdf 5 related to 2.4. 从HTML字符串创建PDF

使用PdfDocument.renderHtmlAsPdf将HTML标记转换为PDF文件。此方法可以使用所有符合W3C标准的HTML和CSS标记生成PDF文档。

renderHtmlAsPdf 处理所有 HTML、CSS 和 JavaScript 内容的方式与现代符合标准的浏览器相同。 这有助于软件工程师创建PDF文档,使其外观与网页浏览器中显示的完全一致。

renderHtmlAsPdf方法可以从计算机或网络驱动器的文件夹中获取图像、样式表和脚本。下一个示例从引用位于assets文件夹中的CSS文件和图像的HTML生成PDF文档:

String html = "<html><head><title>Hello world!</title><link rel='stylesheet' href='assets/style.css'></head><body><h1>Hello from IronPDF!</h1><a href="https://ironpdf.com/java/"><img src='assets/logo.png' /></a></body></html>";
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
pdf.saveAs("output.pdf");
JAVA

上述代码的结果如下图所示。

Html To Pdf 24 related to 2.4. 从HTML字符串创建PDF

PdfDocument.renderHtmlAsPdf 可以渲染各种富媒体元素。如果它能在 Chrome 中显示,那么 renderHtmlAsPdf 也能渲染它!

renderHtmlAsPdf的第二个(可选)参数允许开发人员指定一个基础路径,用于引用网络资源。 此路径可以是本地文件系统上的目录,甚至是一个URL路径。

了解更多关于renderHtmlAsPdf方法的信息,请参考此代码示例,使用HTML创建PDF,或在[PdfDocument类的API参考页](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#renderHtmlAsPdf(java.lang.String)中阅读。

2.5. 从网址创建PDF

开发人员可以使用 IronPDF 的 PdfDocument.renderUrlAsPdf 方法将在线网页转换为 PDF 文档。

下一个示例将维基百科文章渲染成PDF内容。

PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.saveAs("url_to_pdf.pdf");
JAVA

生成的 PDF 文件格式如下所示。

Html To Pdf 7 related to 2.5. 从网址创建PDF

IronPDF Java库可以转换托管在线的网页中的HTML内容。使用PdfDocument.renderUrlAsPdf方法来实现。

了解更多关于将网页转换为PDF内容的信息,请参阅这个将URL转换为PDF的代码示例

2.6. 从HTML文件创建PDF

IronPDF也可以将存储在本地文件系统上的HTML文档直接渲染成相应的PDF格式。

下一个代码示例使用[此发票作为现实示范](https://codepen.io/tjoen/pen/wvgvLX" target="_blank" rel="nofollow noopener noreferrer),展示IronPDF如何高效地转换HTML文件。

为方便起见,此处重现了发票的 HTML 标记:


<html>
<head>
    <meta charset="utf-8">
    <title>Invoice</title>
    <link rel="stylesheet" href="style.css">
    <link rel="license" href="https://www.opensource.org/licenses/mit-license/">
    <script src="script.js"></script>
</head>
<body>
<header>
    <h1>Invoice</h1>
    <address contenteditable>
        <p>Jonathan Neal</p>
        <p>101 E. Chapman Ave<br>Orange, CA 92866</p>
        <p>(800) 555-1234</p>
    </address>
    <span><img alt="" src="http://www.jonathantneal.com/examples/invoice/logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
    <h1>Recipient</h1>
    <address contenteditable>
        <p>Some Company<br>c/o Some Guy</p>
    </address>
    <table class="meta">
        <tr>
            <th><span contenteditable>Invoice #</span></th>
            <td><span contenteditable>101138</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Date</span></th>
            <td><span contenteditable>January 1, 2012</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Due</span></th>
            <td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
        </tr>
    </table>
    <table class="inventory">
        <thead>
        <tr>
            <th><span contenteditable>Item</span></th>
            <th><span contenteditable>Description</span></th>
            <th><span contenteditable>Rate</span></th>
            <th><span contenteditable>Quantity</span></th>
            <th><span contenteditable>Price</span></th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><a class="cut">-</a><span contenteditable>Front End Consultation</span></td>
            <td><span contenteditable>Experience Review</span></td>
            <td><span data-prefix>$</span><span contenteditable>150.00</span></td>
            <td><span contenteditable>4</span></td>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        </tbody>
    </table>
    <a class="add">+</a>
    <table class="balance">
        <tr>
            <th><span contenteditable>Total</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Paid</span></th>
            <td><span data-prefix>$</span><span contenteditable>0.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Balance Due</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
    </table>
</article>
<aside>
    <h1><span contenteditable>Additional Notes</span></h1>
    <div contenteditable>
        <p>A finance charge of 1.5% will be made on unpaid balances after 30 days.</p>
    </div>
</aside>
</body>
</html>

<html>
<head>
    <meta charset="utf-8">
    <title>Invoice</title>
    <link rel="stylesheet" href="style.css">
    <link rel="license" href="https://www.opensource.org/licenses/mit-license/">
    <script src="script.js"></script>
</head>
<body>
<header>
    <h1>Invoice</h1>
    <address contenteditable>
        <p>Jonathan Neal</p>
        <p>101 E. Chapman Ave<br>Orange, CA 92866</p>
        <p>(800) 555-1234</p>
    </address>
    <span><img alt="" src="http://www.jonathantneal.com/examples/invoice/logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
    <h1>Recipient</h1>
    <address contenteditable>
        <p>Some Company<br>c/o Some Guy</p>
    </address>
    <table class="meta">
        <tr>
            <th><span contenteditable>Invoice #</span></th>
            <td><span contenteditable>101138</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Date</span></th>
            <td><span contenteditable>January 1, 2012</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Due</span></th>
            <td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
        </tr>
    </table>
    <table class="inventory">
        <thead>
        <tr>
            <th><span contenteditable>Item</span></th>
            <th><span contenteditable>Description</span></th>
            <th><span contenteditable>Rate</span></th>
            <th><span contenteditable>Quantity</span></th>
            <th><span contenteditable>Price</span></th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><a class="cut">-</a><span contenteditable>Front End Consultation</span></td>
            <td><span contenteditable>Experience Review</span></td>
            <td><span data-prefix>$</span><span contenteditable>150.00</span></td>
            <td><span contenteditable>4</span></td>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        </tbody>
    </table>
    <a class="add">+</a>
    <table class="balance">
        <tr>
            <th><span contenteditable>Total</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Paid</span></th>
            <td><span data-prefix>$</span><span contenteditable>0.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Balance Due</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
    </table>
</article>
<aside>
    <h1><span contenteditable>Additional Notes</span></h1>
    <div contenteditable>
        <p>A finance charge of 1.5% will be made on unpaid balances after 30 days.</p>
    </div>
</aside>
</body>
</html>
HTML

假设 HTML 文件已与 CSS 文件和 JavaScript 文件一起保存到名为 invoices 的文件夹中。 我们可以使用 IronPDF 对 HTML 文件进行如下转换:

PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
pdf.saveAs("htmlfile_to_pdf.pdf");
JAVA

与HTML字符串转换为PDF的示例一样,IronPDF能正确解析HTML文档中的任何相对URL,将它们转换为文件系统上的正确路径。 因此,这个示例生成的PDF文件能够完美地捕捉到任何引用的样式表和脚本通常对网页的视觉影响。

3. 进一步阅读

我们只是触及了IronPDF将HTML渲染为PDF功能的冰山一角。

通过我们代码示例部分提供的精选代码示例,进一步了解如何在Java开发中使用HTML到PDF转换器。

  1. 阅读此代码示例以获取PDF生成设置,了解在转换过程中如何自定义PDF文档的外观。

  2. 使用自定义页眉和页脚边距大小页面尺寸水印等生成PDF文件。

  3. 从文档中提取PDF内容(从PDF提取文本从PDF提取图像),通过PDF压缩优化文件大小,并使用IronPrint功能以编程方式打印PDF

    研究IronPDF Java API 参考页上的PdfDocument类,以获得对渲染的HTML转换为PDF的更大控制。

观看 HTML 转 PDF 教程视频


教程快速访问

Cps Intellij related to 教程快速访问

下载本教程的 Java 源代码

本教程的 HTML 转 PDF Java 源代码全文可作为压缩的 IntelliJ 项目免费下载。

下载

在 GitHub 上探索此教程

该项目的源代码可在 GitHub 上获取。

使用此代码,只需几分钟就能轻松上手并运行。该项目保存为 IntellJ IDEA 项目,但也可导入其他流行的 Java IDE。

Java HTML 转 PDF
Github Icon related to 教程快速访问
Documentation related to 教程快速访问

查看应用程序接口参考

探索 IronPDF 的 API 参考,其中概述了 IronPDF 的所有功能、命名空间、类、方法字段和枚举的详细信息。

查看应用程序接口参考
Darrius Serrant
全栈软件工程师(WebOps)

达瑞乌斯·塞兰特拥有迈阿密大学计算机科学学士学位,目前在Iron Software担任全栈WebOps营销工程师。从小对编码的热爱使他认为计算机既神秘又易接近,成为创意和解决问题的完美媒介。

在Iron Software,达瑞乌斯乐于创造新事物并简化复杂概念,使其更易于理解。作为我们在职开发者之一,他还自愿教授学生,将他的专业知识传授给下一代。

对达瑞乌斯而言,他的工作之所以令人满足,是因为它具有价值并产生了真正的影响。