跳至页脚内容
在 JAVA 中使用 IRONPDF

如何在 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文档,下一步是使用PdfDocument类在此Java PDF查看器应用程序中加载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文件

结论

本文演示了如何使用IronPDF用于基于Java的应用程序来预览Java应用程序中的PDF文件,以及如何访问和显示PDF文件。

利用IronPDF,您可以轻松将PDF预览功能集成到Java应用程序中。 有关使用IronPDF for Java的详细指导和示例,您可以参考此示例。 Java PDF阅读器教程请访问此文章以阅读PDF文件

IronPDF可免费用于开发用途。 要了解有关许可的详细信息,您可以访问提供的许可页。 还提供免费试用用于商业用途。

常见问题解答

如何在Java应用程序中预览PDF文件?

您可以通过使用IronPDF将PDF页面转换为图像,然后使用Java Swing组件显示这些图像来在Java应用程序中预览PDF文件。这涉及使用PdfDocument类加载PDF,将页面转换为BufferedImage,并使用JPanelJScrollPane来显示它们。

在我的Java项目中集成PDF库的步骤是什么?

要将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文件。然后在Java Swing应用程序中使用JPanelJScrollPane显示这些图像。

Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。