使用servlet写一个pdf文件(模板)

时间:2017-04-11 14:15:15

标签: java servlets java-ee itext

所以我刚刚听说过名为iText的API,我对它的使用并不熟悉。

所以我现在的问题是我想在现有的pdf文件(模板)上写一个jsp表单中提供的信息。 我尝试了一些在互联网上找到的代码,它工作正常,但不适用于servlet。 感谢。

EDIT 以下是我发现的代码,并尝试将其放入servlet中。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


            Document document = new Document(PageSize.A4);
            try {

                PdfWriter.getInstance(document, new FileOutputStream(new File(
                        "test.pdf")));
                document.open();
                String content = request.getParameter("aa");
                Paragraph paragraph = new Paragraph(content);
                document.add(paragraph);

            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                document.close();
            }
        }

1 个答案:

答案 0 :(得分:0)

我看着你的servlet,我看到了:

new FileOutputStream(new File("test.pdf"))

这意味着您正在将文件写入服务器上的文件系统。我没有看到您向response对象发送任何字节,因此浏览器中没有任何内容。

你声称iText"不能在servlet"中工作,但这不正确:如果没有抛出异常,那么文件名为" test.pdf&# 34;正在服务器端的工作目录中创建。这不是很聪明,因为越多人使用您的servlet,将在服务器上保存更多的PDF。你可能不想要那个。您可能希望在内存中创建PDF,并将PDF字节提供给浏览器。

对您的问题的简短回答是,您应该将PDF写入OutputStream对象的response而不是FileOutputStream

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());
        }
    }
}

但是,为避免此方法的已知问题,您还应阅读官方文档。搜索关键字" servlet"并且您将找到这些常见问题条目:

由于您是iText的新手,因此您选择使用iText 5代替较新的iText 7令人惊讶.iText 7与iText 5不兼容;它是对图书馆的完全重写。我建议您使用iText 7,因为我们已停止在iText 5上进行主动开发。

<强>更新

错误称为&#34;文档没有页面。&#34;表示您正在尝试创建一个没有任何内容的文档。

替换:

String content = request.getParameter("aa");
Paragraph paragraph = new Paragraph(content);
document.add(paragraph);

使用:

document.add(new Paragraph("Hello"));

我的猜测是在获取参数"aa"时出现问题,导致没有内容添加到文档中。