为什么不在java servlet中创建pdf文档? [英] Why doesn'n create pdf-documents in java servlet?

查看:97
本文介绍了为什么不在java servlet中创建pdf文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用iText / Pdfbox创建PDF文档。当我使用像这样的独立Java类创建PDF时,一切正常:

I use iText/Pdfbox to create a PDF document. Everything works when I create the PDF using a standalone Java class like this:

public static void main(String[] args){
...
...
...
}

文档已正确创建。

但我需要从Servlet创建PDF文档。我将代码粘贴到get或post方法中,在服务器上运行该servlet,但未创建PDF文档!

But I need create a PDF document from a Servlet. I paste the code into the get or post method, run that servlet on the server, but the PDF document isn't created!

此代码作为独立应用程序运行:

This code works as a standalone application:

此代码不起作用:

推荐答案

请阅读文档。例如,问题的答案如何在不在服务器端存储文件的情况下将PDF提供给浏览器?

Please read the documentation. For instance the answer to the question How can I serve a PDF to a browser without storing a file on the server side?

您当前正在文件系统上创建文件。您没有使用响应对象,这意味着您没有向浏览器发送任何字节。这解释了为什么浏览器中没有任何反应。

You are currently creating a file on your file system. You aren't using the response object, meaning you aren't sending any bytes to the browser. This explains why nothing happens in the browser.

这是一个简单的例子:

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 在内存中创建文件更安全,并告诉浏览器在内容标题中可以预期多少字节:

However, some browsers experience problems when you send bytes directly like this. It's safer to create the file in memory using a ByteArrayOutputStream and to tell the browser how many bytes it can expect in the content header:

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/

For the full source code, see PdfServlet. You can try the code here: http://demo.itextsupport.com/book/

您在评论中写道


此演示将PDF文件写入浏览器。我想将PDF保存在硬盘上。

This demo writes the PDF file into the browser. I want to save the PDF on my hard drive.

这个问题可以通过两种不同的方式解释:

This question could be interpreted in two different ways:


  1. 您希望将文件写入用户磁盘驱动器上的特定目录,而无需任何用户交互。这是禁止!如果服务器可以强制将文件写入用户磁盘驱动器的任何位置,那将是一个严重的安全隐患。

  2. 您想要显示一个对话框,以便用户可以保存PDF在他选择的目录中的磁盘驱动器上,而不是仅在浏览器中显示PDF。在这种情况下,请仔细查看文档。你会看到这一行: response.setHeader(Content-disposition,attachment; filename =+testPDF.pdf); 你可以设置内容处置内联如果你想在浏览器中打开PDF,但在问题中,内容处置设置为附件,触发一个对话框打开。

  1. You want to write the file to a specific directory on the user's disk drive without any user interaction. This is forbidden! It would be a serious security hazard if a server could force a file to be written anywhere on a user's disk drive.
  2. You want to show a dialog box so that the user can save the PDF on his disk drive in a directory of his choice instead of just showing the PDF in the browser. In this case, please take a closer look at the documentation. You'll see this line: response.setHeader("Content-disposition","attachment;filename="+ "testPDF.pdf"); You can set the Content-disposition to inline if you want the PDF to open in the browser, but in the question, the Content-disposition is set to attachment which triggers a dialog box to open.

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

这篇关于为什么不在java servlet中创建pdf文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆