我正在jsf / primefaces应用程序中使用itext生成多个pdf文件。有些文件可以正确生成,而另一些则不能。 经过调试后,我发现特定的代码行会导致此问题。
当我打电话
writer.setPageEvent(new Footer(image));
其中writer是PdfWriter类型。我收到这些错误:
[org.primefaces.application.exceptionhandler.PrimeExceptionHandler] (default task-96) Could not handle exception!: java.lang.IllegalStateException: UT010006: Cannot call getWriter(), getOutputStream() already called
我立即获得Pdf Writer的使用权,我使用以下代码行:
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might
// have set some headers in the buffer beforehand.
// We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check
// http://www.iana.org/assignments/media-types
// for all types. Use if
// necessary
// ExternalContext#getMimeType()
// for auto-detection based on
// filename.
// ec.setResponseContentLength(contentLength); // Set it with the file
// size. This header is optional. It will work if it's omitted, but the
// download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above
// OutputStream the usual way.
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, output);
我还尝试使用HttpServletResponse代替:
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
OutputStream output = httpServletResponse.getOutputStream();
但是我遇到了同样的错误。
我该如何解决此问题并直接在PdfWriter中编写?还是在没有PdfWriter的情况下做同样的事情?