如何在 Java 中创建 PDF 文件
在Java中创建PDF文件是企业应用程序的常见要求:按需生成发票和报告,生成证书、收据和审计日志。 IronPDF for Java使用完整的Chromium渲染引擎将HTML转换为PDF,这意味着任何HTML5、CSS3和JavaScript内容都能忠实渲染,没有格式丢失。
本指南涵盖了三种PDF创建方法:从HTML字符串、从本地HTML文件和从实时URL。 它还涵盖了页面格式、密码保护和Spring Boot集成。
快速入门:在Java中从HTML创建PDF
- 将IronPDF添加到您的
pom.xml:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-dependency.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-dependency.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
- 导入库并创建PDF:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/quickstart.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;
// Set your license key (remove watermarks in production)
License.setLicenseKey("Your-License-Key");
// Convert HTML string to PDF and save
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello, IronPDF!</h1>");
pdf.saveAs(Paths.get("output.pdf"));
如何在Java中创建PDF文件
- 通过Maven或Gradle安装IronPDF Java库
- 导入
com.ironsoftware.ironpdf.*并设置您的许可证密钥 - 调用
PdfDocument.renderHtmlAsPdf(),使用HTML字符串在内存中创建PDF - 使用
PdfDocument.renderHtmlFileAsPdf()将本地HTML文件转换为PDF - 调用
pdf.saveAs()将完成的文档写入磁盘
IronPDF for Java是什么?为什么使用它?
IronPDF for Java是一个基于Chromium渲染引擎建造的PDF生成和操作库。由于它像Chrome一样精确渲染HTML,因此能够处理复杂布局,自定义字体,CSS动画,JavaScript生成的内容以及嵌入的图像,无需手动布局代码。
该库涵盖了单个依赖项的完整PDF生命周期。 开发者可以从头创建文档,转换现有HTML内容,合并或拆分文件,添加水印,用密码加密,提取文本和图像,生成可填写的表单,所有这些都通过一个一致的API。 对于HTML繁重的工作流,IronPDF避免了使用低级PDF库如Apache PDFBox所需的手动页面布局计算。
不像iText,大多数商业用途需要AGPL开源许可证条款,IronPDF附带商业友好的许可,且无需复杂的许可证合规审查。 IronPDF for Java 作为Maven工件发布并可以在Windows、Linux和macOS上运行。 它可以与Spring Boot、Jakarta EE以及独立的Java应用程序进行集成。 该库还支持在AWS、Azure和Google Cloud上的服务器部署。
在Java中使用IronPDF的前提条件是什么?
需要哪个Java版本和构建工具?
IronPDF for Java需要JDK 8或更高版本。 建议的最低生产使用版本为JDK 11(LTS)。 从Oracle下载页面下载JDK,或使用如Eclipse Temurin这样的OpenJDK发行版。
Maven (3.6+) 和Gradle (7.0+) 都受到支持。 Maven 是企业级Java项目更常见的选择。
如何将IronPDF添加到Maven项目?
打开项目的<dependencies>块中添加以下依赖项:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-full.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-full.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
保存后,运行mvn install或让您的IDE自动解决依赖项。 Maven从Maven Central下载IronPDF,因此无需私人仓库配置。
如何将IronPDF添加到Gradle项目?
在dependencies块中添加以下代码行:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/gradle-dependency.gradle
implementation 'com.ironsoftware:ironpdf:2024.9.1'
运行gradle build以获取库。 检查Maven Central以获取最新发布的版本。
需要哪些导入和配置?
在Java源文件的开头添加这些导入语句:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/imports.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperOrientation;
import com.ironsoftware.ironpdf.render.PaperSize;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
在生成任何PDF之前,请在main方法或应用程序启动时设置您的许可证密钥:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
License.setLicenseKey("Your-License-Key");
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
License.setLicenseKey("Your-License-Key");
注意:如果没有有效的许可证密钥,生成的PDF会有试用水印。 购买许可证或者开始免费试用以去除它。 参见在Java中使用许可证密钥以获取其他配置选项。
如何在Java中从HTML字符串创建PDF?
将任何HTML字符串直接传递给PdfDocument.renderHtmlAsPdf()。 IronPDF返回一个PdfDocument实例,表示在内存中完成的文档。 调用saveAs()将其写入磁盘。
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-to-pdf.java
// HTML content with inline CSS
String htmlContent = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
// Render HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlContent);
// Save to disk
pdf.saveAs(Paths.get("html.pdf"));
renderHtmlAsPdf()支持完整的HTML5和CSS3规范,包括网页字体、Flexbox、Grid布局和JavaScript执行。 以下示例使用具有自定义样式的多行HTML模板:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-styled.java
// Multi-line HTML with CSS styling using a text block (Java 13+)
String styledHtml = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #2563eb; border-bottom: 2px solid #e5e7eb; padding-bottom: 8px; }
.summary { background: #f3f4f6; padding: 16px; border-radius: 4px; }
</style>
</head>
<body>
<h1>Invoice #1042</h1>
<div class="summary">
<p>Amount due: $1,250.00</p>
<p>Due date: 2024-06-01</p>
</div>
</body>
</html>
""";
PdfDocument invoice = PdfDocument.renderHtmlAsPdf(styledHtml);
invoice.saveAs(Paths.get("invoice.pdf"));
上面的发票示例使用Java文本块(自Java 13起可用)来实现更清洁的多行HTML。 对于较旧的Java版本,手动连接HTML字符串或使用renderHtmlFileAsPdf()从文件中加载。 若要更广泛地了解HTML到PDF的转换包括JavaScript渲染,请参见HTML到PDF教程Java版。
如何在Java中从本地HTML文件创建PDF?
使用PdfDocument.renderHtmlFileAsPdf()转换存储在本地文件系统上的HTML文件。 传递路径作为字符串; 相对路径相对于当前工作目录解析:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-file-to-pdf.java
// Convert a local HTML file to PDF
PdfDocument filePdf = PdfDocument.renderHtmlFileAsPdf("invoice-template.html");
// Save the converted document
filePdf.saveAs(Paths.get("invoice_output.pdf"));
IronPDF将所有引用的资源(外部CSS文件、本地图像和JavaScript库)相对于HTML文件所在的目录进行解析。 这意味着您可以构建一个完整的HTML模板与链接样式表,并通过IronPDF运行它而无需修改任何资源路径。
该方法接受java.nio.file.Path对象。 用于生产使用,偏好使用绝对路径以避免工作目录歧义。 参见HTML文件到PDF示例以获取完整的工作演示。
如何在Java中从网页URL创建PDF?
PdfDocument.renderUrlAsPdf()获取实时URL,使用Chromium渲染,并返回PDF。 这对于捕获仪表盘快照,从托管的收据页面生成PDF收据,或归档网络内容有用:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf.java
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
webPdf.saveAs(Paths.get("ironpdf-homepage.pdf"));
对于需要HTTP身份验证的页面,通过ChromePdfRenderOptions传递凭据:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf-auth.java
// Configure render options with login credentials
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setAuthUsername("username");
renderOptions.setAuthPassword("password");
// Render authenticated page to PDF
PdfDocument securedPdf = PdfDocument.renderUrlAsPdf("https://your-internal-app.com/report", renderOptions);
securedPdf.saveAs(Paths.get("internal-report.pdf"));
参见URL到PDF代码示例以了解详细信息。 对于使用cookies或基于表单身份验证的更复杂登录流程,请参阅网站登录处理。
如何控制页面大小、方向和边距?
使用ChromePdfRenderOptions自定义输出PDF的物理布局。 将配置选项作为第二参数传递给任何渲染方法。 最常见的设置是页面方向、纸张尺寸和边距:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/pdf-formatting.java
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
// Set landscape orientation (default is portrait)
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
// Use US Letter paper size (default is A4)
renderOptions.setPaperSize(PaperSize.LETTER);
// Set margins in millimeters (top, right, bottom, left)
renderOptions.setMarginTop(15);
renderOptions.setMarginRight(15);
renderOptions.setMarginBottom(15);
renderOptions.setMarginLeft(15);
// Include background colors and images
renderOptions.setPrintHtmlBackgrounds(true);
// Apply options when rendering
PdfDocument report = PdfDocument.renderHtmlAsPdf("<h1>Quarterly Report</h1>", renderOptions);
report.saveAs(Paths.get("report.pdf"));
ChromePdfRenderOptions暴露了超过30项设置,超出了上面显示的,包括DPI、JavaScript执行超时、缩放因子和CSS媒体类型。 请参阅PDF生成设置以获取完整列表。对于PaperSize枚举中没有的自定义纸张大小,请参阅自定义PDF纸张大小。
如何为Java中的PDF添加密码保护?
SecurityOptions控制读取和所有者密码以及权限标志。 在保存之前,将SecurityManager:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-basic.java
// Create security settings with a user-facing password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
// Apply security to the document
PdfDocument urlPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
SecurityManager securityManager = urlPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
// Save the password-protected document
urlPdf.saveAs(Paths.get("protected.pdf"));
用于更严格的控制,设置所有者密码并限制特定操作:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-advanced.java
SecurityOptions advancedSecurity = new SecurityOptions();
// User password: required to open the file
advancedSecurity.setUserPassword("user-open-pass");
// Owner password: required to change security settings
advancedSecurity.setOwnerPassword("owner-admin-pass");
// Restrict editing operations
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-advanced.java
SecurityOptions advancedSecurity = new SecurityOptions();
// User password: required to open the file
advancedSecurity.setUserPassword("user-open-pass");
// Owner password: required to change security settings
advancedSecurity.setOwnerPassword("owner-admin-pass");
// Restrict editing operations
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
打开PDF时提示读者输入密码:
输入正确密码后,PDF打开并显示完整内容:
请参阅安全和元数据设置以获取权限标识的完整列表。
如何在Spring Boot应用程序中生成PDF?
IronPDF直接与Spring Boot集成。 从任何控制器方法返回PDF作为字节数组HTTP响应; 此模式适用于按需生成报告、发票下载和数据导出。
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/spring-boot-controller.java
import com.ironsoftware.ironpdf.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
@GetMapping("/invoice/{id}")
public ResponseEntity<byte[]> generateInvoice(@PathVariable String id) throws IOException {
// Build HTML dynamically using the invoice ID
String html = """
<html><body>
<h1>Invoice #%s</h1>
<p>Amount due: $500.00</p>
</body></html>
""".formatted(id);
// Render and return as PDF download
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
byte[] pdfBytes = pdf.getBinaryData();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", "invoice-" + id + ".pdf");
return ResponseEntity.ok().headers(headers).body(pdfBytes);
}
}
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/spring-boot-controller.java
import com.ironsoftware.ironpdf.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
@GetMapping("/invoice/{id}")
public ResponseEntity<byte[]> generateInvoice(@PathVariable String id) throws IOException {
// Build HTML dynamically using the invoice ID
String html = """
<html><body>
<h1>Invoice #%s</h1>
<p>Amount due: $500.00</p>
</body></html>
""".formatted(id);
// Render and return as PDF download
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
byte[] pdfBytes = pdf.getBinaryData();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", "invoice-" + id + ".pdf");
return ResponseEntity.ok().headers(headers).body(pdfBytes);
}
}
getBinaryData()方法以字节数组形式返回PDF,Spring Boot直接将其流式传输给客户端。 不会向磁盘写入任何临时文件。 对于高吞吐量部署,在License.setLicenseKey(),而不是每次请求。
Java PDF创建的下一步是什么?
本指南演示了使用IronPDF在Java中进行PDF生成的四种方法:HTML字符串渲染、本地文件转换、URL捕获及Spring Boot HTTP响应流。 所有方法共享相同的SecurityOptions用于访问保护。
IronPDF for Java还支持添加和盖章水印、合并多个PDF文件、将PDF拆分为单独的页面、添加数字签名、将JavaScript图表渲染为PDF以及程序化打印PDF。
开始免费试用以生成无水印PDF,或查看许可选项以选择适合您项目的方案。 准备更深入探索吗? 查看完整的IronPDF for Java教程页面。
常见问题解答
如何在Java中从HTML字符串创建PDF?
将您的HTML字符串传递给PdfDocument.renderHtmlAsPdf()。该方法在内存中返回PdfDocument对象。调用pdf.saveAs(Paths.get("output.pdf"))将其写入磁盘。IronPDF支持完整的HTML5、CSS3和JavaScript。
IronPDF需要哪个Java版本?
IronPDF for Java需要JDK 8或更高版本。JDK 11 LTS是生产部署的推荐最低要求。
如何将IronPDF添加到Maven项目中?
在pom.xml的<dependencies>部分内添加groupId com.ironsoftware和artifactId ironpdf的依赖块,然后运行mvn install。
如何在Java中从本地HTML文件创建PDF?
使用HTML文件路径调用PdfDocument.renderHtmlFileAsPdf()。IronPDF自动解析所有相对于文件目录的链接CSS、图像和JavaScript。
我可以在Java中从URL创建PDF吗?
是的。使用目标URL调用PdfDocument.renderUrlAsPdf()。IronPDF使用Chromium获取页面并返回PdfDocument。对于HTTP认证后的页面,通过ChromePdfRenderOptions传递凭据。
如何使用IronPDF在Java中保护PDF并设置密码?
创建SecurityOptions对象,使用您的密码调用setUserPassword(),然后在调用saveAs()之前将选项传递给urlPdf.getSecurity().setSecurityOptions()。
如何在Spring Boot应用程序中使用IronPDF?
将您的PDF生成逻辑注入到@RestController方法中。调用PdfDocument.renderHtmlAsPdf(),然后使用pdf.getBinaryData()获取字节数组,并用MediaType.APPLICATION_PDF将其作为ResponseEntity<byte[]>返回。
如何在Java中为IronPDF设置页面大小和方向?
创建ChromePdfRenderOptions对象,调用setPaperSize()和setPaperOrientation(),然后作为第二个参数传递给任何渲染方法。在设置方向之前设置纸张大小以避免顺序冲突。
IronPDF是否运行在Linux和macOS上用Java?
是的。IronPDF for Java在Windows、Linux和macOS上运行。它还支持在AWS、Azure和Google Cloud上的云部署,无需外部PDF查看器或渲染引擎。
没有许可证密钥,PDF会有水印吗?
是的。没有有效的许可证密钥,IronPDF会在所有生成的文档上添加试用水印。在应用程序启动时调用License.setLicenseKey()并使用有效密钥以去除它。




