如何使用 IronPDF 在 Java 中建立 PDF

如何在 Java 中建立 PDF 檔案

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

在 Java 中建立 PDF 檔案是企業應用程式的常見需求:例如依需求產生發票與報告、製作證書、收據及稽核日誌。 IronPDF for Java 採用完整的 Chromium 渲染引擎將 HTML 轉換為 PDF,這意味著任何 HTML5、CSS3 和 JavaScript 內容都能忠實呈現,且不會造成格式遺失。

本指南涵蓋三種 PDF 建立方法:從 HTML 字串、從本機 HTML 檔案,以及從即時網址。 此外,還涵蓋頁面格式設定、密碼保護以及 Spring Boot 整合功能。

快速入門:在 Java 中將 HTML 轉為 PDF

  1. 將 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
  1. 導入函式庫並建立 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"));
//: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

什麼是 IronPDF for Java,以及為何要使用它?

IronPDF for Java 是一款基於 Chromium 渲染引擎建構的 PDF 生成與處理函式庫。由於其渲染 HTML 的方式與 Chrome 完全一致,因此無需手動編寫版面配置程式碼,即可處理複雜版面、自訂字型、CSS 動畫、JavaScript 生成的內容以及嵌入式圖片。

此函式庫僅需單一依賴項,即可涵蓋 PDF 的完整生命週期。 開發人員可透過一致的 API,從頭建立文件、轉換現有 HTML 內容、合併或分割檔案、添加浮水印、使用密碼加密、擷取文字與圖片,以及產生可填寫的表單。 對於大量涉及 HTML 的工作流程,IronPDF 避免了像 Apache PDFBox 這種低階 PDF 函式庫所需要的手動頁面佈局計算。

與 iText 不同,後者針對多數商業用途要求採用 AGPL 開源授權;IronPDF 則提供商業友善的授權方案,無需進行複雜的授權合規性審查。 IronPDF for Java 以 Maven 套件形式發行,並可在 Windows、Linux 及 macOS 系統上運行。 它可與 Spring Boot、Jakarta EE 以及獨立的 Java 應用程式整合。 該函式庫亦支援在 AWSAzureGoogle Cloud 上的伺服器部署。

請注意IronPDF 底層採用 Chromium 進行渲染。 (在 Chrome 中顯示正確的相同 HTML 內容,在您的 PDF 中也會產生相同的輸出結果,不會出現瀏覽器與 PDF 格式不一致的意外狀況。)}]

在 Java 中使用 IronPDF 的先決條件是什麼?

需要哪個 Java 版本和建置工具?

IronPDF for Java 需要 JDK 8 或更高版本。 建議生產環境的最低版本為 JDK 11 (LTS)。 Download the JDK from the Oracle download page or use an OpenJDK distribution such as Eclipse Temurin.

同時支援 Maven (3.6+) 和 Gradle (7.0+)。 對於 Enterprise Java 專案而言,Maven 是更常見的選擇。

如何將 IronPDF 加入 Maven 專案?

開啟專案的 pom.xml 檔案,並在 <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 專案?

請在您的 build.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 以取得該函式庫。 Check Maven Central for the latest published version.

需要哪些匯入項目與設定?

請在您的 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.IO/Exception;
import java.nio.file.Paths;
//: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.IO/Exception;
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() 將其寫入磁碟。

//: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"));
//: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"));
JAVA

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"));
//: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 文字區塊(自 Java 13 起提供),以呈現更簡潔的多行 HTML。 對於舊版 Java,請手動串接 HTML 字串,或使用 renderHtmlFileAsPdf() 從檔案載入。 若需更全面了解包含 JavaScript 渲染在內的 HTML 轉 PDF 轉換,請參閱 Java 版 HTML 轉 PDF 教學指南

提示傳入短 HTML 字串時,IronPDF 會自動將內容封裝在一個最簡化的 HTML 文件中。 若需完全控制標題標籤、meta charset 及 CSS 重置,請提供完整的<!DOCTYPE html> 文件。

如何在 Java 中從本機 HTML 檔案建立 PDF?

using 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"));
//: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"));
JAVA

IronPDF 會將所有被引用的資源(外部 CSS 檔案、本地圖片及 JavaScript 函式庫)相對於 HTML 檔案的目錄進行解析。 這意味著您可以建立一個包含連結樣式表的完整 HTML 範本,並透過 IronPDF 執行,無需修改任何資源路徑。

此方法同時接受 String 路徑與 java.nio.file.Path 物件。 若用於正式環境,請優先使用絕對路徑以避免工作目錄的歧義。 請參閱 HTML 轉 PDF 範例,以查看完整的運作示範。

如何在 Java 中透過網頁網址建立 PDF 檔案?

PdfDocument.renderUrlAsPdf() 會擷取一個即時網址,透過 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"));
//: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"));
JAVA

對於需要 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"));
//: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"));
JAVA

詳情請參閱 PDF 程式碼範例的網址。 若涉及使用 Cookie 或表單驗證的較複雜登入流程,請參閱網站登入處理

如何控制頁面大小、方向和邊距?

請使用 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"));
//: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"));
JAVA

ChromePdfRenderOptions 提供了超過 30 項設定選項,除上述列舉者外,還包含 DPI、JavaScript 執行超時、Zoom 係數及 CSS 媒體類型等。 請參閱 PDF 產生設定以取得完整清單。若需 PaperSize 枚舉中未列出的自訂紙張尺寸,請參閱自訂 PDF 紙張尺寸

重要事項請務必在設定 PaperOrientation 之前先設定 PaperSize。 在某些建置中,若套用 PaperSize,先前設定的頁面方向可能會被覆寫。 建議的排序順序為:尺寸、方向、邊距。)}]

如何在 Java 中為 PDF 檔案新增密碼保護?

SecurityOptions 控制讀取密碼、擁有者密碼以及權限標誌。 儲存前請將 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-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"));
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 檔案時,系統會提示讀者輸入密碼:

Password prompt dialog shown when opening an IronPDF-generated Java PDF with a user password set

當文件受使用者密碼保護時,PDF 閱讀器會顯示密碼提示。

輸入正確密碼後,PDF 檔案將開啟並顯示完整內容:

IronPDF Java PDF document open in a PDF viewer after the correct password is entered, displaying full document content

輸入正確密碼後,文件即可正常顯示。

請參閱安全性與元資料設定,以查看權限標記的完整清單。

如何在 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.IO/Exception;

@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.IO/Exception;

@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 會將其直接串流傳送至客戶端。 不會將任何暫存檔寫入磁碟。 針對高吞吐量部署,請在 @PostConstruct 方法或應用程式啟動監聽器中實例化 License.setLicenseKey(),而非針對每個請求進行實例化。

提示請於應用程式啟動時,透過 @PostConstruct 方法或 ApplicationRunner 設定您的授權金鑰。 在每次請求中呼叫 License.setLicenseKey() 會增加不必要的開銷。

Java PDF 製作的下一步是什麼?

本指南展示了四種使用 IronPDF 在 Java 中生成 PDF 的方法:HTML 字串渲染、本地檔案轉換、URL 擷取,以及 Spring Boot HTTP 回應串流。 所有方法均採用相同的 PdfDocument API、ChromePdfRenderOptions 格式控制,以及 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 區段中加入 groupIdcom.ironsoftwareartifactIdIronPDF 的依賴項區塊,然後執行 mvn install

如何在 Java 中將本機 HTML 檔案轉為 PDF?

請傳入您的 HTML 檔案路徑,並呼叫 PdfDocument.renderHtmlFileAsPdf()。IronPDF 會自動解析所有連結的 CSS、圖片及 JavaScript,並以該檔案所在目錄為基準進行相對路徑轉換。

我可以在 Java 中從網址建立 PDF 檔案嗎?

是的。請傳入目標網址並呼叫 PdfDocument.renderUrlAsPdf()。IronPDF 會透過 Chromium 擷取頁面,並回傳一個 PdfDocument 物件。若頁面位於 HTTP 驗證後方,請透過 ChromePdfRenderOptions 傳遞驗證憑證。

如何在 Java 中使用 IronPDF for Java 為 PDF 設定密碼保護?

建立一個 SecurityOptions 物件,傳入您的密碼呼叫 setUserPassword(),接著在呼叫 saveAs() 之前,將這些選項傳遞給 urlPdf.getSecurity().setSecurityOptions()

如何在 Spring Boot 應用程式中使用 IronPDF?

將您的 PDF 生成邏輯注入 @RestController 方法中。呼叫 PdfDocument.renderHtmlAsPdf(),接著使用 pdf.getBinaryData() 取得位元組陣列,並將其作為 ResponseEntity 並設定 MediaType.APPLICATION_PDF 傳回。

如何在 IronPDF for Java 中設定頁面大小與方向?

建立一個 ChromePdfRenderOptions 物件,呼叫 setPaperSize()setPaperOrientation() 方法,然後將其作為第二個參數傳遞給任何渲染方法。請先設定紙張尺寸,再設定紙張方向,以避免順序衝突。

IronPDF 是否支援在 Linux 和 macOS 上以 Java 執行?

是的。IronPDF for Java 可在 Windows、Linux 和 macOS 上運行。它亦支援在 AWS、Azure 和 Google Cloud 上的雲端部署,且無需外部 PDF 檢視器或渲染引擎。

若未輸入授權金鑰,PDF 檔案會顯示浮水印嗎?

是的。若未提供有效的授權金鑰,IronPDF 會於所有產生的文件中加入試用版浮水印。請在應用程式啟動時,使用有效的金鑰呼叫 License.setLicenseKey() 方法以移除該浮水印。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
版本: 2026.5 just released
Still Scrolling Icon

還在捲動嗎?

想要快速證明?
執行範例 觀看您的 HTML 變成 PDF。