iText - generating files on the fly without needing a PDF file

后端 未结 3 579
半阙折子戏
半阙折子戏 2020-12-04 00:15

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

相关标签:
3条回答
  • 2020-12-04 00:55

    Write it to the servlet output stream, remembering to set the encoding to the correct value

    0 讨论(0)
  • 2020-12-04 01:00

    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.

    0 讨论(0)
  • 2020-12-04 01:02

    This http://onjava.com/onjava/2003/06/18/dynamic_files.html explains how to do it

    0 讨论(0)
提交回复
热议问题