how to open a pdf file from java?

前端 未结 2 829
小鲜肉
小鲜肉 2021-01-24 21:26

I want to open a PDF file from a jsp. The jsp and the PDF are in the same directory. I am using the following piece of code:

if (Desktop.isSupported()) {
    try         


        
相关标签:
2条回答
  • 2021-01-24 22:04

    Have you tried this? I just got this from google, so I dunno if it will work.

    Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:\\Java-    Interview.pdf");
            p.waitFor();
    
    0 讨论(0)
  • 2021-01-24 22:25

    You need to specify the absolute file path. Assuming that there's a filename.pdf in the root of the public webcontent, this should do:

    File myFile = new File(getServletContext().getRealPath("/filename.pdf"));
    

    However, this construct won't work the way you'd expect. It will show the PDF file in webserver machine, not in webbrowser machine! Only when you happen to run both the webserver and webbrowser at physically the same machine, this will "work". But this does obviously not happen in real world when you publish your webapp into the internet where the webserver and webbrowser runs at physically different machines.

    Instead, you just need to link to the PDF file directly.

    <a href="filename.pdf">View PDF</a>
    

    and let the browser handle the display.

    0 讨论(0)
提交回复
热议问题