所以我刚刚听说过名为 iText 的 API,但我不太熟悉它的使用。
所以我现在的问题是我想在现有的pdf文件(模板)上写入jsp表单中提供的信息。 我尝试了一些在互联网上找到的代码,它工作正常,但不适用于 servlet。 谢谢。
编辑这是我找到并尝试放入 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();
}
}
最佳答案
我查看了您的 servlet,发现:
new FileOutputStream(new File("test.pdf"))
这意味着您正在将文件写入服务器上的文件系统。我没有看到您向 response
对象发送任何字节,因此浏览器中没有显示任何内容。
您声称 iText“在 servlet 中不起作用”,但这是不正确的:如果没有引发异常,则会在服务器端的工作目录中创建一个名为“test.pdf”的文件。这不是很聪明,因为使用您的 servlet 的人越多,服务器上保存的 PDF 就越多。你可能不想要这样。您可能希望在内存中创建 PDF,并将 PDF 字节提供给浏览器。
对您问题的简短回答是,您应该将 PDF 写入 response
对象的 OutputStream
,而不是写入 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”,您将找到以下常见问题解答条目:
- How can I serve a PDF to a browser without storing a file on the server side? (iText 5)
- How can I serve a PDF to a browser without storing a file on the server side? (iText 7)
由于您是 iText 的新手,因此您选择使用 iText 5 而不是较新的 iText 7 感到很惊讶。iText 7 与 iText 5 不兼容;它是对库的完全重写。我建议您使用 iText 7,因为我们已经停止了 iText 5 的积极开发。
更新:
称为“文档没有页面”的错误。表示您正在尝试创建一个没有任何内容的文档。
替换:
String content = request.getParameter("aa");
Paragraph paragraph = new Paragraph(content);
document.add(paragraph);
与:
document.add(new Paragraph("Hello"));
我的猜测是,在获取参数“aa”
时出现问题,导致没有内容添加到文档中。
关于java - 使用 servlet 重写 pdf 文件(模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348533/