简体   繁体   English

如何为iText生成的PDF显示“另存为”对话框?

[英]How to show a Save As dialog for a iText generated PDF?

I want to show a Save As dialog when I send the PDF file which is generated by iText in a servlet. 当我发送由iText在servlet中生成的PDF文件时,我想显示一个“ 另存为”对话框。 How can I achieve this? 我该如何实现?

You need to let the servlet set the Content-Disposition header to attachment . 您需要让servlet将Content-Disposition标头设置为attachment

response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

This will force a Save As dialogue where the enduser can choose the location. 这将强制执行“ 另存为”对话框,最终用户可以在其中选择位置。

Please keep in mind that the enduser might have changed its browser settings to take a default action on PDF files, for example to always show it in Reader or to always save it in some fixed location. 请记住,最终用户可能已经改变了其浏览器设置采取PDF文件的默认动作,例如一直显示它Reader或总是将其保存在某个固定位置。 In for example Firefox you can control this by Tools > Options > Applications . 例如,在Firefox中,您可以通过“ 工具”>“选项”>“应用程序”来控制它。 No, you cannot change this browser specific behaviour from the server side on. 不可以,您不能从服务器端更改此浏览器特定的行为。

Ok I solved my problem!! 好吧,我解决了我的问题! I found on this page : http://www.geek-tutorials.com/java/itext/servlet_jsp_output_pdf.php 我在此页面上找到: http : //www.geek-tutorials.com/java/itext/servlet_jsp_output_pdf.php

The method is to write directly with getOutputStream() (not in file path) and send content type header! 方法是直接使用getOutputStream()编写(不在文件路径中)并发送内容类型标头!

response.setContentType("application/pdf");
Document document = new Document();
try{
    PdfWriter.getInstance(document, 
    response.getOutputStream());
    //pdf generate code

It was so simple... 太简单了...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM