In this article, we 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.mkyong.jdbc;
 
import java.io.File;
 
//Windows solution to view a PDF file
public class WindowsPlatformAppPDF {
 
	public static void main(String[] args) {
 
	  try {
 
		if ((new File("c:\\Java-Interview.pdf")).exists()) {
 
			Process p = Runtime
			   .getRuntime()
			   .exec("rundll32 url.dll,FileProtocolHandler c:\\Java-Interview.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.mkyong.io;
 
import java.awt.Desktop;
import java.io.File;
 
//Cross platform solution to view a PDF file
public class AnyPlatformAppPDF {
 
	public static void main(String[] args) {
 
	  try {
 
		File pdfFile = new File("c:\\Java-Interview.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 ex) {
		ex.printStackTrace();
	  }
 
	}
}

Reference

  1. http://download.oracle.com/javase/6/docs/api/java/awt/Desktop.html
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~