如何在Java中建立PDF文件

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

使用 IronPDF 函式庫在 Java 中建立 PDF 檔案非常簡單,該函式庫使用 renderHtmlAsPdf() 等方法將 HTML 轉換為 PDF,這些方法適用於 HTML 字串、renderHtmlFileAsPdf() 適用於 HTML 檔案,以及 renderUrlAsPdf() 適用於網頁。

Quickstart: Create Your First PDF in Java

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=Quickstart PdfDocument pdf = PdfDocument.renderHtmlAsPdf(""); pdf.saveAs(Paths.get("output.pdf"));


<div class="hsg-featured-snippet">
    <h2>如何在Java中建立PDF文件</h2>
    <ol>
        <li><a class="js-modal-open" data-modal-id="download-modal" href="#download-modal">安裝 IronPDF Java 庫</a></li>
        <li>使用<code>renderHtmlAsPdf</code>方法從 HTML 字串建立 PDF 文件</li>
        <li>使用<code>renderHtmlFileAsPdf</code>方法從 HTML 檔案建立 PDF 文件</li>
        <li>使用<code>renderUrlAsPdf</code>方法從 URL 建立 PDF</li>
        <li>將密碼保護的PDF文件導出到所需目錄</li>
    </ol>
</div>

*Creating PDFs programmatically in Java enables automated document generation for invoices, reports, and other business documents on demand.*在 Java 中以程式化的方式創建 PDF,可根據需求自動生成發票、報告和其他商業文件。

<em>本指南涵蓋在 Java 應用程式中使用 IronPDF 程式化地建立 PDF 檔案。

<h2>什麼是 IronPDF Java PDF Library?

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

1.新增文字、圖片及其他內容類型
2.選擇字型、顏色以及控制版面與格式

IronPDF for Java 建立在 .NET Framework 之上,可在 .NET 和 Java 應用程式中使用。 這個函式庫支援進階功能,例如 [自訂水印](https://ironpdf.com/java/how-to/custom-watermark/)、[PDF 壓縮](https://ironpdf.com/java/how-to/compress-pdf-java-tutorial/),以及 [表單建立](https://ironpdf.com/java/how-to/create-forms/)。

IronPDF 還能處理 PDF 相關工作,包括檔案格式轉換、文字與資料擷取,以及密碼加密。 您可以[合併多個 PDF 文件](https://ironpdf.com/java/how-to/java-merge-pdf-tutorial/),或[根據需要分割 PDF 文件](https://ironpdf.com/java/examples/split-pdfs/)。

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

<!-- TODO: 在此添加圖片 -->
<! -- ![演示在 IronPDF for Java 的 java 應用程式中建立 pdf 文件的步驟的螢幕截圖](/static-assets/images/TODO/steps-to-create-pdf-document-in-a-java-application-step_screenshot.webp) --> -->
<!--說明:顯示逐步過程的截圖 -->

<h3>我需要哪些先決條件?

若要在 Maven 專案中使用 IronPDF,請確認已安裝這些先決條件:

1.**Java Development Kit (JDK):** 編譯和執行 Java 應用程式所需的工具。 Download from <a href="https://www.oracle.com/java/technologies/javase-downloads.html" target="_blank" rel="nofollow noopener noreferrer">Oracle website</a>.
2.**Maven:** 下載專案程式庫所需。 從 [Apache Maven 網站](https://maven.apache.org/download.cgi)下載。
3.**IronPdf函式庫:**在pom.xml中加入Maven專案作為依賴:

```xml
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>1.0.0</version>
</dependency>

對於 Gradle 專案,請使用下列方式新增 IronPdf:

implementation 'com.ironsoftware:ironpdf:1.0.0'

撰寫程式碼前應該採取哪些步驟? 首先,將此匯入語句加入您的 Java 原始碼檔案: ```java import com.ironsoftware.ironpdf.*; ``` 針對特定功能,請匯入其他類別: ```java import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions; import com.ironsoftware.ironpdf.security.SecurityOptions; import com.ironsoftware.ironpdf.security.SecurityManager; ``` 接下來,在 `main` 方法中使用有效的授權金鑰設定 IronPDF: ```java License.setLicenseKey("Your license key"); ``` **注意**: *授權金鑰會移除水印。 [購買授權金鑰](/java/licensing/)或[取得免費試用](trial-license)。 在沒有授權的情況下,PDF 會產生水印。 詳情請參閱 [ 使用授權金鑰](https://ironpdf.com/java/get-started/license-keys/)。* IronPDF for Java

如何在 Java 中從 HTML 字串建立 PDF 檔案? 使用 `renderHtmlAsPdf()` 將 HTML 字串轉換為 PDF。 本方法支援 HTML5、CSS3 及 JavaScript 演算法。 傳送 HTML 字串給 `renderHtmlAsPdf` 。 IronPDF 將其轉換為 `PdfDocument` 實例: ```java // HTML content to be converted to PDF String htmlString = "

This is an example HTML string.

"; // Convert HTML string to PDF PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString); // Save the PDF document to a file pdf.saveAs(Paths.get("html.pdf")); ``` 這會建立包含 HTML 內容的 "html.pdf"。 包含複雜的 HTML 與 CSS 定型: ```java // HTML with CSS styling String styledHtml = """

This PDF was created from HTML with custom CSS styling.

"""; PdfDocument styledPdf = PdfDocument.renderHtmlAsPdf(styledHtml); styledPdf.saveAs(Paths.get("styled.pdf")); ``` 如需進階轉換,請參閱 [HTML to PDF 教學](https://ironpdf.com/java/tutorials/html-to-pdf/)。

如何在 Java 中從 HTML 頁面建立 PDF 檔案? 從本機 HTML 檔案建立 PDF: ```java // 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")); ``` `renderHtmlFileAsPdf` 方法接受檔案路徑為 String 或 Path 物件。 IronPDF 使用 CSS 和 JavaScript 完全按照瀏覽器的方式渲染 HTML 元素。 這包括外部 CSS 檔案、圖片和 JavaScript 函式庫。 詳情請參閱 [HTML 檔案轉 PDF](https://ironpdf.com/java/examples/file-to-pdf/) 。 使用 `saveAs` 將 PDF 儲存到特定位置。

如何在 Java 中從 URL 建立 PDF 檔案? 使用 `renderUrlAsPdf()` 從網頁建立 PDF: ```java // 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")); ``` 詳情請參閱 [URL 至 PDF 程式碼範例](/java/examples/converting-a-url-to-a-pdf/)。 關於複雜的認證,請參閱 [Website & System Logins](https://ironpdf.com/java/examples/ironpdf-website-and-system-logins/)。

如何格式化 PDF 檔案? 使用 `ChromePdfRenderOptions` 指定 PDF 格式。 設定頁面方向、大小和頁邊。 將選項作為第二個參數傳給 render 方法: ```java // 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("", renderOptions); formattedPdf.saveAs(Paths.get("formatted.pdf")); ``` 請參閱[PDF 生成設定](/java/examples/pdf-generation-settings/)以取得更多選項。 探索[自訂紙張尺寸](https://ironpdf.com/java/examples/custom-pdf-paper-size/)和[自訂頁邊](https://ironpdf.com/java/examples/ironpdf-set-custom-margins/)。

如何對 PDF 檔案進行密碼保護? 使用 `SecurityOptions` 對 PDF 進行密碼保護: ```java // 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); ``` 透過 PDF 的 `SecurityManager` 應用安全性: ```java // Apply security options to the PDF SecurityManager securityManager = urlToPdf.getSecurity(); securityManager.setSecurityOptions(securityOptions); // Save the password-protected PDF document urlToPdf.saveAs("protected.pdf"); ``` 開啟 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

請參閱 [Security and Metadata Example](/java/examples/security-and-metadata/) 以取得其他設定。

什麼是完整原始碼? 本教學的完整原始碼: ```java // 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 = "

This is an example HTML string.

"; 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")); } } ``` IronPDF 可在不損失格式的情況下渲染圖片和文字。 按鈕仍可點選,文字方塊仍可編輯。 該函式庫支援 [新增簽名](https://ironpdf.com/java/examples/pdf-signatures/)、[渲染圖表](https://ironpdf.com/java/examples/js-charts-to-pdf/),以及 [列印 PDF](https://ironpdf.com/java/how-to/java-print-pdf-tutorial/)。

關鍵要點是什麼? 本指南演示了使用 IronPDF 在 Java 中创建 PDF。 IronPDF 提供簡單的 API,可從 HTML 檔案、XML 文件或其他來源產生 PDF。 快速生成報告、發票或任何文件類型。 部署於[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/)。 IronPDF for Java 需要 [商業授權](/java/licensing/),起價為 $799 。 [取得免費試用版](trial-license)進行生產測試。 *[下載 IronPDF Java 函式庫](/java/how-to/java-create-pdf-tutorial/)。*

常見問題解答

在 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 來說,工作令人滿意因為它被重視且有實際影響。

準備好開始了嗎?
版本: 2025.12 剛發表