如何在Java中建立PDF文件

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

使用IronPDF庫在 Java 中建立 PDF 文件非常簡單,該庫使用 renderHtmlAsPdf() 方法將 HTML 字串轉換為 PDF,使用 renderHtmlFileAsPdf() 方法將 HTML 文件轉換為 PDF,使用 renderUrlAsPdf() 方法將網頁轉換為 PDF。

快速入門:用 Java 創建你的第一個 PDF

  1. 將IronPDF依賴項加入 pom.xml 檔案中:

    <dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>1.0.0</version>
    </dependency>
    <dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>1.0.0</version>
    </dependency>
    XML
  2. 導入IronPDF類別:

    import com.ironsoftware.ironpdf.*;
    import com.ironsoftware.ironpdf.*;
    JAVA
  3. 從 HTML 建立 PDF: ```java :title=快速入門 PdfDocument pdf = PdfDocument.renderHtmlAsPdf(""); pdf.saveAs(Paths.get("output.pdf"));

使用 Java 以程式設計方式建立 PDF 可以實現按需自動產生發票、報告和其他業務文件。

本指南介紹如何使用IronPDF在 Java 應用程式中以程式設計方式建立 PDF 檔案。

什麼是IronPDF Java PDF 函式庫?

IronPDF是一個 Java 程式庫,用於從 HTML 建立 PDF 文件。 它提供創建和自訂 PDF 的功能,包括:

  1. 新增文字、圖像和其他內容類型
  2. 選擇字體、顏色,以及控制佈局和格式

IronPDF基於.NET Framework構建,因此既可用於.NET應用程序,也可用於 Java 應用程式。 該庫支援高級功能,例如自訂浮水印PDF 壓縮表單建立

IronPDF也處理與 PDF 相關的任務,包括文件格式轉換、文字和資料提取以及密碼加密。 您可以根據需要合併多個PDF文件將其拆分

如何在Java應用程式中建立PDF文件?

我需要哪些先決條件?

若要在 Maven 專案中使用IronPDF ,請確保已安裝下列必備組件:

  1. Java 開發工具包 (JDK):編譯和運行 Java 應用程式所必需。 Download from Oracle website.
  2. Maven:用於下載專案庫。 從Apache Maven 網站下載。
  3. IronPDF庫:在 pom.xml 檔案中將其作為依賴項新增至 Maven 專案:
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>1.0.0</version>
</dependency>
XML

對於 Gradle 項目,請使用以下指令新增IronPDF :

implementation 'com.ironsoftware:ironpdf:1.0.0'

在編寫程式碼之前我應該採取哪些步驟?

首先,將以下導入語句新增到您的 Java 原始檔中:

import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.*;
JAVA

若要實現特定功能,請匯入其他類別:

import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
JAVA

接下來,使用有效的許可證金鑰在 main 方法中配置IronPDF :

License.setLicenseKey("Your license key");
License.setLicenseKey("Your license key");
JAVA

注意許可證密鑰可移除浮水印。 購買許可證金鑰取得免費試用版。 如果沒有許可證,產生的PDF文件會帶有浮水印。 請參閱"使用許可證密鑰"以了解詳情。

如何在Java中根據HTML字串建立PDF檔案?

使用 renderHtmlAsPdf() 將 HTML 字串轉換為 PDF。 此方法支援 HTML5、CSS3 和JavaScript渲染。

將 HTML 字串傳遞給 renderHtmlAsPdf。 IronPDF將其轉換為 PdfDocument 實例:

// HTML content to be converted to PDF
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";

// Convert HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);

// Save the PDF document to a file
pdf.saveAs(Paths.get("html.pdf"));
// HTML content to be converted to PDF
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";

// Convert HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);

// Save the PDF document to a file
pdf.saveAs(Paths.get("html.pdf"));
JAVA

這將建立包含 HTML 內容的"html.pdf"檔案。

包含帶有 CSS 樣式的複雜 HTML:

// HTML with CSS styling
String styledHtml = """
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; }
            h1 { color: #2563eb; }
            .content { margin: 20px; padding: 15px; background-color: #f3f4f6; }
        </style>
    </head>
    <body>
        <div class="content">
            <h1>Styled PDF Document</h1>
            <p>This PDF was created from HTML with custom CSS styling.</p>
        </div>
    </body>
    </html>
    """;

PdfDocument styledPdf = PdfDocument.renderHtmlAsPdf(styledHtml);
styledPdf.saveAs(Paths.get("styled.pdf"));
// HTML with CSS styling
String styledHtml = """
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; }
            h1 { color: #2563eb; }
            .content { margin: 20px; padding: 15px; background-color: #f3f4f6; }
        </style>
    </head>
    <body>
        <div class="content">
            <h1>Styled PDF Document</h1>
            <p>This PDF was created from HTML with custom CSS styling.</p>
        </div>
    </body>
    </html>
    """;

PdfDocument styledPdf = PdfDocument.renderHtmlAsPdf(styledHtml);
styledPdf.saveAs(Paths.get("styled.pdf"));
JAVA

如需進行更進階的轉換,請參閱HTML 轉 PDF 教學課程

如何在Java中從HTML頁面建立PDF檔案?

從本機 HTML 檔案建立 PDF:

// Convert HTML file to PDF
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");

// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
// Convert HTML file to PDF
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");

// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
JAVA

renderHtmlFileAsPdf 方法接受檔案路徑作為字串或 Path 物件。

IronPDF使用 CSS 和JavaScript渲染 HTML 元素,方式與瀏覽器完全相同。 這包括外部 CSS 檔案、圖片和JavaScript庫。 詳情請參閱"HTML檔案轉PDF"文件

使用 saveAs 將 PDF 儲存到指定位置。

如何在Java中根據URL建立PDF文件?

使用 renderUrlAsPdf() 從網頁建立 PDF:

// Convert a URL to PDF
PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Convert a URL to PDF
PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
JAVA

對於已認證的網站,請提供憑證:

// Create render options with login credentials
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setAuthUsername("username");
renderOptions.setAuthPassword("password");

// Convert secured URL to PDF
PdfDocument securedPdf = PdfDocument.renderUrlAsPdf("https://secure-site.com", renderOptions);
securedPdf.saveAs(Paths.get("secured.pdf"));
// Create render options with login credentials
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setAuthUsername("username");
renderOptions.setAuthPassword("password");

// Convert secured URL to PDF
PdfDocument securedPdf = PdfDocument.renderUrlAsPdf("https://secure-site.com", renderOptions);
securedPdf.saveAs(Paths.get("secured.pdf"));
JAVA

詳情請參閱PDF程式碼範例的URL連結。 有關複雜的身份驗證,請參閱網站和系統登入

如何格式化PDF文件?

使用 ChromePdfRenderOptions 指定 PDF 格式。 配置頁面方向、大小和邊距。 將選項作為第二個參數傳遞給渲染方法:

// Create render options with custom settings
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();

// Set page orientation to landscape
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);

// Set custom paper size (Letter size)
renderOptions.setPaperSize(PaperSize.LETTER);

// Set custom margins (in millimeters)
renderOptions.setMarginTop(10);
renderOptions.setMarginRight(10);
renderOptions.setMarginBottom(10);
renderOptions.setMarginLeft(10);

// Enable background images and colors
renderOptions.setPrintHtmlBackgrounds(true);

// Apply options to PDF generation
PdfDocument formattedPdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted PDF</h1>", renderOptions);
formattedPdf.saveAs(Paths.get("formatted.pdf"));
// Create render options with custom settings
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();

// Set page orientation to landscape
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);

// Set custom paper size (Letter size)
renderOptions.setPaperSize(PaperSize.LETTER);

// Set custom margins (in millimeters)
renderOptions.setMarginTop(10);
renderOptions.setMarginRight(10);
renderOptions.setMarginBottom(10);
renderOptions.setMarginLeft(10);

// Enable background images and colors
renderOptions.setPrintHtmlBackgrounds(true);

// Apply options to PDF generation
PdfDocument formattedPdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted PDF</h1>", renderOptions);
formattedPdf.saveAs(Paths.get("formatted.pdf"));
JAVA

請參閱PDF 產生設定以了解更多選項。 探索自訂紙張尺寸自訂頁邊距

如何為PDF檔案設定密碼保護?

使用 SecurityOptions 對 PDF 檔案進行密碼保護:

// Create security options and set user password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
// Create security options and set user password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
JAVA

設定進階安全選項:

// Advanced security settings
SecurityOptions advancedSecurity = new SecurityOptions();
advancedSecurity.setUserPassword("user123");
advancedSecurity.setOwnerPassword("owner456");

// Restrict permissions
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
// Advanced security settings
SecurityOptions advancedSecurity = new SecurityOptions();
advancedSecurity.setUserPassword("user123");
advancedSecurity.setOwnerPassword("owner456");

// Restrict permissions
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
JAVA

透過 PDF 的 SecurityManager 應用安全措施:

// Apply security options to the PDF
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);

// Save the password-protected PDF document
urlToPdf.saveAs("protected.pdf");
// Apply security options to the PDF
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);

// Save the password-protected PDF document
urlToPdf.saveAs("protected.pdf");
JAVA

開啟PDF檔案時會彈出​​密碼提示:

Password entry dialog for protected PDF with input field and Open file/Cancel buttons

輸入正確的密碼後,PDF 檔案正常開啟。

IronPDF .NET homepage showing HTML to PDF code examples and download options

有關其他設置,請參閱"安全性和元資料範例"

完整的原始碼是什麼?

本教學的完整原始碼:

// Import statement for IronPDF Java  
import com.ironsoftware.ironpdf.*;
import java.io.IOException;  
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) throws IOException {
        // Apply your license key
        License.setLicenseKey("Your License Key");

        // Convert HTML string to a PDF and save it
        String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
        pdf.saveAs(Paths.get("html.pdf"));

        // Convert HTML file to a PDF and save it
        PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
        myPdf.saveAs(Paths.get("html_file_saved.pdf"));

        // Convert URL to a PDF and save it
        PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
        urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));

        // Password-protect the PDF file
        SecurityOptions securityOptions = new SecurityOptions();
        securityOptions.setUserPassword("shareable");
        SecurityManager securityManager = urlToPdf.getSecurity();
        securityManager.setSecurityOptions(securityOptions);
        urlToPdf.saveAs(Paths.get("protected.pdf"));
    }
}
// Import statement for IronPDF Java  
import com.ironsoftware.ironpdf.*;
import java.io.IOException;  
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) throws IOException {
        // Apply your license key
        License.setLicenseKey("Your License Key");

        // Convert HTML string to a PDF and save it
        String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
        pdf.saveAs(Paths.get("html.pdf"));

        // Convert HTML file to a PDF and save it
        PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
        myPdf.saveAs(Paths.get("html_file_saved.pdf"));

        // Convert URL to a PDF and save it
        PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
        urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));

        // Password-protect the PDF file
        SecurityOptions securityOptions = new SecurityOptions();
        securityOptions.setUserPassword("shareable");
        SecurityManager securityManager = urlToPdf.getSecurity();
        securityManager.setSecurityOptions(securityOptions);
        urlToPdf.saveAs(Paths.get("protected.pdf"));
    }
}
JAVA

IronPDF可以無損渲染影像和文字。 按鈕仍可點擊,文字方塊仍可編輯。 該庫支援添加簽名渲染圖表列印 PDF

有哪些關鍵要點?

本指南示範如何使用IronPDF在 Java 中建立 PDF。 IronPDF提供了一個簡單的 API,可以從 HTML 檔案、XML 文件或其他來源產生 PDF。

快速產生報告、發票或任何類型的文件。 部署在AWSAzureGoogle Cloud上。

IronPDF需要商業許可證,許可證號為 $799。 取得免費試用版,用於生產環境測試。

下載IronPDF Java 庫

常見問題解答

在 Java 中建立 PDF 檔案的最簡單方法是什麼?

在 Java 中創建 PDF 的最簡單方法是使用 IronPDF for Java 的 renderHtmlAsPdf() 方法。只需傳入一個 HTML 字串給此方法,並儲存結果即可:PdfDocument pdf = PdfDocument.renderHtmlAsPdf("Hello World!"); pdf.saveAs(Paths.get("output.pdf"));

如何將 IronPDF 加入我的 Maven 專案?

將 IronPDF 加入您的 Maven 專案,方法是在您的 pom.xml 檔案中加入此依賴:com.ironsoftwareironpdf1.0.0

我可以將現有的 HTML 檔案轉換成 PDF 格式嗎?

是的,IronPDF 提供了 renderHtmlFileAsPdf() 方法,專門用於將 HTML 檔案轉換為 PDF。此方法會從您的檔案系統讀取 HTML 檔案,並將其轉換為 PDF 文件。

如何用 Java 從網頁生成 PDF?

IronPDF 提供 renderUrlAsPdf() 方法,可直接將網頁轉換為 PDF。只需提供您想要轉換的網頁 URL,IronPDF 就會將該網頁渲染為 PDF 文件。

哪些類型的商業文件可以透過程式建立?

IronPDF 可自動生成各種商業文件,包括發票、報告、表單和其他按需文件。該函式庫支援自訂水印、PDF 壓縮和表單建立等進階功能。

是否可以建立密碼保護的 PDF?

是的,IronPDF 支持對 PDF 文件進行密碼加密。您可以將受密碼保護的 PDF 匯出至所需的目錄,確保敏感商業資訊的文件安全。

使用 IronPDF for Java 的系統要求是什麼?

要在 Java 中使用 IronPDF,您需要使用 Java Development Kit (JDK) 來編譯和執行應用程式,使用 Maven 或 Gradle 來進行相依性管理,並將 IronPDF 函式庫作為相依性添加到您的專案中。

我可以操作現有的 PDF,而不只是建立新的 PDF 嗎?

是的,IronPDF 可處理創建以外的各種 PDF 操作任務。您可以合併多個 PDF、分割 PDF、擷取文字和資料,並使用該函式庫的全面功能執行檔案格式轉換。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。

準備好開始了嗎?
版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

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