【发布时间】:2011-08-20 16:16:04
【问题描述】:
我在尝试使用 iText 创建 PDF 文件并想在之后立即下载时遇到问题。首先,我使用 iText 库创建了一个 PDF 文件,该文件被写入服务器上的 TEMP 文件夹,一切正常。但之后我调用了一个下载屏幕,将 TEMP 文件夹中的 PDF 文件下载到客户端,这里出现了问题。下载屏幕显示 Firefox(浏览器)图标而不是 Acrobat 图标。当我下载文件时,我只能看到空白的 PDF 页面,但页数是正确的。例如。我有一个 4 页的 PDF 文件,结果我得到 4 个空白页,没有内容。但是 TEMP 文件夹中的 PDF 文件是正确的,它有 4 页内容正确。
这是我的java代码,当用户点击h:commandLink时执行
public <E> String createPDF(E type, boolean print) throws Exception {
Document document = new Document();
// create a File name for the document
getPdfNaam(type);
try {
//create a PDF writer
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(TEMP + naam + ".pdf"));
//open the PDF document
document.open();
} catch (Exception e) {
e.printStackTrace();
}
//build the PDF file using iText
buildPDFContent(document, type);
//close the PDF document
close(document);
String downloadFile = TEMP + naam + ".pdf";
//call Servlet for download screen in the browser
ServletContext context = (ServletContext) ContextProvider.getFacesContext().getExternalContext().getContext();
HttpServletResponse response = (HttpServletResponse) ContextProvider.getFacesContext().getExternalContext().getResponse();
response.setContentType("application/force-download");
downloadFile = TEMP + naam + ".pdf";
byte[] buf = new byte[1024];
try {
File file = new File(downloadFile);
long length = file.length();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
ServletOutputStream out = response.getOutputStream();
response.setContentLength((int) length);
while ((in != null) && ((length = in.read(buf)) != -1)) {
out.write(buf, 0, (int) length);
}
in.close();
out.close();
} catch (Exception exc) {
exc.printStackTrace();
}
response.addHeader("Content-Disposition", "attachment; filename=\"" + naam + ".pdf" + "\"");
return null;
}
我在这个网站上找到了调用下载屏幕的代码http://www.winstonprakash.com/articles/jsf/file_download_link.htm 我在 Google 和 Stack Overflow 上搜索,但找不到任何相关问题。我正在使用 JSF 2.0 任何帮助将不胜感激!
【问题讨论】: