How to Preview PDF Files in 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.
- JDK (Java Development Kit) and Swing UI framework installed.
- A Java IDE (Integrated Development Environment) such as Eclipse, NetBeans, or IntelliJ IDEA.
- IronPDF library for Java (You can download it from the IronPDF website and include it in your project).
Setting up
- Create a new Java project in your chosen IDE. I'm using IntelliJ IDEA and created the project using Maven.
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>
XMLAdd 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;
}
}
The output PDF file
Converted 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);
}
}
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
);
}
Code Explanation
PDFPreview
extendsJFrame
, a top-level container for window creation.- Instance variables declared:
imagePanel
,scrollPane
, andimagePaths
. ConvertToImages()
takes in PDF fileexample.pdf
, and converts it to a series of images. ThePdfDocument
loads the PDF file and converts each page to aBufferedImage
, then saves each as a PNG in the assets/images/ directory and adds the paths toimagePaths
.PDFPreview()
initializes the application. It callsConvertToImages()
to populateimagePaths
.imagePanel
is initialized and sets its layout as a vertical box layout.- It iterates over
imagePaths
and createsImageIcon
for each image, adds them toJLabel
, and adds labels toimagePanel
. - The source code creates
JScrollPane
and setsimagePanel
as its viewport. - 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. main()
is the entry point of the program. It invokes thePDFPreview
constructor usingSwingUtilities.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.
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.
Frequently Asked Questions
How can I preview PDF files in a Java application?
You can preview PDF files in a Java application by using IronPDF to convert PDF pages into images and then displaying these images using Java Swing components. This involves loading a PDF with the PdfDocument
class, converting pages to BufferedImage
, and using a JPanel
and JScrollPane
to display them.
What are the steps to integrate a PDF library into my Java project?
To integrate IronPDF into your Java project, include the library in your project's pom.xml
file as a Maven dependency with the group ID 'com.ironsoftware' and the artifact ID 'ironpdf'. Ensure you have JDK and a Java IDE installed.
How do I convert PDF pages into images using Java?
With IronPDF, you can convert PDF pages to images by loading the PDF document using the PdfDocument
class and converting each page to a BufferedImage
. These images can then be saved as PNG files for further use.
What Java components are needed to display PDF pages as images?
To display PDF pages as images in Java, you can use Java Swing components, specifically a JPanel
to hold the images and a JScrollPane
to allow scrolling through the images.
Why is the Event Dispatch Thread important when creating a PDF viewer in Java?
The Event Dispatch Thread (EDT) is crucial because it ensures that all Swing components are created and modified on a dedicated thread for GUI operations, preventing potential threading issues in a Java application.
Can I use IronPDF for Java without licensing for development?
Yes, IronPDF can be used for free during development. There is also a free trial available for commercial purposes, allowing you to explore its features before purchasing a license.
Where can I find additional resources for using IronPDF in Java?
Additional resources, examples, and tutorials for using IronPDF in Java are available on the IronPDF website. These resources include guides on creating PDFs from HTML and various PDF manipulation techniques.
What is the process to convert PDF pages to images and display them in Java Swing?
To convert PDF pages to images using IronPDF, load the PDF using PdfDocument
, convert each page to a BufferedImage
, and save them as PNG files. Display these images using a JPanel
and JScrollPane
in a Java Swing application.