如何从Java打开pdf文件? [英] how to open a pdf file from java?

查看:830
本文介绍了如何从Java打开pdf文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从jsp中打开PDF文件. jsp和PDF在同一目录中. 我正在使用以下代码:

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 {
        File myFile = new File("<file name>.pdf");
        Desktop.getDesktop().open(myFile);
    } catch (IOException ex) {
        // no application registered for PDFs
    }
}

但是,我收到未找到文件的错误. 验证过的user.dir,它指向我的tomcat/bin. 如何参考pdf来打开它?

However, I get the error that the file is not found. Verified user.dir and it points to my tomcat/bin. How can I refer to the pdf to open it?

推荐答案

您需要指定绝对文件路径.假设公共网站内容的根目录中有一个filename.pdf,则应该这样做:

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"));

但是,此构造无法按您期望的方式工作.它将在Web服务器计算机中显示PDF文件,而不在Web浏览器计算机中显示PDF文件!仅当您碰巧同时在同一台计算机上运行网络服务器和网络浏览器时,这才起作用".但是,当您将Web应用程序发布到Internet上时,在现实世界中这显然不会发生,在Web应用程序中,Web服务器和Web浏览器在物理上不同的计算机上运行.

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.

相反,您只需要直接链接到PDF文件即可.

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

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

并让浏览器处理显示.

这篇关于如何从Java打开pdf文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆