我正在使用Java中的iText庫生成PDF文件。這個想法是,用戶填寫一些信息,當用戶點擊生成按鈕時,pdf將顯示在瀏覽器的新選項卡中。現在我偶然發現了一些這樣做的問題,它們是: - URL沒有改變,所以不是/application/user.pdf我得到了/application/dashboard.xhtml - 我可以將pdf文件保存在除瀏覽器外的所有瀏覽器中爲Chrome。iText生成的PDF在Chrome中未正確顯示
請注意,我不想將它保存在光盤上,只需在瀏覽器中顯示PDF,以便用戶可以選擇是否要保存它。
這裏是我使用生成我的PDF代碼:
public static void createPdf(User user, byte languageNumber, HttpServletResponse response) {
Document document = new Document();
try {
/* PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("c://" + user.getUsername() + "_" + languageCode + ".pdf"));*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.addTitle("Your CV");
document.addSubject("This is your CV");
document.addKeywords("CV");
document.addAuthor(user.getUsername());
document.open();
document.add(
new Paragraph(user.getPersonalInformation().getFirstname() + " " + user.getPersonalInformation().getLastname()));
document.close();
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
response.setContentLength(baos.size());
//ServletOutputStream out = response.getOutputStream();
OutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
* 這個方法是一個按鈕後面我的JSF頁面上*
public String exportPdf() {
user = userService.retrieveLoginUser();
FacesContext context = FacesContext.getCurrentInstance();
try {
Object response = context.getExternalContext().getResponse();
if (response instanceof HttpServletResponse) {
HttpServletResponse hsr = (HttpServletResponse) response;
PdfCreator.createPdf(user, selectLanguage, hsr);
//Tell JSF to skip the remaining phases of the lifecycle
context.responseComplete();
}
return "../" + user.getUsername() + ".pdf";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
使用的技術: - JSF 2.0 - Facelets - iText
在此先感謝:D
也許它可能需要您設置MIME內容? 「application/pdf」,如果我記得正確... – SJuan76 2011-05-22 18:49:58
你有沒有設置內容處置:內聯? – MJB 2011-05-22 19:05:14