How to open a PDF file in Java on Windows / Any Platform

By | April 10, 2018

In Java development, sometimes we need to open a PDF file with java code. So in this java tutorial and example, we will show you two ways to open a PDF file with Java.

1. rundll32 – Windows Platform Solution

In Windows, you can use “rundll32” command to launch a PDF file, see example :

package com.cimblo.jdbc;

import java.io.File;

//Java solution to view a PDF file on Windows platform
public class HowToOpen_a_PDF_FileInJava {

	public static void main(String[] args) {

	  try {

		if ((new File("c:\\Java-Coding-Examples.pdf")).exists()) {
			Process p = Runtime
			   .getRuntime()
			   .exec("rundll32 url.dll,FileProtocolHandler c:\\Java-Coding-Examples.pdf");
			p.waitFor();				
		} else {
			System.out.println("File is not exists");
		}
		System.out.println("Done");
  	  } catch (Exception ex) {
		ex.printStackTrace();
	  }
	}
}

2. AWT Desktop – Cross Platform Solution

This Awt Desktop cross platform solution is always recommended, as it works in *nix, Windows and Mac platforms.

package com.cimblo.io;

import java.awt.Desktop;
import java.io.File;

//Java solution to view a PDF file in Cross platform
public class HowToOpen_a_PDF_FileInJava {

	public static void main(String[] args) {

	  try {
		File pdfFile = new File("c:\\Java-Coding-Tutorial.pdf");
		if (pdfFile.exists()) {

			if (Desktop.isDesktopSupported()) {
				Desktop.getDesktop().open(pdfFile);
			} else {
				System.out.println("Awt Desktop is not supported!");
			}

		} else {
			System.out.println("File is not exists!");
		}
		System.out.println("Done");
	  } catch (Exception javaExample) {
		javaExample.printStackTrace();
	  }
	}
}

That is two way about “How to open a PDF file in Java on Windows / Any Platform”, please give me feedback if any update or new best practice in the latest java code and trick.

Reference

  1. http://download.oracle.com/javase/6/docs/api/java/awt/Desktop.html

Leave a Reply

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