Open a PDF using Java Swing

In this tutorial, we will learn how to open a PDF using Java Swing without using any external dependencies. If you search on the internet all the tutorials will make you add some external dependencies to open a pdf file so here I will help you open a pdf file using java by only using the java application. This method involves using swing to create a button and then using a cmd command to execute and open the pdf specified in the exec() function.
The file name is saved as 3-Operators.pdf, and the command and function are stored in the java.lang.Runtime package

Code

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class app {

    public static void main(String[] args) {
        JFrame jfrm = new JFrame("pdf");
        JButton jbadmin = new JButton("Open pdf");
        jbadmin.setBounds(170, 60, 250, 60);
        jbadmin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jfrm.dispose();
                try {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler \"C:\\java\-Operators.pdf\"");
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Check your file details");
                }
            }
        });
        jfrm.setSize(650, 400);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrm.add(jbadmin);
        jfrm.setLayout(null);
        jfrm.setVisible(true);
    }
}
The interface to open a pdf named 3-operators
Swing GUI for the button to open a pdf

As soon as we click the button created the pdf file is opened as shown in the given image:

file will be opened
The file opened after the execution

This is how we open a PDF file using Java Swing.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top