Solved

Diaplay PDF file in JAVA

Posted on 2006-06-27
16
800 Views
Last Modified: 2013-11-23
How can I Display a PDF File in JAVA

Thanking you
0
Comment
Question by:sree032397
  • 5
  • 3
  • 2
  • +2
16 Comments
 
LVL 1

Expert Comment

by:mikal_sk
Comment Utility
Hey

Try this : hardcode youre path into displayURL method : "file://".



import java.io.IOException;

/*
* A simple, static class to display a URL in the system browser.
*/

public class BrowserControl{

    /**
     * Display a file in the system browser.  If you want to display a
     * file, you must include the absolute path name.
     *
     * @param url the file's url (the url must start with either "http://"or
     * "file://").
     */
  public static void displayURL(String url) {

        boolean windows = isWindowsPlatform();
        String cmd = null;

        try{
            if (windows){

                // cmd = 'rundll32 url.dll,FileProtocolHandler http://...'
                cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
                Process p = Runtime.getRuntime().exec(cmd);
            }
            else{
                // Under Unix, Netscape has to be running for the "-remote"
                // command to work.  So, we try sending the command and
                // check for an exit value.  If the exit command is 0,
                // it worked, otherwise we need to start the browser.
                // cmd = 'netscape -remote openURL(http://www.javaworld.com)'
                cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")";
                Process p = Runtime.getRuntime().exec(cmd);
                try{
                    // wait for exit code -- if it's 0, command worked,
                    // otherwise we need to start the browser up.
                    int exitCode = p.waitFor();
                    if (exitCode != 0){
                        // Command failed, start up the browser
                        // cmd = 'netscape http://www.javaworld.com'
                        cmd = UNIX_PATH + " "  + url;
                        p = Runtime.getRuntime().exec(cmd);
                    }
                }
                catch(InterruptedException x){
                    System.err.println("Error bringing up browser, cmd='" +cmd + "'");
                    System.err.println("Caught: " + x);
                }
            }
        }
        catch(IOException x){
            // couldn't exec browser
            System.err.println("Could not invoke browser, command=" + cmd);
            System.err.println("Caught: " + x);
        }
    }
    /**
     * Try to determine whether this application is running under Windows
     * or some other platform by examing the "os.name" property.
     *
     * @return true if this application is running under a Windows OS
     */
    public static boolean isWindowsPlatform(){

        String os = System.getProperty("os.name");
        if ( os != null && os.startsWith(WIN_ID))
            return true;
        else
            return false;
    }
    /**
     * Simple example.
     */
    public static void main(String[] args){
        displayURL("http://www.javaworld.com");
    }
    // Used to identify the windows platform.
    private static final String WIN_ID = "Windows";
    // The default system browser under windows.
    private static final String WIN_PATH = "rundll32";
    // The flag to display a url.
    private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
    // The default browser under unix.
    private static final String UNIX_PATH = "netscape";
    // The flag to display a url.
    private static final String UNIX_FLAG = "-remote openURL";
0
 
LVL 1

Expert Comment

by:mikal_sk
Comment Utility
Hi again ive just tested this solution, it works for me.

init the class like this

// Abselute path to file
 public static void main(String[] args){
        displayURL("C://JAVA//Courses//LANGUAGE//WJ2751.pdf");
    }

make sure you have adobe reader innstalled :)


BR
Mike
0
 
LVL 8

Expert Comment

by:hiteshgupta1
Comment Utility
this article illustrates dat how to open a non HTML document from a servlet

http://www.javaworld.com/javaworld/javatips/jw-javatip94.html
0
 
LVL 1

Author Comment

by:sree032397
Comment Utility
No, I dont want to open it in External Application,
It should be displayed in a Java UI
0
 
LVL 8

Expert Comment

by:kaliyugkaarjun
Comment Utility
Try:

Runtime.exec("adobe.exe", new String[] { "paper1.pdf" });

or u can try this

Process theProcess =
Runtime.getRuntime().exec("/Program Files/Adobe/Acrobat7.0/Reader/AcroRd32.exe C:\\filename.pdf");

You need to pass the absolute pathway for the executable and the file being read.

if you are reading in a file from a file chooser you can also do the following

Process theProcess = Runtime.getRuntime().exec("/Program Files/Adobe/Acrobat7.0/Reader/AcroRd32.exe "+chooser.getSelectedFile().getPath());

hope this helps

Chk this site..they r saying some of their components r helpful for pdf display in java UI
http://sourceforge.net/projects/xom/
0
 
LVL 1

Expert Comment

by:mikal_sk
Comment Utility

How do you want to display the PDF file : applet, Swing, Servlet

Also check out this tool, should also give you the opportunity to edit the documents:
http://www.lowagie.com/iText/

BR
Mike
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 1

Author Comment

by:sree032397
Comment Utility
I want to display it using Swing
0
 
LVL 1

Accepted Solution

by:
mikal_sk earned 168 total points
Comment Utility
Then you should be looking for a printing API:
http://schmidt.devlib.org/java/libraries-pdf.html

I would recommend taking a look at "Adobe Acrobat Reader for Java", since it is freeware.
You should find plenty of coding examples in each link.

I have not tried any of these myself, but I know iText is very popular.
http://www.lowagie.com/iText/

hope this helps
0
 
LVL 8

Assisted Solution

by:kaliyugkaarjun
kaliyugkaarjun earned 166 total points
Comment Utility
0
 

Assisted Solution

by:ObiRenoKenobi
ObiRenoKenobi earned 166 total points
Comment Utility
I also recommend to use iText. I've used it before to write and read PDF documents and works very well. I think that displaying it in a Swing component without an external API, is very difficult and time consuming... but yes, is possible.
0
 
LVL 1

Author Comment

by:sree032397
Comment Utility

I Downloaded iText. But how to use iText for displaying PDF FIles in a swing component.

I downloaded acrobat.jar from ADobe Acrobat to display PDF Files. But when I tried to use it in a class file it giving an exception which I copied below :

Exception in thread "main" java.lang.NoClassDefFoundError: com/apple/mrj/MRJAbou
tHandler
        at PDFViewer.viewPDFDocument(PDFViewer.java:17)
        at PDFViewer.main(PDFViewer.java:69)
Press any key to continue...

Please help me in this regard
0
 

Expert Comment

by:ObiRenoKenobi
Comment Utility
Well, you just make sure you have the API in your classpath before executing it, or if you're executing in another machine, make sure that the API is in the package you're distributing.
0
 
LVL 1

Expert Comment

by:mikal_sk
Comment Utility
Had a closer look at PDF viewer it seems to be deprecated and havent really been maintained by Adobe.

Please have a look at this one :
http://www.jpedal.org

Looks good. You have to download a JAR file and follow the tutorials.

BR
Mike
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mapShare challenge 13 68
Path of Workbook 3 44
recursion example 16 68
parse convert xml feed to text (python) 2 28
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
The viewer will learn how to implement Singleton Design Pattern in Java.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now