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

如何在 Java 中預覽 PDF 文件

這篇文章將展示如何使用 IronPDF 在 Java 應用程序中預覽 PDF 文件。

IronPDF

IronPDF is a high-performance Java library, offering fast and accurate operations, making it an excellent choice for PDF-related tasks such as reading PDF files, extracting text and images, merging, and 拆分

藉助 IronPDF 庫,您可以從 HTML 、URL 和字符串創建 PDF,並具有精確的像素完美渲染。

先決條件

要在 Java 中創建一個 PDF 文檔查看器,您需要設置以下內容。

  1. 安裝 JDK(Java 開發工具包)和 Swing UI 框架。
  2. 一個 Java IDE(集成開發環境),如 Eclipse、NetBeans 或 IntelliJ IDEA。
  3. 用於 Java 的 IronPDF 庫(您可以從 IronPDF 網站 下載並將其包含在您的項目中)。

設置

  1. 在您選擇的 IDE 中創建一個新的 Java 專案。我使用 IntelliJ IDEA 並使用 Maven 創建專案。
  2. 使用 Maven 將 IronPDF 庫添加到您的項目中,方法是在專案的 pom.xml 文件中添加如下所示的依賴項:

    <!-- Add IronPDF dependency in your pom.xml -->
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>latest_version</version>
    </dependency>
    <!-- Add IronPDF dependency in your pom.xml -->
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>latest_version</version>
    </dependency>
    XML
  3. 添加必要的導入:

    import com.ironsoftware.ironpdf.PdfDocument;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.List;
    import com.ironsoftware.ironpdf.PdfDocument;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.List;
    JAVA

加載 PDF 文件格式

若要查看 PDF 文檔,下一步是在此 Java PDF 查看應用程序中使用 PdfDocument 類加載 PDF 文件。

public class PDFPreview extends JFrame {

    private List<String> imagePaths = new ArrayList<>();

    private List<String> ConvertToImages() throws IOException {
        // Load the PDF document from a file
        PdfDocument pdfDocument = PdfDocument.fromFile(Paths.get("example.pdf"));
        // Convert the PDF pages to a list of BufferedImages
        List<BufferedImage> extractedImages = pdfDocument.toBufferedImages();
        int i = 1;
        // Iterate over the extracted images and save each to an image file
        for (BufferedImage extractedImage : extractedImages) {
            String fileName = "assets/images/" + i + ".png";
            ImageIO.write(extractedImage, "PNG", new File(fileName));
            // Store the file paths in the image paths list
            imagePaths.add("assets/images/" + i + ".png");
            i++;
        }
        return imagePaths;
    }
}
public class PDFPreview extends JFrame {

    private List<String> imagePaths = new ArrayList<>();

    private List<String> ConvertToImages() throws IOException {
        // Load the PDF document from a file
        PdfDocument pdfDocument = PdfDocument.fromFile(Paths.get("example.pdf"));
        // Convert the PDF pages to a list of BufferedImages
        List<BufferedImage> extractedImages = pdfDocument.toBufferedImages();
        int i = 1;
        // Iterate over the extracted images and save each to an image file
        for (BufferedImage extractedImage : extractedImages) {
            String fileName = "assets/images/" + i + ".png";
            ImageIO.write(extractedImage, "PNG", new File(fileName));
            // Store the file paths in the image paths list
            imagePaths.add("assets/images/" + i + ".png");
            i++;
        }
        return imagePaths;
    }
}
JAVA

如何在 Java 中預覽 PDF 文件,圖 1:輸出 PDF 文件 輸出 PDF 文件

轉換為圖像:

如何在 Java 中預覽 PDF 文件,圖 2:將 PDF 文件轉換為圖像 將 PDF 文件轉換為圖像

創建 PDF 查看器窗口

現在,您可以使用 Java Swing 組件在預覽窗口中顯示轉換後的圖像。

public class PDFPreview extends JFrame {
    private JPanel imagePanel;
    private JScrollPane scrollPane;

    public PDFPreview() {
        try {
            // Convert the PDF to images and store the image paths
            imagePaths = this.ConvertToImages();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Create imagePanel
        imagePanel = new JPanel();
        imagePanel.setLayout(new BoxLayout(imagePanel, BoxLayout.Y_AXIS));

        // Add images to the panel
        for (String imagePath : imagePaths) {
            ImageIcon imageIcon = new ImageIcon(imagePath);
            JLabel imageLabel = new JLabel(imageIcon);
            imageLabel.setBorder(new EmptyBorder(10, 10, 10, 10));
            imagePanel.add(imageLabel);
        }

        // Create the scroll pane and add imagePanel to it
        scrollPane = new JScrollPane(imagePanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        // Set up the frame
        getContentPane().add(scrollPane);
        setTitle("PDF Viewer");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
}
public class PDFPreview extends JFrame {
    private JPanel imagePanel;
    private JScrollPane scrollPane;

    public PDFPreview() {
        try {
            // Convert the PDF to images and store the image paths
            imagePaths = this.ConvertToImages();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Create imagePanel
        imagePanel = new JPanel();
        imagePanel.setLayout(new BoxLayout(imagePanel, BoxLayout.Y_AXIS));

        // Add images to the panel
        for (String imagePath : imagePaths) {
            ImageIcon imageIcon = new ImageIcon(imagePath);
            JLabel imageLabel = new JLabel(imageIcon);
            imageLabel.setBorder(new EmptyBorder(10, 10, 10, 10));
            imagePanel.add(imageLabel);
        }

        // Create the scroll pane and add imagePanel to it
        scrollPane = new JScrollPane(imagePanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        // Set up the frame
        getContentPane().add(scrollPane);
        setTitle("PDF Viewer");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
}
JAVA

調用主類構造函數

最後,將以下代碼放入 PDFPreview 類的主方法中:

public static void main(String[] args) {
    // Run the PDF viewer in the Event Dispatch Thread
    SwingUtilities.invokeLater(
        PDFPreview::new
    );
}
public static void main(String[] args) {
    // Run the PDF viewer in the Event Dispatch Thread
    SwingUtilities.invokeLater(
        PDFPreview::new
    );
}
JAVA

代碼解釋

  1. PDFPreview 擴展了 JFrame,用於窗口創建的頂級容器。
  2. 聲明實例變量:imagePanelscrollPaneimagePaths
  3. ConvertToImages() 接收 PDF 文件 example.pdf 並將其轉換為一系列圖像。 PdfDocument 加載 PDF 文件並將每頁轉換為 BufferedImage,然後將每個頁面保存為 PNG 在 assets/images/ 目錄中,並將路徑添加到 imagePaths
  4. PDFPreview() 初始化應用程序。 它調用 ConvertToImages() 來填充 imagePaths
  5. imagePanel 被初始化並將佈局設置為垂直箱佈局。
  6. 它遍歷 imagePaths 並為每個圖像創建 ImageIcon,將它們添加到 JLabel,並將標籤添加到 imagePanel
  7. 源代碼創建 JScrollPane 並將 imagePanel 設置為其視口。
  8. 接下來,代碼將 scrollPane 添加到框架的內容窗格,設置框架的標題,設置默認關閉操作,打包組件,將框架居中在屏幕上並使其可見。
  9. main() 是程序的入口點。 它使用 SwingUtilities.invokeLater() 調用 PDFPreview 構造函數,以確保在事件調度线程上創建和修改 Swing 組件,專用於 GUI 操作的线程。

現在,執行程序,將顯示 PDF 文檔文件查看器以及加載的 PDF 文檔。

如何在 Java 中預覽 PDF 文件,圖 3:輸出 PDF 文件 輸出 PDF 文件

結論

這篇文章展示了如何在基於 Java 的應用程序中使用 IronPDF 來預覽 PDF 文件,以及如何訪問和顯示 PDF 文件。

使用 IronPDF,您可以輕鬆地將 PDF 預覽功能集成到您的 Java 應用程序中。 有關使用 Java 的 IronPDF 的詳細指導和範例,您可以參閱此 範例。 要獲取 Java PDF 閱讀器教程,請訪問此 文章以閱讀 PDF 文件

IronPDF 在開發用途上是免費的。 要了解有關許可證詳細信息,您可以訪問提供的 許可證頁面。 也提供商業用途的免費試用

常見問題解答

如何在 Java 應用程式中預覽 PDF 文件?

您可以在 Java 應用程式中使用 IronPDF 來將 PDF 頁面轉換為圖像,然後使用 Java Swing 組件顯示這些圖像。這涉及到使用 PdfDocument 類加載 PDF、將頁面轉換為 BufferedImage,並使用 JPanelJScrollPane 來顯示它們。

將 PDF 庫集成到我的 Java 專案中有哪些步驟?

要將 IronPDF 集成到您的 Java 專案中,請將該庫包括在您的專案的 pom.xml 文件中作為 Maven 依賴,組 ID 為 'com.ironsoftware',工件 ID 為 'ironpdf'。確保您安裝了 JDK 和 Java IDE。

如何使用 Java 將 PDF 頁面轉換為圖像?

透過 IronPDF,可以使用 PdfDocument 類加載 PDF 文檔並將每頁轉換為 BufferedImage,從而將 PDF 頁面轉換為圖像。這些圖像然後可以保存為 PNG 文件以供進一步使用。

顯示 PDF 頁面為圖像需要哪些 Java 組件?

要在 Java 中顯示 PDF 頁面為圖像,您可以使用 Java Swing 組件,特別是用於存放圖像的 JPanel 和允許滾動圖像的 JScrollPane

為什麼在 Java 中創建 PDF 查看器時事件調度線程很重要?

事件調度線程 (EDT) 很重要,因為它確保所有的 Swing 組件都在專用的線程上創建和修改,以進行 GUI 操作,從而防止在 Java 應用程式中可能的線程問題。

我可以在不獲得許可的情況下使用 IronPDF for Java 進行開發嗎?

是的,IronPDF 可以在開發期間免費使用。還有一個免費試用版可供商業用途使用,允許您在購買許可前探索其功能。

在哪裡可以找到有關在 Java 中使用 IronPDF 的其他資源?

有關在 Java 中使用 IronPDF 的其他資源、示例和教程可在 IronPDF 網站上找到。這些資源包括有關從 HTML 創建 PDF 和各種 PDF 操作技術的指南。

將 PDF 頁面轉換為圖像並在 Java Swing 中顯示它們的過程是什麼?

要使用 IronPDF 將 PDF 頁面轉換為圖像,請使用 PdfDocument 加載 PDF,將每頁轉換為 BufferedImage,並將它們保存為 PNG 文件。使用 JPanelJScrollPane 在 Java Swing 應用程式中顯示這些圖像。

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

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

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

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