Saltar al pie de página
USANDO IRONPDF PARA JAVA

Cómo Previsualizar Archivos PDF en Java

This article will demonstrate how to use IronPDF to preview PDF files within a Java application.

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 splitting.

With the help of the IronPDF library, you can create PDFs from HTML, URLs, and strings with precise pixel-perfect rendering.

Prerequisites

To create a document viewer for PDF documents in Java, you need the following things set in place.

  1. JDK (Java Development Kit) and Swing UI framework installed.
  2. A Java IDE (Integrated Development Environment) such as Eclipse, NetBeans, or IntelliJ IDEA.
  3. IronPDF library for Java (You can download it from the IronPDF website and include it in your project).

Setting up

  1. Create a new Java project in your chosen IDE. I'm using IntelliJ IDEA and created the project using Maven.
  2. Add the IronPDF library to your project using Maven by adding the dependencies shown below in your project's pom.xml file:

    <!-- 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. Add the necessary imports:

    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

Loading the PDF File Format

To view PDF documents, the next step is to load the PDF file in this Java PDF viewer application by using the PdfDocument class.

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

How to Preview PDF Files in Java, Figure 1: The output PDF file The output PDF file

Converted to Images:

How to Preview PDF Files in Java, Figure 2: Convert PDF file to images Convert PDF file to images

Creating PDF Viewer Window

Now, you can display the converted images in a preview window using Java Swing components.

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

Invoke the Main class Constructor

Finally, place the following code in the main method in the PDFPreview class:

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

Code Explanation

  1. PDFPreview extends JFrame, a top-level container for window creation.
  2. Instance variables declared: imagePanel, scrollPane, and imagePaths.
  3. ConvertToImages() takes in PDF file example.pdf, and converts it to a series of images. The PdfDocument loads the PDF file and converts each page to a BufferedImage, then saves each as a PNG in the assets/images/ directory and adds the paths to imagePaths.
  4. PDFPreview() initializes the application. It calls ConvertToImages() to populate imagePaths.
  5. imagePanel is initialized and sets its layout as a vertical box layout.
  6. It iterates over imagePaths and creates ImageIcon for each image, adds them to JLabel, and adds labels to imagePanel.
  7. The source code creates JScrollPane and sets imagePanel as its viewport.
  8. Next, the code adds scrollPane to the frame's content pane, sets frame's title, sets default close operation, packs components, centers frame on the screen, and makes it visible.
  9. main() is the entry point of the program. It invokes the PDFPreview constructor using SwingUtilities.invokeLater() to ensure the Swing components are created and modified on the Event Dispatch Thread, the dedicated thread for GUI operations.

Now, execute the program and the PDF document file viewer will be displayed with the loaded PDF document.

How to Preview PDF Files in Java, Figure 3: The output PDF file The output PDF file

Conclusion

This article demonstrated how to use IronPDF for Java-based applications to preview PDF files within a Java application, and how to access and display a PDF file.

With IronPDF, you can easily integrate PDF preview functionality into your Java application. For detailed guidance and examples on utilizing IronPDF for Java, you can refer to this example. For the Java PDF reader tutorial visit this article to read PDF files.

IronPDF is free for development purposes. To learn more about the licensing details, you can visit the provided licensing page. A free trial for commercial use is also available.

Preguntas Frecuentes

¿Cómo puedo previsualizar archivos PDF en una aplicación Java?

Puedes previsualizar archivos PDF en una aplicación Java utilizando IronPDF para convertir las páginas del PDF en imágenes y luego mostrando estas imágenes usando componentes de Java Swing. Esto implica cargar un PDF con la clase PdfDocument, convertir las páginas a BufferedImage, y usar un JPanel y JScrollPane para mostrarlas.

¿Cuáles son los pasos para integrar una biblioteca PDF en mi proyecto Java?

Para integrar IronPDF en tu proyecto Java, incluye la biblioteca en el archivo pom.xml de tu proyecto como una dependencia de Maven con el ID de grupo 'com.ironsoftware' y el ID de artefacto 'ironpdf'. Asegúrate de tener instalado el JDK y un IDE de Java.

¿Cómo convierto las páginas de PDF en imágenes usando Java?

Con IronPDF, puedes convertir las páginas de PDF en imágenes cargando el documento PDF usando la clase PdfDocument y convirtiendo cada página en un BufferedImage. Estas imágenes se pueden guardar como archivos PNG para su uso posterior.

¿Qué componentes de Java se necesitan para mostrar páginas de PDF como imágenes?

Para mostrar páginas de PDF como imágenes en Java, puedes usar componentes Java Swing, específicamente un JPanel para contener las imágenes y un JScrollPane para permitir el desplazamiento a través de las imágenes.

¿Por qué es importante el Event Dispatch Thread al crear un visor de PDF en Java?

El Event Dispatch Thread (EDT) es crucial porque asegura que todos los componentes de Swing se creen y modifiquen en un hilo dedicado para operaciones de GUI, evitando posibles problemas de hilos en una aplicación Java.

¿Puedo usar IronPDF para Java sin licencia para el desarrollo?

Sí, IronPDF se puede usar gratis durante el desarrollo. También hay una prueba gratuita disponible para fines comerciales, lo que te permite explorar sus características antes de comprar una licencia.

¿Dónde puedo encontrar recursos adicionales para usar IronPDF en Java?

Recursos adicionales, ejemplos, y tutoriales para usar IronPDF en Java están disponibles en el sitio web de IronPDF. Estos recursos incluyen guías para crear PDFs desde HTML y varias técnicas de manipulación de PDF.

¿Cuál es el proceso para convertir páginas de PDF a imágenes y mostrarlas en Java Swing?

Para convertir páginas de PDF a imágenes usando IronPDF, carga el PDF usando PdfDocument, convierte cada página en un BufferedImage, y guárdalas como archivos PNG. Muestra estas imágenes usando un JPanel y JScrollPane en una aplicación Java Swing.

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...

Leer más