【发布时间】:2012-10-03 12:54:09
【问题描述】:
我研究了几种在 iframe 中打印 pdf 的选项,但似乎都没有。
简单细节:
- 我从用户那里获得了一些搜索参数。
- 我进行数据库搜索,然后使用 Apachi FOP 生成结果的 PDF。
- 它们被定向到具有打印和取消按钮的网页。
- 当用户单击“打印”按钮时,将打开一个显示 PDF 的窗口。
- 将打开一个打印对话框供用户打印 PDF。
- PDF 文件已从服务器中删除。
- 窗户关闭
高级细节:
- 这只需要在 IE8 上运行。
- FOP 集成不使用任何 XSLT 转换。它仅使用格式化为字符串的输入 FOP XML 的 StringReader
- 显示 PDF 的窗口实际上是两个 JSP 页面。
- 首页:
- 具有以第二个 JSP 页面作为源的 iframe
- 在加载时运行 printPDF() 函数,在 iframe 中打印 PDF
- 第二页:
- 使用 Java BufferedOutputStream 和 ServletOutputStream
- 输出后会删除文件
- 使用 out = pageContent.pushBody();
这是第一个jsp页面的一部分(调用打印函数的运行):
<body onload='printPDF()'>
<table>
<tr>
<td class="content">
<%
// get myfilename from the myfile parameter on the URL
String myfile = request.getParameter("myfile");
out.print("<iframe src='fc_view_letter.jsp?myfile="+ myfile + "' id='pdfFrame'></iframe>");
%>
</td>
</tr>
</table>
<script>
function printPDF()
{
var id = 'pdfFrame';
var iframe = document.frames ? document.frames[0] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printPage();
//ifWin.print();
}
</script>
</body>
这是第二个 JSP 页面的大部分内容(显示 pdf 的页面):
<%@ page session="false" %>
<%@ page import="java.io.*" %>
<%@ page import="java.net.URLDecoder" %>
<html>
<head>
</head>
<body>
<%
String myfile = request.getParameter("myfile");
String myfiledecoded = "";
myfiledecoded = URLDecoder.decode(myfile, "UTF8");
String myfilename = myfiledecoded;
String extension;
int dotPos = myfilename.lastIndexOf(".")+1;
extension = myfilename.substring(dotPos);
int slashPos = myfilename.lastIndexOf("/")+1;
String secondparam = "filename=" + myfiledecoded.substring(slashPos);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", secondparam);
try {
ServletOutputStream sout = response.getOutputStream();
response.setHeader("Content-Disposition", secondparam);
File file = new File(myfilename);
FileInputStream fstream = new FileInputStream(file);
BufferedInputStream bis = null;
bis = new BufferedInputStream(fstream);
BufferedOutputStream bos = null;
bos = new BufferedOutputStream(sout);
byte[] buff = new byte[1024];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
sout.flush();
sout.close();
//file.delete();
}
catch (Exception e) {
System.out.println("Exception Occured...................." );
}
out.clear();
out = pageContext.pushBody();
%>
</body>
</html>
我认为的问题是: 我认为缓冲区消除了所有的 html,只显示 PDF。或者至少它在 IE 中做到了这一点。当我查看 Firefox 时,它嵌入了 PDF 文件。也许我无法获取 iframe 的内容,因为它不再是 HTML。
到目前为止,这是我的资料来源:
Javascript Print iframe contents only
How to open print dialog after pdf generated?
http://www.ehow.com/how_7352227_use-javascript-print-pdf.html
http://www.webmasterworld.com/forum91/4086.htm
how to print pdf inside embed/iframe using javascript
Printing contents of a dynamically created iframe from parent window
【问题讨论】:
-
如果有人知道如何将 javascript 事件添加到 FOP XML,我愿意将 onload 打印事件添加到 FOP XML。
标签: jsp pdf printing apache-fop