请阅读文档。比如How can I serve a PDF to a browser without storing a file on the server side?问题的答案
您当前正在文件系统上创建一个文件。您没有使用 response 对象,这意味着您没有向浏览器发送任何字节。这就解释了为什么浏览器中什么也没有发生。
这是一个简单的例子:
public class Hello extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/pdf");
try {
// step 1
Document document = new Document();
// step 2
PdfWriter.getInstance(document, response.getOutputStream());
// step 3
document.open();
// step 4
document.add(new Paragraph("Hello World"));
document.add(new Paragraph(new Date().toString()));
// step 5
document.close();
} catch (DocumentException de) {
throw new IOException(de.getMessage());
}
}
}
但是,当您像这样直接发送字节时,某些浏览器会遇到问题。使用ByteArrayOutputStream 在内存中创建文件并告诉浏览器它可以在内容头中预期多少字节会更安全:
public class PdfServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// Get the text that will be added to the PDF
String text = request.getParameter("text");
if (text == null || text.trim().length() == 0) {
text = "You didn't enter any text.";
}
// step 1
Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// step 3
document.open();
// step 4
document.add(new Paragraph(String.format(
"You have submitted the following text using the %s method:",
request.getMethod())));
document.add(new Paragraph(text));
// step 5
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");
// the contentlength
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
}
catch(DocumentException e) {
throw new IOException(e.getMessage());
}
}
}
完整源代码见PdfServlet。你可以在这里试试代码:http://demo.itextsupport.com/book/
你在评论中写道
此演示将 PDF 文件写入浏览器。我想将 PDF 保存在我的硬盘上。
这个问题可以用两种不同的方式来解释:
- 您希望将文件写入用户磁盘驱动器上的特定目录,而无需任何用户交互。这是禁止!如果服务器可以强制将文件写入用户磁盘驱动器的任何位置,这将是一个严重的安全隐患。
- 您希望显示一个对话框,以便用户可以将其磁盘驱动器上的 PDF 保存在他选择的目录中,而不仅仅是在浏览器中显示 PDF。在这种情况下,请仔细查看文档。您将看到这一行:
response.setHeader("Content-disposition","attachment;filename="+ "testPDF.pdf"); 如果您希望 PDF 在浏览器中打开,您可以将 Content-disposition 设置为 inline,但在问题中,Content-disposition 设置为 attachment,这会触发对话框打开。
另见How to show a Save As dialog for a iText generated PDF?