iText - 无需 PDF 文件即可即时生成文件 [英] iText - generating files on the fly without needing a PDF file

查看:30
本文介绍了iText - 无需 PDF 文件即可即时生成文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 iText 生成 pdf 文件,但我对生成有疑问.我想将 PDF 提供给浏览器,以便浏览器显示它,而无需实际创建文件.

实现这一目标的最佳方法是什么?

一个限制是我需要从 JSP 页面使用它 - 我正在寻找可以规避getOutputStream 已经被调用一次"错误的东西.

解决方案

我想将 PDF 提供给浏览器,以便浏览器显示它,而无需实际创建文件.

只需将 responsegetOutputStream() 而不是 new FileOutputStream 传递给 PdfWriter.

PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());//...

<小时><块引用>

一个限制是我需要从 JSP 页面使用它 - 我正在寻找可以绕过getOutputStream has been called once"错误的东西.

只需删除 JSP 中 <% %> 之外的任何空格,包括换行符.它们由响应编写者隐式发送到响应.

即不要

<% page import="foo" %><% page import="bar" %><%for (int i = 0; i <1000; i++) {out.println("我不应该使用scriptlets.");}%>(此处换行)

但更是如此

<% page import="foo" %><% page import="bar" %><%for (int i = 0; i <1000; i++) {out.println("我应该使用servlets.");}%>

或者更好的是,不要将 Java 代码放在 JSP 文件中.JSP 文件旨在呈现像 HTML 一样的模板文本,而不是做完全不同的事情.在像 servlet 这样的普通 Java 类中执行此操作.

I am trying to use iText for pdf file generation and I have a question regarding the generation. I would like to serve the PDF to the browser so that the browser displays it, without actually creating a file.

What would be the best approach to achieve this?

One limitation is that I would need to use it from a JSP page - something that would circumvent the "getOutputStream has already been called once" error is what I am looking for.

解决方案

I would like to serve the PDF to the browser so that the browser displays it, without actually creating a file.

Just pass responsegetOutputStream() instead of new FileOutputStream to PdfWriter.

PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());
// ...


One limitation is that I would need to use it from a JSP page - something that would circumvent the "getOutputStream has already been called once" error is what I am looking for.

Just remove any whitespace outside <% %> in JSP, including newlines. They are implicitly sent to the response by the response writer.

I.e. do NOT

<% page import="foo" %>
<% page import="bar" %>

<%
   for (int i = 0; i < 1000; i++) {
       out.println("I should not use scriptlets.");
   }
%>

(newline here)

but more so

<% page import="foo" %><% page import="bar" %><%
   for (int i = 0; i < 1000; i++) {
       out.println("I should use servlets.");
   }
%>

Or better, don't put Java code in JSP files. JSP files are designed to present template text like HTML, not to do entirely different things. Do that in a normal Java class like a servlet.

这篇关于iText - 无需 PDF 文件即可即时生成文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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