跳過到頁腳內容
使用 IRONPDF FOR JAVA

Java 庫 PDF 生成(完整代碼示例)

本文將探討 IronPDF 庫,一個在 Java 中創建 PDF 的絕佳工具。

IronPDF:Java PDF 庫

IronPDF 是一個受歡迎的Java PDF 庫,允許開發人員輕鬆創建 PDF 文件、PDF 表單、數字簽名 PDF 文件等等。 With IronPDF, you can use existing PDF documents as templates to generate new PDF files, store PDF data in databases for future use, convert PDFs into other formats like HTML, and even merge multiple PDFs into one.

IronPDF 允許用戶向 PDF 添加文字註釋以個性化他們創建的文件。 此外,使用 IronPDF,您可以在您的 PDF 中加入安全設置,如密碼或水印。 它有助於將 PDF 功能集成到 Java 程序中。 IronPDF 是一個非常多功能且強大的工具,可快速安全地生成 PDF。 讓我們看看 IronPDF 如何用於創建 PDF 文件。

使用 IronPDF 生成 PDF 文件

IronPDF 是創建 PDF 文件的無價之寶。 它提供了所有您所需的功能,可以快速將文檔、網頁和圖像轉換為穩定、安全且易於共享的 PDF。 讓我們在這個演示程序中安裝 IronPDF。

安裝 IronPDF Java PDF 庫

要在 Maven 專案中安裝 IronPDF Java,您可以將以下依賴項添加到專案的pom.xml文件:

<dependencies>
    <!-- Add IronPDF dependency -->
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>YOUR-VERSION-HERE</version>
    </dependency>
    <!-- Add SLF4J logging dependency -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>YOUR-VERSION-HERE</version>
    </dependency>
</dependencies>
<dependencies>
    <!-- Add IronPDF dependency -->
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>YOUR-VERSION-HERE</version>
    </dependency>
    <!-- Add SLF4J logging dependency -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>YOUR-VERSION-HERE</version>
    </dependency>
</dependencies>
XML

這將添加 IronPDF for Java 庫以及它使用的 SLF4J 日誌記錄器。 建議使用最新版本的 IronPDF for Java。 一旦添加了依賴項,您可以運行mvn install來在本地倉庫中安裝依賴項,然後您的專案就可以使用 IronPDF for Java。

創建 PDF 文檔的 Java 代碼

此代碼是用 Java 編寫的,使用 IronPDF 庫將 HTML 轉換為 PDF 文檔

// Import statement for IronPDF Java  
import com.ironsoftware.ironpdf.*;

import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException {
        // Apply your license key
        License.setLicenseKey("YOUR-LICENSE-KEY");

        // Set a log path to store log files generated by IronPDF
        Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

        // Define the HTML content to convert into a PDF
        String html = "<!DOCTYPE html>\r\n"
                + "<html>\r\n"
                + "  <head>\r\n"
                + "    <link href='https://fonts.googleapis.com/css2?family=Popin&display=swap' rel='stylesheet'>\r\n"
                + "    <style>\r\n"
                + "      /* Add CSS styles for the invoice here */\r\n"
                + "      body {\r\n"
                + "        font-family: 'Popin', cursive;\r\n"
                + "      }\r\n"
                + "      .invoice {\r\n"
                + "        width: 80%;\r\n"
                + "        margin: 0 auto;\r\n"
                + "        border: 1px solid #ccc;\r\n"
                + "        padding: 20px;\r\n"
                + "        background-color: #f5f5f5;\r\n"
                + "        color: #333;\r\n"
                + "      }\r\n"
                + "      .invoice h1 {\r\n"
                + "        text-align: center;\r\n"
                + "      }\r\n"
                + "      .invoice .invoice-info {\r\n"
                + "        display: flex;\r\n"
                + "        justify-content: space-between;\r\n"
                + "        margin-bottom: 20px;\r\n"
                + "      }\r\n"
                + "      .invoice .invoice-info div {\r\n"
                + "        width: 45%;\r\n"
                + "      }\r\n"
                + "      .invoice table {\r\n"
                + "        width: 100%;\r\n"
                + "        border-collapse: collapse;\r\n"
                + "      }\r\n"
                + "      .invoice table th, .invoice table td {\r\n"
                + "        border: 1px solid #ccc;\r\n"
                + "        padding: 10px;\r\n"
                + "      }\r\n"
                + "      .invoice table th {\r\n"
                + "        text-align: left;\r\n"
                + "        background-color: #f5f5f5;\r\n"
                + "      }\r\n"
                + "      .invoice table td {\r\n"
                + "        text-align: right;\r\n"
                + "      }\r\n"
                + "      .invoice table td.total {\r\n"
                + "        font-weight: bold;\r\n"
                + "      }\r\n"
                + "    </style>\r\n"
                + "  </head>\r\n"
                + "  <body>\r\n"
                + "    <div class=\"invoice\">\r\n"
                + "      <h1>Invoice</h1>\r\n"
                + "      <div class=\"invoice-info\">\r\n"
                + "        <div>\r\n"
                + "          <p><strong>From:</strong></p>\r\n"
                + "          <p>Your Company Name</p>\r\n"
                + "          <p>123 Main St</p>\r\n"
                + "          <p>City, State ZIP</p>\r\n"
                + "        </div>\r\n"
                + "        <div>\r\n"
                + "          <p><strong>To:</strong></p>\r\n"
                + "          <p>Customer Name</p>\r\n"
                + "          <p>456 Park Ave</p>\r\n"
                + "          <p>City, State ZIP</p>\r\n"
                + "        </div>\r\n"
                + "      </div>\r\n"
                + "      <table>\r\n"
                + "        <thead>\r\n"
                + "          <tr>\r\n"
                + "            <th>Product</th>\r\n"
                + "            <th>Quantity</th>\r\n"
                + "            <th>Price</th>\r\n"
                + "            <th>Total</th>\r\n"
                + "          </tr>\r\n"
                + "        </thead>\r\n"
                + "        <tbody>\r\n"
                + "          <tr>\r\n"
                + "            <td>Product 1</td>\r\n"
                + "            <td>1</td>\r\n"
                + "            <td>$10.00</td>\r\n"
                + "            <td>$10.00</td>\r\n"
                + "          </tr>\r\n"
                + "          <tr>\r\n"
                + "            <td>Product 2</td>\r\n"
                + "            <td>2</td>\r\n"
                + "            <td>$5.00</td>\r\n"
                + "            <td>$10.00</td>\r\n"
                + "          </tr>\r\n"
                + "          <tr>\r\n"
                + "            <td colspan=\"3\" class=\"total\">Total:</td>\r\n"
                + "            <td class=\"total\">$20.00</td>\r\n"
                + "          </tr>\r\n"
                + "        </tbody>\r\n"
                + "      </table>\r\n"
                + "    </div>\r\n"
                + "  </body>\r\n"
                + "</html>";

        // Convert HTML to PDF document
        PdfDocument myPdf = PdfDocument.renderHtmlAsPdf(html);

        // Save the PDF document to a specified path
        myPdf.saveAs(Paths.get("C://HTMLtoPDF.pdf"));
    }
}
// Import statement for IronPDF Java  
import com.ironsoftware.ironpdf.*;

import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException {
        // Apply your license key
        License.setLicenseKey("YOUR-LICENSE-KEY");

        // Set a log path to store log files generated by IronPDF
        Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

        // Define the HTML content to convert into a PDF
        String html = "<!DOCTYPE html>\r\n"
                + "<html>\r\n"
                + "  <head>\r\n"
                + "    <link href='https://fonts.googleapis.com/css2?family=Popin&display=swap' rel='stylesheet'>\r\n"
                + "    <style>\r\n"
                + "      /* Add CSS styles for the invoice here */\r\n"
                + "      body {\r\n"
                + "        font-family: 'Popin', cursive;\r\n"
                + "      }\r\n"
                + "      .invoice {\r\n"
                + "        width: 80%;\r\n"
                + "        margin: 0 auto;\r\n"
                + "        border: 1px solid #ccc;\r\n"
                + "        padding: 20px;\r\n"
                + "        background-color: #f5f5f5;\r\n"
                + "        color: #333;\r\n"
                + "      }\r\n"
                + "      .invoice h1 {\r\n"
                + "        text-align: center;\r\n"
                + "      }\r\n"
                + "      .invoice .invoice-info {\r\n"
                + "        display: flex;\r\n"
                + "        justify-content: space-between;\r\n"
                + "        margin-bottom: 20px;\r\n"
                + "      }\r\n"
                + "      .invoice .invoice-info div {\r\n"
                + "        width: 45%;\r\n"
                + "      }\r\n"
                + "      .invoice table {\r\n"
                + "        width: 100%;\r\n"
                + "        border-collapse: collapse;\r\n"
                + "      }\r\n"
                + "      .invoice table th, .invoice table td {\r\n"
                + "        border: 1px solid #ccc;\r\n"
                + "        padding: 10px;\r\n"
                + "      }\r\n"
                + "      .invoice table th {\r\n"
                + "        text-align: left;\r\n"
                + "        background-color: #f5f5f5;\r\n"
                + "      }\r\n"
                + "      .invoice table td {\r\n"
                + "        text-align: right;\r\n"
                + "      }\r\n"
                + "      .invoice table td.total {\r\n"
                + "        font-weight: bold;\r\n"
                + "      }\r\n"
                + "    </style>\r\n"
                + "  </head>\r\n"
                + "  <body>\r\n"
                + "    <div class=\"invoice\">\r\n"
                + "      <h1>Invoice</h1>\r\n"
                + "      <div class=\"invoice-info\">\r\n"
                + "        <div>\r\n"
                + "          <p><strong>From:</strong></p>\r\n"
                + "          <p>Your Company Name</p>\r\n"
                + "          <p>123 Main St</p>\r\n"
                + "          <p>City, State ZIP</p>\r\n"
                + "        </div>\r\n"
                + "        <div>\r\n"
                + "          <p><strong>To:</strong></p>\r\n"
                + "          <p>Customer Name</p>\r\n"
                + "          <p>456 Park Ave</p>\r\n"
                + "          <p>City, State ZIP</p>\r\n"
                + "        </div>\r\n"
                + "      </div>\r\n"
                + "      <table>\r\n"
                + "        <thead>\r\n"
                + "          <tr>\r\n"
                + "            <th>Product</th>\r\n"
                + "            <th>Quantity</th>\r\n"
                + "            <th>Price</th>\r\n"
                + "            <th>Total</th>\r\n"
                + "          </tr>\r\n"
                + "        </thead>\r\n"
                + "        <tbody>\r\n"
                + "          <tr>\r\n"
                + "            <td>Product 1</td>\r\n"
                + "            <td>1</td>\r\n"
                + "            <td>$10.00</td>\r\n"
                + "            <td>$10.00</td>\r\n"
                + "          </tr>\r\n"
                + "          <tr>\r\n"
                + "            <td>Product 2</td>\r\n"
                + "            <td>2</td>\r\n"
                + "            <td>$5.00</td>\r\n"
                + "            <td>$10.00</td>\r\n"
                + "          </tr>\r\n"
                + "          <tr>\r\n"
                + "            <td colspan=\"3\" class=\"total\">Total:</td>\r\n"
                + "            <td class=\"total\">$20.00</td>\r\n"
                + "          </tr>\r\n"
                + "        </tbody>\r\n"
                + "      </table>\r\n"
                + "    </div>\r\n"
                + "  </body>\r\n"
                + "</html>";

        // Convert HTML to PDF document
        PdfDocument myPdf = PdfDocument.renderHtmlAsPdf(html);

        // Save the PDF document to a specified path
        myPdf.saveAs(Paths.get("C://HTMLtoPDF.pdf"));
    }
}
JAVA
  • 第一步是使用setLicenseKey方法應用許可證秘鑰。 秘鑰作為字符串參數傳遞; 在這種情況下,"YOUR-LICENSE-KEY"應替換為實際的許可證秘鑰。
  • 下一步是使用setLogPath方法設置日誌路徑。 這是 IronPDF 引擎日誌文件保存的地方。 在這種情況下,設置為"C:/tmp/IronPdfEngine.log"。
  • The main method is defined, and a PdfDocument object is created by calling the renderHtmlAsPdf method, passing in a string of HTML as the argument. 這將把 HTML 轉換為 PDF 並存儲在myPdf對象中。
  • 最後一步是使用[saveAs](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#saveAs(java.lang.String)方法將myPdf對象保存到文件中。 文件位置作為 Paths 對象的參數傳遞,在這種情況下為"HTMLtoPDF.pdf"。

在這裡,您可以看到上面程序的輸出,其中使用 IronPDF Java PDF 庫創建了一個 PDF 文件。

Java 庫 PDF 生成(完整代碼示例),圖1:來自 HTML 字符串的輸出 PDF 文件 來自 HTML 字符串的輸出 PDF 文件

從 URL 創建 PDF 文件

IronPDF 可以從各種來源,包括本地網絡和外部服務器,將網頁渲染為 PDF

import com.ironsoftware.ironpdf.*;

import java.io.IOException;
import java.nio.file.Paths;

public class UrlToPdfExample {
    public static void main(String[] args) throws IOException {
        // Apply your license key
        License.setLicenseKey("YOUR-LICENSE-KEY");

        // Set a log path to store log files generated by IronPDF
        Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

        // Convert a webpage to a PDF by specifying the URL
        PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

        // Save the PdfDocument to a file
        myPdf.saveAs(Paths.get("url.pdf"));
    }
}
import com.ironsoftware.ironpdf.*;

import java.io.IOException;
import java.nio.file.Paths;

public class UrlToPdfExample {
    public static void main(String[] args) throws IOException {
        // Apply your license key
        License.setLicenseKey("YOUR-LICENSE-KEY");

        // Set a log path to store log files generated by IronPDF
        Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

        // Convert a webpage to a PDF by specifying the URL
        PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

        // Save the PdfDocument to a file
        myPdf.saveAs(Paths.get("url.pdf"));
    }
}
JAVA
  • [PdfDocument.renderUrlAsPdf](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#renderUrlAsPdf(java.lang.String)方法專為此設計,並接受包含要轉換的網頁 URL 的字符串。 該方法檢索網頁的 HTML 內容並將其轉換為 PDF 文檔。 IronPDF 保留所有網頁組件的外觀,同時使交互功能(如鏈接、表單字段等)正常運作。

結果如下:

Java 庫 PDF 生成(完整代碼示例),圖2:從 URL 的輸出 PDF 文件 從 URL 的輸出 PDF 文件

總結

總之,IronPDF 是一個寶貴的 Java 庫,具有許多創建和操作 PDF 文件的功能。 Whether you need to digitally sign a PDF document, fill out PDF forms, or perform other tasks, IronPDF makes it easy to do so with minimal coding.

免費試用版提供和起價為$799的靈活定價選項,使 IronPDF 成為開發人員尋求為其項目新增 PDF 功能的經濟實惠解決方案。

常見問題解答

我如何在Java中創建PDF文檔?

使用IronPDF,您可以通過綜合API在Java中創建PDF文檔,從頭生成新的PDF或將現有文檔轉換為PDF格式。

Java中將HTML轉換為PDF的過程是什麼?

在Java中將HTML轉換為PDF,IronPDF提供了方法renderHtmlAsPdf,允許您輸入HTML字串,並接收PDF文檔作為輸出。

我如何在Java應用程序中將網頁URL轉換為PDF?

IronPDF允許使用方法renderUrlAsPdf將網頁URL轉換為PDF。此方法從URL檢索HTML內容並將其轉換為PDF文檔。

我可以使用Java庫對PDF文檔進行數字簽名嗎?

是的,IronPDF提供了對PDF文檔進行數字簽名的功能,確保文檔的真實性和完整性。

如何使用Java為PDF添加安全功能?

IronPDF提供安全功能,如密碼保護和水印,可以應用於PDF以增強其安全性。

在Maven項目中安裝PDF庫的步驟是什么?

要在Maven項目中安裝IronPDF,您需要將IronPDF依賴項和SLF4J日誌依賴項添加到您的pom.xml文件,然後執行mvn install命令。

如何使用Java操作現有的PDF文件?

IronPDF允許您通過提供編輯文本、合併文檔、添加註釋和應用數字簽名的方法來操作現有PDF文件。

購買前可以測試IronPDF的功能嗎?

是的,IronPDF提供免費試用,讓開發人員在做出購買決定前測試其功能。

使用PDF庫的好處是什麼?

像IronPDF這樣的Java PDF庫簡化了創建、編輯和轉換PDF的過程,減少大量代碼編寫的需求並提升效率。

如何使用Java將多個PDF文件合併為一個?

IronPDF具有將多個PDF文件合併為一個文檔的功能,使多個PDF文件輕鬆合併為一個文件。

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

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

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

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