以下程序实现了读取某个路径下的pdf文件,并用浏览器打开:
package test
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.OutputStream
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
public class PDFServlet extends HttpServlet {
private static final long serialVersionUID = -3065671125866266804L
public PDFServlet() {
super()
}
public void destroy() {
super.destroy()
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/pdf")
FileInputStream in = new FileInputStream(new File("d:/1.pdf"))
OutputStream out = response.getOutputStream()
byte[] b = new byte[512]
while ((in.read(b)) != -1) {
out.write(b)
}
out.flush()
in.close()
out.close()
}
public void init() throws ServletException {
}
}
如果你希望直接打印,这办法基本不可行了。
不过你可以过渡一下,这样的话,有两种不同的方法:
1. 你的链接可以直接链接到PDF文件,URL可以写成类似:“http://www.xx.com/mypdf.pdf”,这样办的话,如果用户安装了PDF的浏览器支持,打开后用户的浏览器可以直接在浏览器中运行adobe reader。然后由用户选择是否打印。
2. 如果你感觉上面的方法不合理,你也可以学习百度文库的做法,使用flash制作一个PDF阅读器,这样,你可以在flash上面加上打印按钮,这样的方法与上面大同小异,却不用考虑用户是否已经安装了adobe reader。
以上是两种不同的实现方案,第一种很简单,但对于没有安装adobe reader的用户,会相当影响用户体验。可是第二种,实现的技术却很高,需要很强的actionsctript的开发能力,我也无能为力,至少现在是这个样子的。
直接使用js打开一个PDF文件,我觉得无法实现。