如何在 Java 中创建 PDF 文件 Copy for LLMsCopy for LLMs Copy page as Markdown for LLMs
# 如何在 Java 中创建 PDF 文件
在Java中创建PDF文件是企业应用程序的常见要求:按需生成发票和报告,生成证书、收据和审计日志。 IronPDF for Java使用完整的Chromium渲染引擎将HTML转换为PDF,这意味着任何HTML5、CSS3和JavaScript内容都能忠实渲染,没有格式丢失。
本指南涵盖了三种PDF创建方法:从HTML字符串、从本地HTML文件和从实时URL。 它还涵盖了页面格式、密码保护和Spring Boot集成。
*as-heading:2(快速入门:在Java中从HTML创建PDF)*
1. 将IronPDF添加到您的`pom.xml`:
```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>
```
2. 导入库并创建PDF:
```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"));
```
<div class="hsg-featured-snippet">
<h3>如何在Java中创建PDF文件</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="download-modal" href="#download-modal">通过Maven或Gradle安装IronPDF Java库</a></li>
<li>导入<code>com.ironsoftware.ironpdf.*</code>并设置您的许可证密钥</li>
<li>调用<code>PdfDocument.renderHtmlAsPdf()</code>,使用HTML字符串在内存中创建PDF</li>
<li>使用<code>PdfDocument.renderHtmlFileAsPdf()</code>将本地HTML文件转换为PDF</li>
<li>调用<code>pdf.saveAs()</code>将完成的文档写入磁盘</li>
</ol>
</div>
## 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](https://ironpdf.com/java/get-started/aws/)、[Azure](https://ironpdf.com/java/get-started/azure/)和[Google Cloud](https://ironpdf.com/java/get-started/google-cloud/)上的服务器部署。
[[i:(IronPDF在后台使用Chromium进行渲染。 正如Chrome中看起来正确的HTML,在PDF中也产生相同的输出,而无需浏览器到PDF格式调整的惊讶。)]]
## 在Java中使用IronPDF的前提条件是什么?
### 需要哪个Java版本和构建工具?
IronPDF for Java需要**JDK 8或更高版本**。 建议的最低生产使用版本为JDK 11(LTS)。 从<a href="https://www.oracle.com/java/technologies/javase-downloads.html" target="_blank" rel="nofollow noopener noreferrer">Oracle下载页面</a>下载JDK,或使用如<a href="https://adoptium.net/" target="_blank" rel="nofollow noopener noreferrer">Eclipse Temurin</a>这样的OpenJDK发行版。
**Maven** (3.6+) 和**Gradle** (7.0+) 都受到支持。 Maven 是企业级Java项目更常见的选择。
### 如何将IronPDF添加到Maven项目?
打开项目的`<dependencies>`块中添加以下依赖项:
```xml
//: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`块中添加以下代码行:
```groovy
//: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`以获取库。 检查<a href="https://central.sonatype.com/artifact/com.ironsoftware/ironpdf" target="_blank" rel="nofollow noopener noreferrer">Maven Central</a>以获取最新发布的版本。
### 需要哪些导入和配置?
在Java源文件的开头添加这些导入语句:
```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`方法或应用程序启动时设置您的许可证密钥:
```java
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
License.setLicenseKey("Your-License-Key");
```
**注意:**如果没有有效的许可证密钥,生成的PDF会有试用水印。 [购买许可证](/java/licensing/)或者[开始免费试用](#trial-license)以去除它。 参见[在Java中使用许可证密钥](https://ironpdf.com/java/get-started/license-keys/)以获取其他配置选项。
## 如何在Java中从HTML字符串创建PDF?
将任何HTML字符串直接传递给`PdfDocument.renderHtmlAsPdf()`。 IronPDF返回一个`PdfDocument`实例,表示在内存中完成的文档。 调用`saveAs()`将其写入磁盘。
```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模板:
```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版](https://ironpdf.com/java/tutorials/html-to-pdf/)。
[[t:(对于传递的简短HTML字符串,IronPDF会自动将内容包装在一个最小的HTML文档中。 为了完全控制head标签,meta字符集,及CSS重置,请传递完整的!DOCTYPE html文档。)]]
## 如何在Java中从本地HTML文件创建PDF?
使用`PdfDocument.renderHtmlFileAsPdf()`转换存储在本地文件系统上的HTML文件。 传递路径作为字符串; 相对路径相对于当前工作目录解析:
```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示例](https://ironpdf.com/java/examples/file-to-pdf/)以获取完整的工作演示。
## 如何在Java中从网页URL创建PDF?
`PdfDocument.renderUrlAsPdf()`获取实时URL,使用Chromium渲染,并返回PDF。 这对于捕获仪表盘快照,从托管的收据页面生成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`传递凭据:
```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代码示例](https://ironpdf.com/java/examples/converting-a-url-to-a-pdf/)以了解详细信息。 对于使用cookies或基于表单身份验证的更复杂登录流程,请参阅[网站登录处理](https://ironpdf.com/java/examples/ironpdf-website-and-system-logins/)。
## 如何控制页面大小、方向和边距?
使用`ChromePdfRenderOptions`自定义输出PDF的物理布局。 将配置选项作为第二参数传递给任何渲染方法。 最常见的设置是页面方向、纸张尺寸和边距:
```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生成设置](https://ironpdf.com/java/examples/pdf-generation-settings/)以获取完整列表。对于`PaperSize`枚举中没有的自定义纸张大小,请参阅[自定义PDF纸张大小](https://ironpdf.com/java/examples/custom-pdf-paper-size/)。
[[n:(始终在PaperOrientation之前设置PaperSize。 在某些版本中,PaperSize应用后可能会覆盖先设置的方向。 推荐顺序是:尺寸,然后是方向,最后是边距。)]]
## 如何为Java中的PDF添加密码保护?
`SecurityOptions`控制读取和所有者密码以及权限标志。 在保存之前,将`SecurityManager`:
```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"));
```
用于更严格的控制,设置所有者密码并限制特定操作:
```java
//: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时提示读者输入密码:
<div class="content-img-align-center">
<div class="center-image-wrapper">
<a rel="nofollow" href="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-1.webp" target="_blank"><img src="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-1.webp" alt="打开设置了用户密码的 IronPDF 生成 Java PDF 时显示的密码提示对话框" class="img-responsive add-shadow" /></a>
<p class="content__image-caption">当文档用用户密码保护时,PDF阅读器会显示密码提示。</p>
</div>
</div>
输入正确密码后,PDF打开并显示完整内容:
<div class="content-img-align-center">
<div class="center-image-wrapper">
<a rel="nofollow" href="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-2.webp" target="_blank"><img src="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-2.webp" alt="输入正确密码后在 PDF 查看器中打开的 IronPDF Java PDF 文档,显示完整文档内容" class="img-responsive add-shadow" /></a>
<p class="content__image-caption">提供正确密码后,文档正常渲染。</p>
</div>
</div>
请参阅[安全和元数据设置](https://ironpdf.com/java/examples/security-and-metadata/)以获取权限标识的完整列表。
## 如何在Spring Boot应用程序中生成PDF?
IronPDF直接与Spring Boot集成。 从任何控制器方法返回PDF作为字节数组HTTP响应; 此模式适用于按需生成报告、发票下载和数据导出。
```java
//: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()`,而不是每次请求。
[[t:(使用@PostConstruct方法或ApplicationRunner在应用程序启动时一次性设置许可证密钥。 每个请求调用License.setLicenseKey()会增加不必要的开销。)]]
## Java PDF创建的下一步是什么?
本指南演示了使用IronPDF在Java中进行PDF生成的四种方法:HTML字符串渲染、本地文件转换、URL捕获及Spring Boot HTTP响应流。 所有方法共享相同的`SecurityOptions`用于访问保护。
IronPDF for Java还支持[添加和盖章水印](https://ironpdf.com/java/how-to/custom-watermark/)、[合并多个PDF文件](https://ironpdf.com/java/how-to/java-merge-pdf-tutorial/)、[将PDF拆分为单独的页面](https://ironpdf.com/java/examples/split-pdfs/)、[添加数字签名](https://ironpdf.com/java/examples/pdf-signatures/)、[将JavaScript图表渲染为PDF](https://ironpdf.com/java/examples/js-charts-to-pdf/)以及[程序化打印PDF](https://ironpdf.com/java/how-to/java-print-pdf-tutorial/)。
[开始免费试用](#trial-license)以生成无水印PDF,或[查看许可选项](#licensing)以选择适合您项目的方案。 准备更深入探索吗? 查看完整的[IronPDF for Java教程页面](https://ironpdf.com/java/tutorials/html-to-pdf/)。
Ask ChatGPT about this page
Ask Gemini about this page
Ask Perplexity about this page
在Java中创建PDF文件是企业应用程序的常见要求:按需生成发票和报告,生成证书、收据和审计日志。 IronPDF for Java使用完整的Chromium渲染引擎将HTML转换为PDF,这意味着任何HTML5、CSS3和JavaScript内容都能忠实渲染,没有格式丢失。
本指南涵盖了三种PDF创建方法:从HTML字符串、从本地HTML文件和从实时URL。 它还涵盖了页面格式、密码保护和Spring Boot集成。
将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>
XML
导入库并创建PDF:
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" ));
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
如何在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 上的服务器部署。
IronPDF在后台使用Chromium进行渲染。 正如Chrome中看起来正确的HTML,在PDF中也产生相同的输出,而无需浏览器到PDF格式调整的惊讶。
在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>
XML
保存后,运行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'
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/gradle-dependency.gradle
implementation 'com.ironsoftware:ironpdf:2024.9.1'
Text
运行gradle build以获取库。 检查Maven Central 以获取最新发布的版本。
需要哪些导入和配置?
在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 ;
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;
Java
在生成任何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");
Java
**注意:**如果没有有效的许可证密钥,生成的PDF会有试用水印。 购买许可证 或者开始免费试用 以去除它。 参见在Java中使用许可证密钥 以获取其他配置选项。
如何在Java中从HTML字符串创建PDF?
将任何HTML字符串直接传递给PdfDocument.renderHtmlAsPdf()。 IronPDF返回一个PdfDocument实例,表示在内存中完成的文档。 调用saveAs()将其写入磁盘。
// 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" ));
// 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"));
Java
renderHtmlAsPdf()支持完整的HTML5和CSS3规范,包括网页字体、Flexbox、Grid布局和JavaScript执行。 以下示例使用具有自定义样式的多行HTML模板:
// 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" ));
// 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文本块(自Java 13起可用)来实现更清洁的多行HTML。 对于较旧的Java版本,手动连接HTML字符串或使用renderHtmlFileAsPdf()从文件中加载。 若要更广泛地了解HTML到PDF的转换包括JavaScript渲染,请参见HTML到PDF教程Java版 。
对于传递的简短HTML字符串,IronPDF会自动将内容包装在一个最小的HTML文档中。 为了完全控制head标签,meta字符集,及CSS重置,请传递完整的!DOCTYPE html文档。
如何在Java中从本地HTML文件创建PDF?
使用PdfDocument.renderHtmlFileAsPdf()转换存储在本地文件系统上的HTML文件。 传递路径作为字符串; 相对路径相对于当前工作目录解析:
// 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" ));
// 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"));
Java
IronPDF将所有引用的资源(外部CSS文件、本地图像和JavaScript库)相对于HTML文件所在的目录进行解析。 这意味着您可以构建一个完整的HTML模板与链接样式表,并通过IronPDF运行它而无需修改任何资源路径。
该方法接受java.nio.file.Path对象。 用于生产使用,偏好使用绝对路径以避免工作目录歧义。 参见HTML文件到PDF示例 以获取完整的工作演示。
如何在Java中从网页URL创建PDF?
PdfDocument.renderUrlAsPdf()获取实时URL,使用Chromium渲染,并返回PDF。 这对于捕获仪表盘快照,从托管的收据页面生成PDF收据,或归档网络内容有用:
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument .renderUrlAsPdf( "https://ironpdf.com" );
webPdf.saveAs( Paths .get( "ironpdf-homepage.pdf" ));
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
webPdf.saveAs(Paths.get("ironpdf-homepage.pdf"));
Java
对于需要HTTP身份验证的页面,通过ChromePdfRenderOptions传递凭据:
// 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" ));
// 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"));
Java
参见URL到PDF代码示例 以了解详细信息。 对于使用cookies或基于表单身份验证的更复杂登录流程,请参阅网站登录处理 。
如何控制页面大小、方向和边距?
使用ChromePdfRenderOptions自定义输出PDF的物理布局。 将配置选项作为第二参数传递给任何渲染方法。 最常见的设置是页面方向、纸张尺寸和边距:
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 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"));
Java
ChromePdfRenderOptions暴露了超过30项设置,超出了上面显示的,包括DPI、JavaScript执行超时、缩放因子和CSS媒体类型。 请参阅PDF生成设置 以获取完整列表。对于PaperSize枚举中没有的自定义纸张大小,请参阅自定义PDF纸张大小 。
始终在PaperOrientation之前设置PaperSize。 在某些版本中,PaperSize应用后可能会覆盖先设置的方向。 推荐顺序是:尺寸,然后是方向,最后是边距。
如何为Java中的PDF添加密码保护?
SecurityOptions控制读取和所有者密码以及权限标志。 在保存之前,将SecurityManager:
// 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" ));
// 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"));
Java
用于更严格的控制,设置所有者密码并限制特定操作:
//: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);
Java
打开PDF时提示读者输入密码:
当文档用用户密码保护时,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);
}
}
Java
getBinaryData()方法以字节数组形式返回PDF,Spring Boot直接将其流式传输给客户端。 不会向磁盘写入任何临时文件。 对于高吞吐量部署,在License.setLicenseKey(),而不是每次请求。
使用@PostConstruct方法或ApplicationRunner在应用程序启动时一次性设置许可证密钥。 每个请求调用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教程页面 。
常见问题解答 将您的HTML字符串传递给PdfDocument.renderHtmlAsPdf()。该方法在内存中返回PdfDocument对象。调用pdf.saveAs(Paths.get("output.pdf"))将其写入磁盘。IronPDF支持完整的HTML5、CSS3和JavaScript。
IronPDF for Java需要JDK 8或更高版本。JDK 11 LTS是生产部署的推荐最低要求。
在pom.xml的<dependencies>部分内添加groupId com.ironsoftware和artifactId ironpdf的依赖块,然后运行mvn install。
使用HTML文件路径调用PdfDocument.renderHtmlFileAsPdf()。IronPDF自动解析所有相对于文件目录的链接CSS、图像和JavaScript。
是的。使用目标URL调用PdfDocument.renderUrlAsPdf()。IronPDF使用Chromium获取页面并返回PdfDocument。对于HTTP认证后的页面,通过ChromePdfRenderOptions传递凭据。
创建SecurityOptions对象,使用您的密码调用setUserPassword(),然后在调用saveAs()之前将选项传递给urlPdf.getSecurity().setSecurityOptions()。
将您的PDF生成逻辑注入到@RestController方法中。调用PdfDocument.renderHtmlAsPdf(),然后使用pdf.getBinaryData()获取字节数组,并用MediaType.APPLICATION_PDF将其作为ResponseEntity<byte[]>返回。
创建ChromePdfRenderOptions对象,调用setPaperSize()和setPaperOrientation(),然后作为第二个参数传递给任何渲染方法。在设置方向之前设置纸张大小以避免顺序冲突。
是的。IronPDF for Java在Windows、Linux和macOS上运行。它还支持在AWS、Azure和Google Cloud上的云部署,无需外部PDF查看器或渲染引擎。
是的。没有有效的许可证密钥,IronPDF会在所有生成的文档上添加试用水印。在应用程序启动时调用License.setLicenseKey()并使用有效密钥以去除它。
技术作家
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。
...
阅读更多