如何使用 IronPDF for JAVA 将 HTML 转换为 PDF

用 Java 将 HTML 转换为 PDF.

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPDF for Java通过运行完整的Chromium渲染引擎将HTML内容转换为PDF文档——与现代浏览器相同的引擎。 每个CSS属性、字体、图像和JavaScript生成的布局都以像素精度呈现在页面上,正如它在浏览器窗口中一样。

本教程介绍了三种核心转换方法:HTML字符串到PDF、实时URL到PDF和本地HTML文件到PDF。 它还涵盖安装、许可证配置以及开发者最常使用的渲染选项。

Java库的API结构与IronPDF for .NET相似,因此在两个运行时之间工作的团队会发现过渡非常简单。 本教程中所有示例的源代码可在GitHub上获得。

快速入门:在Java中将HTML转换为PDF

将 IronPDF 添加到您的 Maven pom.xml 中,然后调用一个方法即可生成 PDF:

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/quickstart.java
import com.ironsoftware.ironpdf.*;

// Set your license key before any rendering calls
License.setLicenseKey("YOUR-LICENSE-KEY");

// Convert an HTML string to a PDF and save it
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF for Java!</h1>");
pdf.saveAs("output.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/quickstart.java
import com.ironsoftware.ironpdf.*;

// Set your license key before any rendering calls
License.setLicenseKey("YOUR-LICENSE-KEY");

// Convert an HTML string to a PDF and save it
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF for Java!</h1>");
pdf.saveAs("output.pdf");
JAVA

今天在您的项目中使用 IronPDF,免费试用。

第一步:
green arrow pointer

目录


安装 IronPDF for Java

IronPDF for Java通过Maven Central和作为独立JAR发布。 对于大多数项目,推荐使用Maven路径,因为它能处理传递依赖关系,并保持开发者机器和CI管道中的库版本一致。

选项1:将IronPDF添加为Maven依赖项

打开项目的 pom.xml 文件,并在 <dependencies> 块中添加以下条目:

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/maven-dependency.xml
<dependencies>

    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>
</dependencies>
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/maven-dependency.xml
<dependencies>

    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>
</dependencies>
XML

第一个工件拉取最新的IronPDF for Java版本。 第二个工件激活SLF4J日志记录,以便IronPDF的渲染引擎可以在执行期间写入诊断消息。 偏好Logback或Log4J的开发者可以替换为该提供者。 日志记录依赖是可选的——如果不需要日志,请忽略它。

保存文件后,从项目根目录运行 mvn install 以下载这两个库。 Maven会自动解析完整的依赖关系图,包括IronPDF所需的任何传递依赖。

对于 Gradle 项目,build.gradle 中对应的依赖声明为:

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/gradle-dependency.java
// build.gradle (Groovy DSL)
// dependencies {
//     implementation 'com.ironsoftware:ironpdf:[LATEST_VERSION]'
//     implementation 'org.slf4j:slf4j-simple:[LATEST_VERSION]'
// }
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/gradle-dependency.java
// build.gradle (Groovy DSL)
// dependencies {
//     implementation 'com.ironsoftware:ironpdf:[LATEST_VERSION]'
//     implementation 'org.slf4j:slf4j-simple:[LATEST_VERSION]'
// }
JAVA

请将 [LATEST_VERSION] 替换为 IronPDF 变更日志或 Maven Central 页面中该构建版本的版本号。

选项2:手动添加JAR文件

Maven Central直接下载IronPDF JAR,并将其添加到项目的classpath中。 此方法可在没有构建工具的情况下使用,但需要手动版本管理,因此最适合于不使用Maven或Gradle的旧项目,或外部网络访问受限的环境。

下载后,通过IDE的项目设置将JAR添加到项目的classpath中。 在IntelliJ IDEA中,右击项目根目录,选择"打开模块设置",导航到"依赖关系",然后添加JAR文件。在Eclipse中,右击项目,进入"属性 > Java构建路径 > 库",然后点击"添加外部JARs"。

请注意IronPDF JAR包含捆绑的Chromium引擎二进制文件。 新机器上的第一次渲染调用会将其解压到临时目录,需要花费几秒钟。 随后的调用使用已缓存的二进制文件,立即启动。 在容器化环境中,在解压路径挂载一个持久化卷,以避免在每个容器启动时重新解压。)}]

系统要求

IronPDF for Java运行于JDK 8或更高版本。 它支持Windows、Linux和macOS上的x86-64和ARM64架构。 无需外部浏览器安装——Chromium二进制文件已捆绑在JAR中。 在Linux上,确保Chromium所需的标准共享库存在。 IronPDF for Java文档列出了常见Linux发行版所需的最低包。


如何导入IronPDF并配置许可证密钥?

每个 IronPDF 类都位于 com.ironsoftware.ironpdf 包中。 导入它到所有将创建或操作PDF文档的源文件顶部。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/import-and-license.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Apply your license key before any other IronPDF calls
License.setLicenseKey("YOUR-LICENSE-KEY");

// Optional: set a custom log file path
Settings.setLogPath(Paths.get("IronPdfEngine.log"));
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/import-and-license.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Apply your license key before any other IronPDF calls
License.setLicenseKey("YOUR-LICENSE-KEY");

// Optional: set a custom log file path
Settings.setLogPath(Paths.get("IronPdfEngine.log"));
JAVA

没有许可证密钥,IronPDF在试用模式下运行,并在每个PDF页面上盖上平铺的水印。 设置密钥可以去除水印并解锁所有功能。 开始免费试用以立即获取一个密钥。

渲染后的 PDF 页面上带有 IronPDF 试用版水印

当激活试用或商业许可证时,许可证密钥是Iron Software发出的一个字符串。 将其存储在环境变量或配置文件中,而不是在源代码中进行硬编码。 一个常见的模式是在启动时从环境变量读取它:

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/license-from-env.java
import com.ironsoftware.ironpdf.*;

// Read the license key from an environment variable
String licenseKey = System.getenv("IRONPDF_LICENSE_KEY");
if (licenseKey != null && !licenseKey.isEmpty()) {
    License.setLicenseKey(licenseKey);
}
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/license-from-env.java
import com.ironsoftware.ironpdf.*;

// Read the license key from an environment variable
String licenseKey = System.getenv("IRONPDF_LICENSE_KEY");
if (licenseKey != null && !licenseKey.isEmpty()) {
    License.setLicenseKey(licenseKey);
}
JAVA

这种方法将密钥排除在版本控制之外,并使在开发、测试和生产环境之间使用不同的密钥变得简单。

重要License.setLicenseKeySettings.setLogPath 必须在调用任何渲染或操作方法之前同时被调用。 将其放置在应用程序启动时——最好放在静态初始化块或 main 入口点中。)}]


如何将HTML字符串转换为PDF?

PdfDocument.renderHtmlAsPdf 接受一段 HTML 标记字符串,并返回一个 PdfDocument 对象,该对象可在写入磁盘前进行保存、合并或修改。 这是编程生成HTML的主要方法,例如,通过将数据库值与定义为Java字符串的HTML模板或从文件加载的HTML模板组合起来建立报告。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/html-string-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Simple one-liner: convert an HTML string to a PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
pdf.saveAs("htmlstring_to_pdf.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/html-string-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Simple one-liner: convert an HTML string to a PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
pdf.saveAs("htmlstring_to_pdf.pdf");
JAVA

渲染引擎根据可选的第二个参数——基本路径来解析相对资产路径(图像、样式表、脚本)。 当提供基本路径时,引擎将其视为解析相对URL的根路径。 这使得引用本地CSS和图像文件的HTML在没有路径操作的情况下可以正确渲染。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/html-string-with-assets.java
import com.ironsoftware.ironpdf.*;

// HTML references assets in a local "assets" subfolder
String html = "<html>" +
    "<head><link rel='stylesheet' href='assets/style.css'></head>" +
    "<body><h1>Invoice</h1><img src='assets/logo.png' /></body>" +
    "</html>";

// Pass the base path so IronPDF resolves relative asset URLs
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html, "C:/my-project/templates");
pdf.saveAs("invoice.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/html-string-with-assets.java
import com.ironsoftware.ironpdf.*;

// HTML references assets in a local "assets" subfolder
String html = "<html>" +
    "<head><link rel='stylesheet' href='assets/style.css'></head>" +
    "<body><h1>Invoice</h1><img src='assets/logo.png' /></body>" +
    "</html>";

// Pass the base path so IronPDF resolves relative asset URLs
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html, "C:/my-project/templates");
pdf.saveAs("invoice.pdf");
JAVA

saveAs 方法接受绝对路径或相对路径。 如果文件不存在,库会创建该文件;如果存在,则会覆盖它。 当写入应用程序可能尚未创建的目录时,请先使用 Files.createDirectories(Paths.get("output")) 创建该目录,然后再调用 saveAs

IronPDF支持Chromium实施的完整HTML5和CSS3功能集。 通过 CSS 中 @font-face 加载的自定义字体,在字体文件位于基路径下时可正确渲染。 PDF 输出中还会包含由 JavaScript 渲染的 SVG 元素和 <canvas> 元素。

提示将HTML模板保存在专用目录中,并将该目录作为基本路径传递。 这种模式允许设计人员更新模板而无需接触任何Java代码。


如何在Java中将URL转换为PDF?

PdfDocument.renderUrlAsPdf 会获取指定 URL 的页面,等待 JavaScript 执行并加载动态内容,然后将完全渲染的 DOM 转换为 PDF。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/url-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a live web page to PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.saveAs("wikipedia_pdf_article.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/url-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a live web page to PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.saveAs("wikipedia_pdf_article.pdf");
JAVA

引擎处理身份验证头、cookie和JavaScript密集的单页应用。 对于需要登录或自定义请求头的信息页,请在调用 renderUrlAsPdf 之前,使用 ChromePdfRenderOptions 类配置请求参数。

这种转换方法对归档网页、生成合规快照以及从内部仪表板生成面向客户的报告非常有用。 完全支持通过本地网络访问的服务器生成的页面——请像处理公共 URL 一样传递 http://localhost:8080/report/123。 IronPDF会在呈现之前等待页面完全加载,因此依赖异步数据提取的仪表板会呈现出已填充的数据而不是空的图表。

对于受 HTTP 基本身份验证保护的页面,请使用 http://user:password@host/path 格式在 URL 中传递凭据。 对于受会话 Cookie 保护的页面,请在将 ChromePdfRenderOptions 对象传递给 renderUrlAsPdf 之前,先配置其 Cookie 存储器。 有关配置请求头和管理经过身份验证的URL cookie的详细信息,请参阅IronPDF for Java文档


如何将本地HTML文件转换为PDF?

PdfDocument.renderHtmlFileAsPdf 从本地文件系统读取 HTML 文件并将其渲染为 PDF。 由文件中相对路径引用的所有链接资产(CSS、JavaScript、图像)都相对于HTML文件自己的目录进行解析。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/html-file-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a local HTML file — assets resolve relative to its directory
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
pdf.saveAs("htmlfile_to_pdf.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/html-file-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a local HTML file — assets resolve relative to its directory
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
pdf.saveAs("htmlfile_to_pdf.pdf");
JAVA

这种方法是转换复杂HTML文档的最准确方法。 因为渲染引擎在文件系统路径上而不是内存字符串上操作,所以多层资产目录的相对引用在没有任何额外配置的情况下解析。 一个依赖于同一文件夹中 style.cssscript.js 的模板,无需调整路径即可正确渲染。

这种方法特别适合发票生成、合同生产以及设计师在与Java应用独立维护HTML模板的任何工作流程。 开发团队将该模板视为数据文件,将其与应用程序一同存储,并使用路径调用 renderHtmlFileAsPdf。 当设计师更新模板以更改品牌或布局时,不需要更改Java代码。

请注意IronPDF支持Chromium支持的所有现代HTML和CSS功能——Flexbox、CSS网格、CSS变量、Web字体和媒体查询都在输出PDF中正确渲染。


如何设置PDF生成选项?

ChromePdfRenderOptions 控制渲染行为:纸张尺寸、边距、Zoom 级别、打印介质类型、JavaScript 超时等。 创建一个实例,配置所需属性,并将其作为第二个参数传递给任何 render*AsPdf 方法。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/render-options.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;

ChromePdfRenderOptions options = new ChromePdfRenderOptions();

// Render the page using the print media type (uses @media print CSS rules)
options.setCssMediaType(CssMediaType.PRINT);

// Wait up to 5 seconds for JavaScript to finish executing
options.setJavaScriptTimeout(5000);

// Apply a 1.5x zoom level to scale content to fit the page
options.setZoom(150);

// Render at 150 DPI for sharper images in print output
options.setDpi(150);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Styled Report</h1>",
    options
);
pdf.saveAs("styled_report.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/render-options.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;

ChromePdfRenderOptions options = new ChromePdfRenderOptions();

// Render the page using the print media type (uses @media print CSS rules)
options.setCssMediaType(CssMediaType.PRINT);

// Wait up to 5 seconds for JavaScript to finish executing
options.setJavaScriptTimeout(5000);

// Apply a 1.5x zoom level to scale content to fit the page
options.setZoom(150);

// Render at 150 DPI for sharper images in print output
options.setDpi(150);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Styled Report</h1>",
    options
);
pdf.saveAs("styled_report.pdf");
JAVA

CssMediaType.PRINT 设置指示引擎应用 @media print CSS 规则,许多 HTML 模板使用这些规则来隐藏导航栏并应用 PRINT 专用布局。 对于使用 JavaScript 图表库(如 D3.js、Chart.js)或采用延迟加载内容的页面,setJavaScriptTimeout 方法至关重要——若超时时间过短,PDF 将在 JavaScript 完成渲染前捕获页面,导致图表空白或内容缺失。 如果渲染的PDF缺少预期内容,请增加超时时间。

setDpi 方法用于控制输出中的图像分辨率。 默认(96 DPI)适合屏幕文档。 对于将要打印或在高DPI显示器上显示的PDF,使用150或300 DPI。 较高的DPI值会成比例地增加文件大小。 有关可配置属性的完整列表,请参阅PDF生成设置代码示例


如何添加页眉和页脚?

IronPDF支持基于文本和HTML的页眉和页脚。 文本标题使用 TextHeaderFooter 对象,其中包含格式标记({date}),这些标记将在渲染时自动解析。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/headers-footers.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.headerfooter.*;

// Create a text-based header and footer
TextHeaderFooter header = new TextHeaderFooter();
header.setCenterText("Confidential — {date}");
header.setFontSize(10);

TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("My Company, Inc.");
footer.setRightText("Page {page} of {total-pages}");
footer.setFontSize(9);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Annual Report</h1>");
pdf.addTextHeaders(header);
pdf.addTextFooters(footer);
pdf.saveAs("report_with_headers.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/headers-footers.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.headerfooter.*;

// Create a text-based header and footer
TextHeaderFooter header = new TextHeaderFooter();
header.setCenterText("Confidential — {date}");
header.setFontSize(10);

TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("My Company, Inc.");
footer.setRightText("Page {page} of {total-pages}");
footer.setFontSize(9);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Annual Report</h1>");
pdf.addTextHeaders(header);
pdf.addTextFooters(footer);
pdf.saveAs("report_with_headers.pdf");
JAVA

{page}{total-pages} 标记会在页脚生成类似"第 3 页,共 12 页"的值,并随页数变化自动更新,因此渲染前无需知道最终页数。 {date} 标记将根据系统区域设置插入当前日期。 其他可用标记包括 {document-title}{url}

使用 addTextHeadersaddTextFooters 添加的页眉和页脚默认适用于文档中的每一页。 传递可选的页码范围参数来限制它们到特定页——例如,跳过封面页的页眉。

对于需要徽标、品牌颜色或自定义布局的样式化标题,请改用 HtmlHeaderFooter —— 它支持完整的 HTML 字符串,并将其渲染为与页面正文相同的效果。 有关完整HTML页眉模式的示例,请参阅自定义页眉和页脚示例


如何设置页边距和纸张尺寸?

在调用任何 render*AsPdf 方法之前,请先传入一个已配置好边距和纸张尺寸值的 ChromePdfRenderOptions 实例。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/margins-paper-size.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import com.ironsoftware.ironpdf.page.*;

ChromePdfRenderOptions options = new ChromePdfRenderOptions();

// Set uniform margins in millimeters
options.setMarginTop(20);
options.setMarginBottom(20);
options.setMarginLeft(15);
options.setMarginRight(15);

// Use A4 paper (default is Letter)
options.setPaperSize(PaperSize.A4);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<p>Page content here.</p>", options);
pdf.saveAs("a4_with_margins.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/margins-paper-size.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import com.ironsoftware.ironpdf.page.*;

ChromePdfRenderOptions options = new ChromePdfRenderOptions();

// Set uniform margins in millimeters
options.setMarginTop(20);
options.setMarginBottom(20);
options.setMarginLeft(15);
options.setMarginRight(15);

// Use A4 paper (default is Letter)
options.setPaperSize(PaperSize.A4);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<p>Page content here.</p>", options);
pdf.saveAs("a4_with_margins.pdf");
JAVA

边距值以毫米为单位。 PaperSize 枚举涵盖了标准纸张尺寸(A4、Letter、Legal、A3 等)。 需要非标准尺寸的开发者可以使用 options.setCustomPaperWidthoptions.setCustomPaperHeight 设置自定义宽度和高度。 自定义纸张尺寸示例自定义边距示例展示了完整的配置模式。


如何在PDF上应用水印?

IronPDF中的水印是在每页上以可配置的不透明度盖印的HTML。 这种方法让开发人员对水印的外观有完全控制——任何HTML元素、图像或样式文本都可以作为印章。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/watermark.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Confidential Report</h1><p>Internal use only.</p>");

// Define the watermark using an HTML string
String watermarkHtml = "<h1 style='color:rgba(200,0,0,0.3); transform:rotate(-45deg);'>DRAFT</h1>";

// Stamp the watermark on all pages at 50% opacity
pdf.applyStamp(watermarkHtml);

pdf.saveAs("draft_watermark.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/watermark.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Confidential Report</h1><p>Internal use only.</p>");

// Define the watermark using an HTML string
String watermarkHtml = "<h1 style='color:rgba(200,0,0,0.3); transform:rotate(-45deg);'>DRAFT</h1>";

// Stamp the watermark on all pages at 50% opacity
pdf.applyStamp(watermarkHtml);

pdf.saveAs("draft_watermark.pdf");
JAVA

applyStamp 方法接受 HtmlStampOptions 参数以实现精确定位——居中、左上角、自定义像素偏移量以及 z-index(前景或背景)。 将印章设置为背景会将其置于文本后面,以保持文档可读。 设置为前景则将其放在顶部,这在打印时更难以遮挡。

提示要产生重复平铺水印——IronPDF本身在试用模式下应用的类型——在HTML印章字符串中渲染一个旋转的文本元素网格,并将元素的大小调整为填满整个页面。

有关背景水印、平铺图案和通过升级许可证去除水印的例子,请参阅自定义水印指南


如何将多个PDF合并为一个?

PdfDocument.merge 将两个或多个 PdfDocument 对象按顺序组合,并返回一个新的文档。 这是一种从组件部分组装报告、附加封面或拼接批处理作业中的每用户部分的优选方法。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/merge-pdfs.java
import com.ironsoftware.ironpdf.*;
import java.util.Arrays;
import java.util.List;

// Render two separate HTML documents into PDFs
PdfDocument cover    = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1>");
PdfDocument body     = PdfDocument.renderHtmlAsPdf("<h1>Report Body</h1><p>Section one...</p>");
PdfDocument appendix = PdfDocument.renderHtmlAsPdf("<h2>Appendix A</h2>");

// Merge all three into a single PDF in the specified order
List<PdfDocument> parts = Arrays.asList(cover, body, appendix);
PdfDocument merged = PdfDocument.merge(parts);
merged.saveAs("full_report.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/merge-pdfs.java
import com.ironsoftware.ironpdf.*;
import java.util.Arrays;
import java.util.List;

// Render two separate HTML documents into PDFs
PdfDocument cover    = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1>");
PdfDocument body     = PdfDocument.renderHtmlAsPdf("<h1>Report Body</h1><p>Section one...</p>");
PdfDocument appendix = PdfDocument.renderHtmlAsPdf("<h2>Appendix A</h2>");

// Merge all three into a single PDF in the specified order
List<PdfDocument> parts = Arrays.asList(cover, body, appendix);
PdfDocument merged = PdfDocument.merge(parts);
merged.saveAs("full_report.pdf");
JAVA

合并输出中的每个源文档的页面按源列表指定的顺序出现。 合并后的文档不会继承任何原始文档的元数据——若这些字段对下游用户重要,请在合并后使用 PdfDocument.getPdfMetaData() 更新 meta.title 及其他文档属性。

merge 方法还提供了一个接受两个 PdfDocument 实例作为参数的重载版本。 对于许多文档的大量合并,请使用列表重载——它比链接多个双参数调用更有效,因为它在一次传递中处理所有源。

请注意合并列表中的每个源 PdfDocument 在调用后仍保持有效且未更改。 merged 实例是一个新的、独立的文档。 (当不再需要源文档时,请使用其 close() 方法释放相关的本地资源。)}]


如何添加或删除PDF中的页面?

可通过 PdfDocument.copyPagesPdfDocument.removePages 方法,将单个页面从一个文档复制到另一个文档,或直接删除。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/page-operations.java
import com.ironsoftware.ironpdf.*;
import java.util.Arrays;

// Generate a multi-page document using CSS page breaks
PdfDocument report = PdfDocument.renderHtmlAsPdf(
    "<p>Page 1 content</p>" +
    "<div style='page-break-after:always;'></div>" +
    "<p>Page 2 content</p>" +
    "<div style='page-break-after:always;'></div>" +
    "<p>Page 3 content</p>"
);

// Remove page 2 (zero-indexed — page index 1)
report.removePages(Arrays.asList(1));

// Save the two-page result
report.saveAs("two_page_report.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/page-operations.java
import com.ironsoftware.ironpdf.*;
import java.util.Arrays;

// Generate a multi-page document using CSS page breaks
PdfDocument report = PdfDocument.renderHtmlAsPdf(
    "<p>Page 1 content</p>" +
    "<div style='page-break-after:always;'></div>" +
    "<p>Page 2 content</p>" +
    "<div style='page-break-after:always;'></div>" +
    "<p>Page 3 content</p>"
);

// Remove page 2 (zero-indexed — page index 1)
report.removePages(Arrays.asList(1));

// Save the two-page result
report.saveAs("two_page_report.pdf");
JAVA

IronPDF中的页面索引是从零开始的。 删除多页时,请将所有索引通过单次 removePages 调用传入,而非在循环中多次调用,因为每次删除都会导致后续页面的索引发生偏移。 一次传递完整列表可以避免索引漂移。 例如,要从一份五页的文档中删除第 2 页和第 4 页,应传递 Arrays.asList(1, 3) —— 而不是分别调用两次。

若需插入外部 PDF 中的页面(例如,从静态模板中追加法律声明),请使用 PdfDocument.insertPdf 在特定位置拼接外部文档。 接收文档的页数在插入后立即更新。

css page-break-after:always CSS 属性是强制在将渲染为 PDF/A 的 HTML 中插入分页的标准方法。 IronPDF 还支持较新的 break-after: page CSS 属性。 两种方法都在不需要任何特殊Java代码的情况下产生可预测的分页符。


如何在Java中为PDF设置密码保护?

IronPDF支持PDF上的两种不同密码:控制编辑、打印和复制权限的所有者密码和控制文档打开的用户密码。 两者均通过 SecurityOptions 类进行设置。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/password-protect.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.security.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Secure Document</h1>");

SecurityOptions security = new SecurityOptions();

// Require a password to open the document
security.setUserPassword("user123");

// Require a separate password to edit, print, or copy content
security.setOwnerPassword("owner456");

// Restrict printing to prevent unauthorized reproduction
security.setAllowUserPrinting(PrintOptions.FullPrintQuality);

PdfSecurityManager securityManager = new PdfSecurityManager(pdf);
securityManager.setSecurityOptions(security);

pdf.saveAs("secure_document.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/password-protect.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.security.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Secure Document</h1>");

SecurityOptions security = new SecurityOptions();

// Require a password to open the document
security.setUserPassword("user123");

// Require a separate password to edit, print, or copy content
security.setOwnerPassword("owner456");

// Restrict printing to prevent unauthorized reproduction
security.setAllowUserPrinting(PrintOptions.FullPrintQuality);

PdfSecurityManager securityManager = new PdfSecurityManager(pdf);
securityManager.setSecurityOptions(security);

pdf.saveAs("secure_document.pdf");
JAVA

AllowUserPrinting 设置接受 PrintOptions 枚举值:LowQualityPrintNoPrint。 当设置所有者密码但用户密码保留为空时,文档在打开时不需要密码,但在PDF编辑器中进行编辑和其他操作需要所有者密码。

警告PDF密码保护加密文件但不能替代适当的访问控制系统。 有决心的用户使用专业工具可以尝试对弱密码进行暴力攻击。 对需要真正安全的文档使用强大、随机生成的密码。)}]


如何转换带有动态数据的HTML模板?

从数据驱动的HTML模板生成PDF是IronPDF的最常见生产使用案例之一。 标准做法是在 Java 中使用模板库或字符串操作构建 HTML 字符串,然后将生成的字符串传递给 renderHtmlAsPdf

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/dynamic-template.java
import com.ironsoftware.ironpdf.*;

// Simulate data from a database or service layer
String customerName  = "Acme Corp";
String invoiceNumber = "INV-20240501";
String totalAmount   = "$1,250.00";
String dueDate       = "2024-06-01";

// Build the HTML template with real data injected
String html = "<!DOCTYPE html><html><head>" +
    "<style>body{font-family:Arial,sans-serif;margin:40px;}" +
    "table{width:100%;border-collapse:collapse;}" +
    "th,td{border:1px solid #ccc;padding:8px;text-align:left;}" +
    "th{background:#f4f4f4;}</style></head><body>" +
    "<h1>Invoice</h1>" +
    "<p><strong>Customer:</strong> " + customerName + "</p>" +
    "<p><strong>Invoice #:</strong> " + invoiceNumber + "</p>" +
    "<table><tr><th>Description</th><th>Amount</th></tr>" +
    "<tr><td>Professional Services</td><td>" + totalAmount + "</td></tr>" +
    "</table>" +
    "<p><strong>Due Date:</strong> " + dueDate + "</p>" +
    "</body></html>";

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
pdf.saveAs(invoiceNumber + ".pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/dynamic-template.java
import com.ironsoftware.ironpdf.*;

// Simulate data from a database or service layer
String customerName  = "Acme Corp";
String invoiceNumber = "INV-20240501";
String totalAmount   = "$1,250.00";
String dueDate       = "2024-06-01";

// Build the HTML template with real data injected
String html = "<!DOCTYPE html><html><head>" +
    "<style>body{font-family:Arial,sans-serif;margin:40px;}" +
    "table{width:100%;border-collapse:collapse;}" +
    "th,td{border:1px solid #ccc;padding:8px;text-align:left;}" +
    "th{background:#f4f4f4;}</style></head><body>" +
    "<h1>Invoice</h1>" +
    "<p><strong>Customer:</strong> " + customerName + "</p>" +
    "<p><strong>Invoice #:</strong> " + invoiceNumber + "</p>" +
    "<table><tr><th>Description</th><th>Amount</th></tr>" +
    "<tr><td>Professional Services</td><td>" + totalAmount + "</td></tr>" +
    "</table>" +
    "<p><strong>Due Date:</strong> " + dueDate + "</p>" +
    "</body></html>";

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
pdf.saveAs(invoiceNumber + ".pdf");
JAVA

对于较大的项目,考虑使用ThymeleafFreemarker这样一个Java模板库来管理HTML模板作为单独的文件,通过上下文对象注入数据,并保持比字符串连接更干净的模板语法。 这两个库均会生成一个纯文本 HTML 字符串,该字符串可直接传递给 renderHtmlAsPdf

提示在批处理任务中生成 PDF 时——例如,为每位客户生成一张发票——请在循环开始前实例化 ChromePdfRenderOptions 一次,并在每次渲染调用中复用该实例。 每次调用创建新的选项对象会增加不必要的对象分配开销。


如何在Java中提取PDF中的文本?

PdfDocument.extractAllText 会读取 PDF 中每页的所有文本内容,并将其作为单个字符串返回。 这对于搜索索引、数据提取和渲染后的内容验证非常有用。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/extract-text.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Open an existing PDF (or use the result of a render call)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("output.pdf"));

// Extract all text content as a plain string
String text = pdf.extractAllText();
System.out.println(text);
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/extract-text.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Open an existing PDF (or use the result of a render call)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("output.pdf"));

// Extract all text content as a plain string
String text = pdf.extractAllText();
System.out.println(text);
JAVA

返回的字符串保留每页文本的阅读顺序,但不包括格式。 列与表格单元格之间的空白用空格表示。 对于包含多个逻辑章节的 PDF 文件,extractTextFromPage(int pageIndex) 可将单页文本隔离出来,这在逐页处理大型文档时更为高效。

文本提取仅适用于文本以实际文本对象形式存储在 PDF 结构中的 PDF 文件——由 renderHtmlAsPdf 生成的 PDF 文件始终符合条件。 扫描的文档,其页面为图像,需要在文本提取之前进行OCR。 IronOCR是一个补充的Iron Software库,增加了OCR功能到Java和.NET应用。

对于图像提取,请使用 pdf.extractAllImages(),该方法将返回一个 BufferedImage 对象列表,列表中每个对象对应文档中发现的一张图像。 有关完整的代码模式示例,请参阅从PDF提取文本示例从PDF中提取图像示例


如何压缩PDF文件?

PdfDocument.compressImages 通过以较低质量重新编码嵌入的图像来减小文件大小。 这对于从包含大照片或横幅图像的网页生成的PDF特别有效。

//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/compress-pdf.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

PdfDocument pdf = PdfDocument.fromFile(Paths.get("large_report.pdf"));

// Compress embedded images to 60% quality (0–100 scale)
pdf.compressImages(60);

pdf.saveAs("compressed_report.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf/compress-pdf.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

PdfDocument pdf = PdfDocument.fromFile(Paths.get("large_report.pdf"));

// Compress embedded images to 60% quality (0–100 scale)
pdf.compressImages(60);

pdf.saveAs("compressed_report.pdf");
JAVA

50到75之间的质量值通常将文件大小减少40–70%,并对屏幕阅读提供可接受的视觉保真度。 低于40的值可能会在照片上引入可见的伪影,虽然它们对于具有大块纯色区域的图表和截图来说是可以接受的。

重载的 compressImages(int quality, boolean scaleExistingImages) 方法还接受一个布尔值,用于控制是否缩放那些尺寸大于 PDF 中显示尺寸的图像。 将其设置为 true 还能进一步减小文件大小,因为这样可以消除嵌入高分辨率图像但在页面上以较小尺寸显示时产生的冗余分辨率。 这在网页到PDF的转换中很常见,其中图像以2x分辨率提供,以支持视网膜显示。

PDF压缩示例展示了跨多页文档的批量压缩,包括如何在压缩后验证大小减少。


下一步

本教程涵盖了三种HTML到PDF转换方法、安装、许可证配置、渲染选项、页眉和页脚、页面布局设置、文本提取和文件压缩。

要深入了解,请在IronPDF for Java文档中探索这些资源:

  1. PDF生成设置——配置DPI、缩放、超时和CSS媒体类型以实现精确渲染控制。
  2. 页眉和页脚——添加HTML页眉和页脚,带品牌徽标和自定义布局。
  3. 页面布局——设置自定义边距纸张尺寸以生成可打印的输出。
  4. 水印——应用背景和前景水印以实现文档安全。
  5. 内容提取——从PDF中提取文本提取图像以进行后续处理。
  6. 文件压缩——减小PDF文件大小以便于存储和电子邮件传输。
  7. API参考——浏览完整的IronPDF Java API参考,了解每个类和方法。

开始免费试用,今天就在您的Java应用中开始将HTML转换为PDF。 当您准备好部署时,查看许可选项以找到适合您项目的计划。

常见问题解答

如何在 Java 中将 HTML 字符串转换为 PDF?

使用您的 HTML 字符串调用 PdfDocument.renderHtmlAsPdf。传递可选的基础路径作为第二个参数,以便相对 CSS、图像和脚本引用能正确解析。调用返回的 PdfDocument 上的 saveAs 来写入文件。

如何在 Java 中将 URL 转换为 PDF?

使用完全合格的 URL 调用 PdfDocument.renderUrlAsPdf。IronPDF 获取页面,等待 JavaScript 执行,并将加载完成的 DOM 渲染为 PDF。

如何在 Java 中将本地 HTML 文件转换为 PDF?

使用绝对文件路径调用 PdfDocument.renderHtmlFileAsPdf。HTML 文件中的所有相对资产引用都会自动相对于该文件所在目录解析。

如何使用 Maven 在 Java 项目中安装 IronPDF?

将 IronPDF 依赖项添加到 pom.xml 中,用 groupId com.ironsoftwareartifactId ironpdf,然后从项目根目录运行 mvn install

如何去除 IronPDF 生成的 PDF 上的水印?

在任何渲染调用之前使用有效的许可证密钥调用 License.setLicenseKey。没有许可证密钥,IronPDF 在每页都会贴上平铺水印。

如何在 Java 中将页眉和页脚添加到 PDF?

创建一个 TextHeaderFooter 实例,使用格式令牌(如 {page}{total-pages})设置其文本属性,然后调用 pdf.addTextHeaderspdf.addTextFooters。对于带有标志的样式页眉,改用 HtmlHeaderFooter

如何在 Java 中设置 PDF 页面边距和纸张大小?

创建一个 ChromePdfRenderOptions 实例,调用 setMarginTopsetMarginBottomsetMarginLeftsetMarginRight(以毫米为单位)和 setPaperSize,并将 PaperSize 枚举值作为选项传递到任何渲染方法中。

如何在 Java 中将多个 PDF 合并为一个?

创建一个包含所需顺序文档的 List,然后将其传递给 PdfDocument.merge。该方法返回一个新 PdfDocument,包含所有来源的所有页面。

如何在 Java 中给 PDF 设置密码保护?

创建一个 SecurityOptions 实例,调用 setUserPasswordsetOwnerPassword,然后在保存文档前通过 PdfSecurityManager 应用该设置。

如何在 Java 中从 PDF 中提取文本?

调用 pdf.extractAllText() 以将所有文本内容检索为单个字符串。使用 extractTextFromPage(int pageIndex) 从特定页面提取文本。

Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。

准备开始了吗?
版本: 2026.5 just released
Still Scrolling Icon

还在滚动吗?

想快速获得证据?
运行示例看着你的HTML代码变成PDF文件。