用 Java 将 HTML 转换为 PDF.

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

IronPDF for Java使用现代浏览器中的相同渲染引擎将HTML内容转换为像素完美的PDF文档。 Java应用程序可以从HTML字符串、本地HTML文件或实时网页生成PDF,无需任何额外的渲染软件或GUI环境。

本教程涵盖了IronPDF for Java中提供的三种HTML到PDF转换方法,以及安装、许可和配置选项。 已经使用IronPDF for .NET的开发者将会发现Java API很熟悉; 等效的.NET教程可在HTML到PDF for .NET教程中找到。

请注意IronPDF for Java需要Java 8或更高版本,并与包括Spring Boot、Java EE和Micronaut在内的所有主要基于JVM的框架兼容。

快速入门:从HTML生成PDF

以下示例从HTML字符串创建一个页面的PDF并将其保存到磁盘。 通过Maven安装库(步骤1)后,这就是所有需要的代码:

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

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

// Render an HTML string to a PDF file
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1><p>Generated in Java.</p>");
pdf.saveAs("output.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/quickstart-html-string.java
import com.ironsoftware.ironpdf.*;

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

// Render an HTML string to a PDF file
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1><p>Generated in Java.</p>");
pdf.saveAs("output.pdf");
JAVA

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

第一步:
green arrow pointer

目录


如何在Java项目中安装IronPDF?

IronPDF for Java可在Maven中央存储库中获得。 推荐的安装方法是Maven,但不使用构建系统时也支持手动安装JAR。

作为Maven依赖项安装

请将以下文件添加到项目 dependencies 文件的 pom.xml 部分:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/maven-dependency.xml
<dependency>
  <groupId>com.ironsoftware</groupId>
  <artifactId>ironpdf</artifactId>
  <version>2024.9.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>2.0.5</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/maven-dependency.xml
<dependency>
  <groupId>com.ironsoftware</groupId>
  <artifactId>ironpdf</artifactId>
  <version>2024.9.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>2.0.5</version>
</dependency>
XML

第一个工件引入了IronPDF。 The second is an SLF4J logging implementation. IronPDF使用SLF4J在渲染期间发出诊断消息; you can substitute it with Logback or Log4j 2, or omit logging entirely.

在项目根目录下运行 mvn install 以下载依赖项。 在固定版本号之前检查IronPDF的最新版本,因变更日志列出了所有当前和过去的版本。

手动安装JAR

不使用Maven的开发者可以直接从Maven Central下载IronPDF胖JAR并将其添加到项目类路径中。 胖JAR捆绑了所有传递依赖项。

提示推荐在新项目中使用Maven。 JAR安装需要手动管理依赖关系,在较大的项目中可能导致版本冲突。)]}

导入IronPDF包

所有 PDF 渲染和处理类均位于 com.ironsoftware.ironpdf 包中。 在使用IronPDF的任何Java源文件中添加此导入语句:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/import-package.java
import com.ironsoftware.ironpdf.*;
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/import-package.java
import com.ironsoftware.ironpdf.*;
JAVA

设置许可证密钥

没有许可证密钥时,IronPDF将在每个页面上渲染带有平铺水印的PDF。 要移除水印,请在调用任何渲染方法之前,将有效的许可证密钥传递给 License.setLicenseKey

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-license-key.java
import com.ironsoftware.ironpdf.*;

// Set the license key before any rendering call
License.setLicenseKey("YOUR-LICENSE-KEY");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-license-key.java
import com.ironsoftware.ironpdf.*;

// Set the license key before any rendering call
License.setLicenseKey("YOUR-LICENSE-KEY");
JAVA

在应用程序启动时,在运行任何PDF生成逻辑之前进行此调用。 开始免费试用以获取试用密钥,或查看许可选项以便生产使用。

配置日志文件路径

IronPDF 会将渲染诊断信息写入应用程序工作目录中名为 IronPdfEngine.log 的日志文件中。 调用 Settings.setLogPath 来更改文件名或位置:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-log-path.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Configure logging before calling any rendering methods
Settings.setLogPath(Paths.get("logs/ironpdf.log"));
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-log-path.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Configure logging before calling any rendering methods
Settings.setLogPath(Paths.get("logs/ironpdf.log"));
JAVA

重要在执行任何 PDF 转换或处理方法之前,请调用 Settings.setLogPath。 在渲染开始后进行的调用将不起作用。)}]

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

PdfDocument.renderHtmlAsPdf 将 HTML 字符串转换为 PdfDocument 对象,该对象随后可保存到磁盘或传递给其他处理方法。 该方法支持任何符合 W3C 标准的 HTML,包括包含 <head><body> 元素的完整页面标记。

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

// Convert a simple HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save the resulting PDF to a file
pdf.saveAs("htmlstring_to_pdf.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-string-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a simple HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save the resulting PDF to a file
pdf.saveAs("htmlstring_to_pdf.pdf");
JAVA
PDF output showing a rendered H1 heading generated from an HTML string using PdfDocument.renderHtmlAsPdf

PdfDocument.renderHtmlAsPdf方法将HTML标记渲染成PDF,并保留所有符合W3C标准的样式和结构。

该方法返回一个 PdfDocument 实例。 调用 saveAs 将 PDF 写入磁盘,或使用 getBinaryData 获取原始 PDF 字节流以供流式传输或存储。

renderHtmlAsPdf 以与符合标准的浏览器相同的方式处理所有 HTML、CSS 和 JavaScript 内容。 生成的PDF准确反映了在Chrome中查看页面时的样子。

有关此方法的更多详细信息,请参阅IronPDF Java示例页面上的HTML字符串到PDF代码示例

如何在HTML字符串中加载本地资源?

HTML通常通过相对路径引用外部资源(样式表、图像、脚本)。 renderHtmlAsPdf 接受一个可选的第二个参数,用于设置解析这些引用时的基路径。 基路径可以指向本地目录或URL。

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

// HTML with references to local stylesheets and images
String html = "<html>"
    + "<head>"
    +   "<title>Invoice</title>"
    +   "<link rel='stylesheet' type='text/css' href='style.css'>"
    + "</head>"
    + "<body>"
    +   "<div class='content'>"
    +     "<h1>Invoice #1001</h1>"
    +     "<img src='logo.png' alt='Company Logo'/>"
    +   "</div>"
    + "</body>"
    + "</html>";

// The second argument resolves relative asset paths
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html, "C:/invoices/");
pdf.saveAs("invoice.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-string-local-assets.java
import com.ironsoftware.ironpdf.*;

// HTML with references to local stylesheets and images
String html = "<html>"
    + "<head>"
    +   "<title>Invoice</title>"
    +   "<link rel='stylesheet' type='text/css' href='style.css'>"
    + "</head>"
    + "<body>"
    +   "<div class='content'>"
    +     "<h1>Invoice #1001</h1>"
    +     "<img src='logo.png' alt='Company Logo'/>"
    +   "</div>"
    + "</body>"
    + "</html>";

// The second argument resolves relative asset paths
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html, "C:/invoices/");
pdf.saveAs("invoice.pdf");
JAVA
PDF output displaying an invoice with styled layout, logo image, and CSS formatting applied from local assets

提供基路径时,renderHtmlAsPdf将从该目录解析相对资产引用,生成一个完整样式的PDF。

基路径参数可以与绝对文件系统路径和URL字符串配合使用。 这使得 renderHtmlAsPdf 适合从存储在磁盘上或由 Web 服务器提供的模板生成 PDF 文件。

提示使用 Windows 风格反斜杠 (C:\invoices\) 的路径应转换为正斜杠,或使用 Paths.get() 以确保跨平台兼容性。

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

PdfDocument.renderUrlAsPdf 从指定 URL 获取实时网页并将其渲染为 PDF。 该方法加载完整页面,包括所有外部CSS、JavaScript和图像,然后再进行渲染。

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

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

// Render a live web page as a PDF document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.saveAs("url_to_pdf.pdf");
JAVA
PDF output of the Wikipedia article on PDF format, showing the page layout and content rendered by PdfDocument.renderUrlAsPdf

PdfDocument.renderUrlAsPdf方法捕获网页的完整渲染状态,包括JavaScript渲染的内容。

renderUrlAsPdf 会在 JavaScript 执行完成后才捕获渲染后的页面,这意味着动态生成的内容(如图表或通过 AJAX 加载的数据)将出现在生成的 PDF 中。

有关等效的.NET实现或其他URL到PDF选项,请参阅将URL转换为PDF代码示例

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

PdfDocument.renderHtmlFileAsPdf 读取本地 HTML 文件并将其渲染为 PDF。 HTML文件中引用的所有相对路径(样式表、图像、脚本)均相对于HTML文件目录进行解析。

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

// Convert a local HTML file to PDF
// IronPDF resolves relative asset paths from the HTML file's directory
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
pdf.saveAs("htmlfile_to_pdf.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-file-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a local HTML file to PDF
// IronPDF resolves relative asset paths from the HTML file's directory
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
pdf.saveAs("htmlfile_to_pdf.pdf");
JAVA

此方法非常适合用于模板化文档生成:发票模板、报告或存储为HTML文件的证书及其关联的CSS和图像资源。 IronPDF以与浏览器相同的精度渲染文件,保留所有CSS布局规则。

请注意HTML文件路径必须是绝对路径。 传递给 renderHtmlFileAsPdf 的相对路径将从 JVM 工作目录中解析,这在服务器环境中可能会产生意外结果。)]

如何自定义PDF输出设置?

PdfRenderOptions 类用于控制页面布局和渲染行为。 创建一个 PdfRenderOptions 实例,配置所需属性,并将其传递给任意渲染方法。

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

// Configure rendering options before generating the PDF
PdfRenderOptions options = new PdfRenderOptions();
// Set the zoom level (100 = normal size)
options.setZoom(100);
// Wait for JavaScript to finish before rendering
options.setJavaScriptTimeout(5000);
// Enable printing of background colors and images
options.setPrintBackground(true);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Customized PDF</h1>",
    options
);
pdf.saveAs("customized.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/render-options.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;

// Configure rendering options before generating the PDF
PdfRenderOptions options = new PdfRenderOptions();
// Set the zoom level (100 = normal size)
options.setZoom(100);
// Wait for JavaScript to finish before rendering
options.setJavaScriptTimeout(5000);
// Enable printing of background colors and images
options.setPrintBackground(true);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Customized PDF</h1>",
    options
);
pdf.saveAs("customized.pdf");
JAVA

PdfRenderOptions 类提供了用于控制 DPI、视口宽度、纸张方向和超时值的额外属性。 有关可用选项的完整列表,请参阅PDF生成设置代码示例

如何向PDF添加页眉和页脚?

IronPDF支持基于文本和HTML的页眉和页脚。 文本页眉使用预定义合并字段来表示常见值,如页码和文档标题; HTML页眉接受任意HTML标记,以完全自定义布局。

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

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Annual Report</h1><p>Content goes here.</p>");

// Create a text-based header using merge fields
TextHeaderFooter header = new TextHeaderFooter();
header.setCenterText("Annual Report");
header.setRightText("{page} of {total-pages}");
header.setFont(com.ironsoftware.ironpdf.font.FontTypes.Helvetica);
header.setFontSize(10.0);

// Create a text-based footer
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("Confidential");
footer.setRightText("Generated by IronPDF");

pdf.addTextHeaders(header);
pdf.addTextFooters(footer);

pdf.saveAs("report_with_headers.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/headers-footers.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.headerfooter.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Annual Report</h1><p>Content goes here.</p>");

// Create a text-based header using merge fields
TextHeaderFooter header = new TextHeaderFooter();
header.setCenterText("Annual Report");
header.setRightText("{page} of {total-pages}");
header.setFont(com.ironsoftware.ironpdf.font.FontTypes.Helvetica);
header.setFontSize(10.0);

// Create a text-based footer
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("Confidential");
footer.setRightText("Generated by IronPDF");

pdf.addTextHeaders(header);
pdf.addTextFooters(footer);

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

{page}{total-pages} 合并字段将在渲染时替换为当前页码和总页数。 对于更复杂的布局(例如包含公司徽标的页脚),请使用 HtmlHeaderFooter 代替 TextHeaderFooter

有关基于HTML的页眉和页脚的完整详细信息,请参阅添加页眉和页脚代码示例

提示页眉和页脚在页边距内进行渲染。 在应用页眉或页脚之前增加上或下页边距,以防止与页面内容重叠。

如何设置自定义页边距和页面大小?

在渲染 PDF/A 之前,页面大小和边距需在 PdfRenderOptions 对象中进行配置。 IronPDF支持标准纸张尺寸(A4、Letter、Legal)和完全自定义尺寸。

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

PdfRenderOptions options = new PdfRenderOptions();
// Set margins in millimeters: top, right, bottom, left
options.setMarginTop(25);
options.setMarginRight(20);
options.setMarginBottom(25);
options.setMarginLeft(20);
// Use A4 paper size
options.setPaperSize(PaperSize.A4);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted Document</h1>", options);
pdf.saveAs("formatted_document.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/margins-page-size.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import com.ironsoftware.ironpdf.page.*;

PdfRenderOptions options = new PdfRenderOptions();
// Set margins in millimeters: top, right, bottom, left
options.setMarginTop(25);
options.setMarginRight(20);
options.setMarginBottom(25);
options.setMarginLeft(20);
// Use A4 paper size
options.setPaperSize(PaperSize.A4);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted Document</h1>", options);
pdf.saveAs("formatted_document.pdf");
JAVA

有关支持的纸张尺寸和单位的完整列表,请参阅自定义纸张尺寸代码示例自定义页边距代码示例

如何向PDF添加水印?

PdfDocument.applyWatermark 会在文档的每一页添加文本或图像水印。 默认情况下,水印显示在页面内容下方的独立图层上;若将 isStampBehind 标志设置为 false,则水印将显示在页面内容上方。

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

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

// Apply an HTML watermark; supports full CSS styling
String watermarkHtml = "<h1 style='color: rgba(200, 0, 0, 0.2); transform: rotate(-45deg); font-size: 60px;'>DRAFT</h1>";
// Second argument: opacity (0-100), third: rotation (degrees), fourth: stamp behind content
pdf.applyWatermark(watermarkHtml, 50, 45, true);

pdf.saveAs("draft_watermarked.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/add-watermark.java
import com.ironsoftware.ironpdf.*;

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

// Apply an HTML watermark; supports full CSS styling
String watermarkHtml = "<h1 style='color: rgba(200, 0, 0, 0.2); transform: rotate(-45deg); font-size: 60px;'>DRAFT</h1>";
// Second argument: opacity (0-100), third: rotation (degrees), fourth: stamp behind content
pdf.applyWatermark(watermarkHtml, 50, 45, true);

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

HTML方法提供精确的水印样式控制,包括字体、大小、颜色和透明度。 有关高级水印配置(如重复图案平铺或基于图像的印章),请参阅水印指南

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

PdfDocument.extractAllText 读取 PDF 中嵌入的文本内容,并将其作为单个 String 返回。 此方法从文档中所有页面中提取可选择的文本。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-text.java
import com.ironsoftware.ironpdf.*;

// Load an existing PDF from disk
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("report.pdf"));

// Extract all embedded text from the document
String text = pdf.extractAllText();
System.out.println(text);
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-text.java
import com.ironsoftware.ironpdf.*;

// Load an existing PDF from disk
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("report.pdf"));

// Extract all embedded text from the document
String text = pdf.extractAllText();
System.out.println(text);
JAVA

文本提取适用于将文本存储为可选择字形的PDF。对于图像基扫描的PDF,请考虑将IronPDF与OCR库配合使用,以从渲染的页面图像中提取文本。

有关其他选项,包括每页文本提取,请参阅从PDF中提取文本代码示例

如何在Java中从PDF中提取图像?

PdfDocument.extractAllImages 返回一个 BufferedImage 对象列表,其中每个对象对应 PDF 中嵌入的一张图片。 返回的图像可以直接保存到磁盘或传递至下游图像处理逻辑。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-images.java
import com.ironsoftware.ironpdf.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;

// Load an existing PDF
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Extract all embedded images
List<BufferedImage> images = pdf.extractAllImages();
for (int i = 0; i < images.size(); i++) {
    ImageIO.write(images.get(i), "PNG", new File("extracted_image_" + i + ".png"));
}
System.out.println("Extracted " + images.size() + " image(s).");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-images.java
import com.ironsoftware.ironpdf.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;

// Load an existing PDF
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Extract all embedded images
List<BufferedImage> images = pdf.extractAllImages();
for (int i = 0; i < images.size(); i++) {
    ImageIO.write(images.get(i), "PNG", new File("extracted_image_" + i + ".png"));
}
System.out.println("Extracted " + images.size() + " image(s).");
JAVA

有关更多提取选项,包括从特定页面提取图像,请参阅从PDF中提取图像代码示例

如何压缩PDF文件?

PdfDocument.compressImages 通过以较低质量重新编码嵌入的图像来减小 PDF 文件大小。 方法接受一个质量值,从1(最低质量,最小文件)到100(最高质量)。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/compress-pdf.java
import com.ironsoftware.ironpdf.*;

// Load a large PDF with embedded images
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("large_report.pdf"));

// Compress images to 60% quality to reduce file size
pdf.compressImages(60);

pdf.saveAs("large_report_compressed.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/compress-pdf.java
import com.ironsoftware.ironpdf.*;

// Load a large PDF with embedded images
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("large_report.pdf"));

// Compress images to 60% quality to reduce file size
pdf.compressImages(60);

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

图像压缩是减少包含照片或高分辨率图形的PDF大小的最有效方法。 有关额外的文件大小减少策略,例如删除嵌入字体,请参阅PDF压缩代码示例

提示在40到70之间的质量值通常为大多数PDF用例提供文件大小减少与视觉保真度之间的良好平衡。

如何以编程方式打印PDF?

PdfDocument.print 使用标准的 Java 打印 API 将 PDF 发送至系统的默认打印机。 该方法接受一个布尔值,控制是否显示打印对话框。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/print-pdf.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Print silently to the default printer (no dialog shown)
pdf.print(false);
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/print-pdf.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Print silently to the default printer (no dialog shown)
pdf.print(false);
JAVA

true 传递给 print 方法以显示系统打印对话框,允许用户在发送打印任务前选择打印机并配置打印设置。

下一步

本教程涵盖了IronPDF for Java中的核心HTML到PDF转换方法,以及安装、配置和常见文档处理操作。

更进一步:

  1. 浏览完整的HTML到PDF Java代码示例以了解此处未涉及的其他渲染场景。
  2. 阅读IronPDF for Java文档以了解部署、线程安全和服务器配置。
  3. 探索完整的IronPDF Java API参考以获取详细的方法签名和参数描述。

开始免费试用以生成没有水印的PDF,或查看许可选项以找到适合您项目的计划。


教程快速访问

用于Java开发的IntelliJ IDEA IDE标志

下载本教程的 Java 源代码

本教程的完整HTML到PDF Java源代码可作为压缩的IntelliJ项目下载。

下载

在 GitHub 上探索此教程

该项目的源代码可作为IntelliJ IDEA项目在GitHub上获得。它可以导入到其他流行的Java IDE中,包括Eclipse和NetBeans。

Java HTML到PDF在GitHub上
用于源码库的GitHub标志
IronPDF Java API参考文档图标

查看 API 参考

探索IronPDF Java API参考,涵盖库中可用的所有命名空间、类、方法和枚举。

查看 API 参考

常见问题解答

IronPDF for Java 用于做什么?

IronPDF for Java 将 HTML 内容转换为 Java 应用程序中的 PDF 文档。它支持将 HTML 字符串、本地 HTML 文件以及实时网页 URL 转换为 PDF,还提供添加页眉和页脚、水印、文本提取、图像提取和文件压缩的工具。

如何在Java项目中安装IronPDF?

在您的 pom.xml 中添加两个 Maven 依赖项:com.ironsoftware:ironpdforg.slf4j:slf4j-simple,然后运行 mvn install。或者,从 Maven Central 下载 fat JAR 并将其添加到项目类路径中。

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

用您的 HTML 标记调用 PdfDocument.renderHtmlAsPdf(htmlString)。该方法返回一个 PdfDocument 对象。调用 pdf.saveAs("output.pdf") 将其写入磁盘。

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

调用 PdfDocument.renderUrlAsPdf("https://example.com")。IronPDF 获取页面,等待 JavaScript 执行,然后将加载完成的页面渲染为 PDF。

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

调用 PdfDocument.renderHtmlFileAsPdf("C:/path/to/file.html")。使用绝对文件路径。IronPDF 自动解析来自 HTML 文件目录的相对 CSS 和图像引用。

IronPDF for Java 会在生成的 PDF 上添加水印吗?

没有许可证密钥,IronPDF 会在所有生成的 PDF 上添加平铺水印。在任何渲染调用前设置有效许可证密钥 License.setLicenseKey("YOUR-KEY") 以删除水印。

IronPDF需要哪个Java版本?

IronPDF for Java 需要 Java 8 或更高版本。它与 Spring Boot、Java EE、Micronaut 和其他基于 JVM 的框架兼容。

如何在 Java 中使用 IronPDF 将页码添加到 PDF?

创建一个 TextHeaderFooter 实例并调用 setRightText("{page} of {total-pages}")。将该对象传递给 pdf.addTextFooters(footer)。合并字段在渲染时被替换为实际页码。

IronPDF for Java 能从 PDF 中提取文本吗?

是的。用 PdfDocument.fromFile(Paths.get("file.pdf")) 加载 PDF,然后调用 pdf.extractAllText() 来检索所有可选择的文本内容为 String。

如何在 Java 中减少 PDF 的文件大小?

调用 pdf.compressImages(quality),其中 quality 是 1 到 100 之间的整数。60 的值对于大多数 PDF 提供了文件大小和图像保真度之间的良好平衡。

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

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

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

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

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

还在滚动吗?

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