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

Java PDF 渲染庫(開發人員教程)

介紹 Java PDF 庫,IronPDF

如果您在進行 Java 專案並需要從 HTML 生成 PDF 文件或從 PDF 中提取文字,您應該尋找可靠且高效的 Java PDF 庫。 您可能會發現 IronPDF - Java PDF 庫,它簡化了 PDF 的生成和操作文檔,讓您作為開發者的生活更容易管理。 市面上有多種 PDF 庫,例如 PDF Clown 或 iText,但本文將深入探討 IronPDF 的世界,並探索它如何在您的 Java 專案中幫助您。

IronPDF入門指南

IronPDF 是一個 Java 庫,允許您在 Java 應用程式中創建、讀取和編輯 PDF 文件。 這個多功能的庫支持使用 IronPDF 從 HTML 生成 PDF、現有的 PDF 文件和 URL。 您可以使用 IronPDF 從 PDF 中提取文字,這使得它成為任何處理 PDF 文件的 Java 開發者必備的工具。

在 Maven 專案中安裝 IronPDF

Maven 是 Java 專案中流行的構建自動化和依賴管理工具。 要在 Maven 專案中安裝 IronPDF,您需要將必要的依賴添加到您的 pom.xml 檔中。

以下是如何將 IronPDF 和其所需的日誌依賴 SLF4J 添加到您的 Maven 專案中的指導:

  1. 打開您專案的 pom.xml 檔。
  2. 找到 dependencies 部分。 如果不存在,請創建一個。
  3. 添加以下 IronPDF 和 SLF4J 的依賴項目:

    <dependencies>
        <!-- IronPDF Dependency -->
        <dependency>
            <groupId>com.ironsoftware</groupId>
            <artifactId>ironpdf</artifactId>
            <version>2023.10.1</version>
        </dependency>
    
        <!-- SLF4J Dependency (Simple Logging Facade for Java) -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.7</version>
        </dependency>
    </dependencies>
    <dependencies>
        <!-- IronPDF Dependency -->
        <dependency>
            <groupId>com.ironsoftware</groupId>
            <artifactId>ironpdf</artifactId>
            <version>2023.10.1</version>
        </dependency>
    
        <!-- SLF4J Dependency (Simple Logging Facade for Java) -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.7</version>
        </dependency>
    </dependencies>
    XML
  4. 保存 pom.xml 文件。
  5. 通過您的 IDE 或在專案根目錄下執行 mvn install 命令運行您的 Maven 專案。 Maven 會自動下載並將 IronPDF 和 SLF4J 的依賴項添加到您的專案中。

現在,您已成功將 IronPDF 添加到您的 Maven 專案中,您可以開始使用這個強大的 Java PDF 庫來創建、編輯和操作 Java 應用程式中的 PDF 文件。 別忘了查閱 IronPDF 文檔,以獲取更多示例和有關庫功能和能力的詳細信息。 讓我們在這裡探索一些功能。

將 HTML 渲染為 PDF

處理 PDF 文件時最常見的任務之一是使用 IronPDF 將 HTML 轉換為 PDF。 IronPDF 讓這件事情變得非常簡單,只需要幾行代碼。 以下是一個將簡單 HTML 字串轉換為 PDF 文件的示例:

import com.ironsoftware.ironpdf.*;

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

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

            // Set a log path
            Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

            // Render the HTML as a PDF, stored in myPdf as type PdfDocument
            PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1>Hello World</h1> Made with IronPDF!");

            // Save the PdfDocument to a file
            myPdf.saveAs(Paths.get("html_saved.pdf"));
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
import com.ironsoftware.ironpdf.*;

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

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

            // Set a log path
            Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

            // Render the HTML as a PDF, stored in myPdf as type PdfDocument
            PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1>Hello World</h1> Made with IronPDF!");

            // Save the PdfDocument to a file
            myPdf.saveAs(Paths.get("html_saved.pdf"));
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
JAVA

這段代碼段匯入了必要的 IronPDF 類別並應用了一個授權金鑰。 接下來,它設置了用於調試目的的日誌路徑。 renderHtmlAsPdf 方法將 HTML 字串作為輸入,並將其轉換為 PDF 文件,然後您可以將其保存到一個文件中。

Java PDF 渲染器庫(開發者教程),圖 1:輸出 PDF 文件 輸出 PDF 文件

將 HTML 文件轉換為 PDF

IronPDF 還支持將 HTML 文件轉換為 PDF 文件。 該過程與前一個示例非常相似,只是使用的方法略有改變:

import com.ironsoftware.ironpdf.*;

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

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

            // Set a log path
            Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

            // Render the HTML file as a PDF, stored in myPdf as type PdfDocument
            PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");

            // Save the PdfDocument to a file
            myPdf.saveAs(Paths.get("html_file_saved.pdf"));
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
import com.ironsoftware.ironpdf.*;

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

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

            // Set a log path
            Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

            // Render the HTML file as a PDF, stored in myPdf as type PdfDocument
            PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");

            // Save the PdfDocument to a file
            myPdf.saveAs(Paths.get("html_file_saved.pdf"));
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
JAVA

此情況下,使用的是 renderHtmlFileAsPdf 方法,而非 renderHtmlAsPdf,它接受 HTML 文件的路徑作為輸入,並創建 PDF 文件。

將 URL 轉換為 PDF

IronPDF 能夠將網頁轉換為 PDF 文件。 當您想從動態網頁生成 PDF 報告時,這一特別有用。 下面的代碼段展示了如何做到這一點:

import com.ironsoftware.ironpdf.*;

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

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

            // Set a log path
            Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

            // Render the URL as a PDF, stored in myPdf as type PdfDocument
            PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Save the PdfDocument to a file
            myPdf.saveAs(Paths.get("url.pdf"));
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
import com.ironsoftware.ironpdf.*;

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

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

            // Set a log path
            Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

            // Render the URL as a PDF, stored in myPdf as type PdfDocument
            PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Save the PdfDocument to a file
            myPdf.saveAs(Paths.get("url.pdf"));
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
JAVA

renderUrlAsPdf 方法將 URL 作為輸入,並從網頁的內容創建 PDF 文件。 此方法可以處理複雜的頁面,包括那些帶有 JavaScript 和 CSS 的頁面。

Java PDF 渲染器庫(開發者教程),圖 2:來自 URL 的輸出 PDF 文件 從 URL 的輸出 PDF 文件

從 PDF 中提取文字

除創建 PDF 文件之外,IronPDF 還提供了從現有 PDF 文件中提取文字的功能。 此功能在需要搜索、索引或分析 PDF 文件內容時非常有用。以下代碼段展示了如何從 PDF 文件中提取文本:

import com.ironsoftware.ironpdf.*;

public class ExtractTextFromPdfExample {
    public static void main(String[] args) {
        // Render PDF from a URL
        PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");

        // Extract all text from the PDF document
        String text = pdf.extractAllText();

        // Output the extracted text
        System.out.println("Text extracted from the PDF: " + text);
    }
}
import com.ironsoftware.ironpdf.*;

public class ExtractTextFromPdfExample {
    public static void main(String[] args) {
        // Render PDF from a URL
        PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");

        // Extract all text from the PDF document
        String text = pdf.extractAllText();

        // Output the extracted text
        System.out.println("Text extracted from the PDF: " + text);
    }
}
JAVA

在此示例中,從 URL 渲染了一個 PDF,使用 extractAllText 方法獲取 PDF 文件的文本內容。 提取的文本可以被打印到控制台或根據需要進行處理。

使用 IronPDF 將圖像轉換為 PDF

IronPDF 還可以將圖像轉換為 PDF 文件。 當您需要創建 PDF 資料夾或將多個圖像合併為一個檔案時,這派上用場。以下代碼段展示了如何將目錄中的一組圖像轉換為單個 PDF 文件:

import com.ironsoftware.ironpdf.*;

import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

public class ImagesToPdfExample {
    public static void main(String[] args) {
        Path imageDirectory = Paths.get("assets/images");

        List<Path> imageFiles = new ArrayList<>();

        // Use DirectoryStream to iterate over image files
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(imageDirectory, "*.{png,jpg}")) {
            for (Path entry : stream) {
                imageFiles.add(entry);
            }

            // Convert images to a PDF document and save it
            PdfDocument.fromImage(imageFiles).saveAs(Paths.get("assets/composite.pdf"));
        } catch (IOException exception) {
            throw new RuntimeException(String.format("Error converting images to PDF from directory: %s: %s",
                    imageDirectory,
                    exception.getMessage()),
                    exception);
        }
    }
}
import com.ironsoftware.ironpdf.*;

import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

public class ImagesToPdfExample {
    public static void main(String[] args) {
        Path imageDirectory = Paths.get("assets/images");

        List<Path> imageFiles = new ArrayList<>();

        // Use DirectoryStream to iterate over image files
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(imageDirectory, "*.{png,jpg}")) {
            for (Path entry : stream) {
                imageFiles.add(entry);
            }

            // Convert images to a PDF document and save it
            PdfDocument.fromImage(imageFiles).saveAs(Paths.get("assets/composite.pdf"));
        } catch (IOException exception) {
            throw new RuntimeException(String.format("Error converting images to PDF from directory: %s: %s",
                    imageDirectory,
                    exception.getMessage()),
                    exception);
        }
    }
}
JAVA

僅用這一段代碼,IronPDF 就輕鬆地將多個圖像轉換為單個 PDF 文件,進一步展示了該庫在各種 PDF 相關任務中的多功能性和實用性。

結論

IronPDF 是一個強大且多功能的 Java PDF 庫,可簡化 Java 應用程式中的 PDF 生成和操作。 With its easy-to-use API, you can effortlessly convert HTML, HTML files, and URLs into PDF documents using IronPDF, as well as extract text from PDFs from existing PDF files. 通過將 IronPDF 集成到您的 Java 項目中,您可以簡化工作流並輕鬆創建高質量的 PDF。

Additionally, IronPDF is also capable of rendering charts in PDFs, watermarking PDF documents, working with PDF forms and digital signatures programmatically.

IronPDF 提供免費試用,讓您有足夠的時間來評估其功能並確定它是否適合您的項目。 如果您決定在試用期後繼續使用 IronPDF,其授權價格從 $799 開始。

常見問題解答

Java PDF 庫 IronPDF 是用來做什麼的?

IronPDF 是一個 Java 庫,旨在支持在 Java 應用中創建、讀取和編輯 PDF 文件。它擅長於將 HTML、HTML 文件和 URL 轉換為 PDF,幾乎不需要編程。

如何將 PDF 庫集成到 Maven 專案中?

要將 IronPDF 集成到 Maven 專案中,您需要在 `` 部分中將 IronPDF 和 SLF4J 依賴項添加到您的 `pom.xml` 文件中。此設置允許 Maven 下載並將這些依賴項加入您的專案。

如何使用 Java 將 HTML 轉換為 PDF?

可以使用 IronPDF 的 renderHtmlAsPdf 方法在 Java 中將 HTML 轉換為 PDF。該方法處理 HTML 字串並生成 PDF 文件。

我可以將 HTML 文件轉換為 PDF 文件嗎?

是的,IronPDF 允許您使用 renderHtmlFileAsPdf 方法將 HTML 文件轉換為 PDF,該方法讀取 HTML 文件並輸出 PDF 文件。

在 Java 中是否可以將網頁轉換為 PDF?

是的,使用 IronPDF,您可以使用 renderUrlAsPdf 方法將網頁轉換為 PDF。該方法接收一個 URL 並從網頁內容創建 PDF。

如何在 Java 中程式化提取 PDF 文件中的文本?

可以使用 IronPDF 的 extractAllText 方法來從 PDF 中提取文本,該方法檢索並輸出 PDF 文件中的文本內容。

可以使用 Java 庫將圖片轉換為 PDF 嗎?

是的,IronPDF 支持將圖片轉換為 PDF。可以使用 fromImage 方法將單個或多個圖片轉換為一個 PDF 文件。

IronPDF 為 PDF 操作提供了什麼其他功能?

IronPDF 提供其他功能,例如在 PDF 中呈現圖表、添加水印以及處理 PDF 表單和數字簽名,這些都可以程式化管理。

是否有免費試用版可用於測試 IronPDF?

是的,IronPDF 提供免費試用版以供評估,讓您在購買前測試其功能。

在哪裡可以找到更多關於使用 IronPDF 在 Java 上的資訊和範例?

可以在 IronPDF 官方文檔中找到使用 IronPDF 的詳細資訊和範例,該文檔提供全面的指導和程式碼片段。

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

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

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

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