How to convert a PDF generating in response.outputStream to a Base64 encoding

前端 未结 1 1120
情话喂你
情话喂你 2021-01-17 07:20

I am doing a project where i need to create a admit card for student who are appearing in examination. The pdf Generation part is working fine but my problem is i have to e

相关标签:
1条回答
  • 2021-01-17 07:59

    When I look at your code, I see:

    PdfWriter.getInstance(document,response.getOutputStream());
    

    Which means that you are instructing iText to write PDF bytes straight to the browser. This outputstream is closed at the moment you close the document.

    I also see:

    OutputStream responseOutputStream = response.getOutputStream();
    

    I even see that you try adding stuff to this stream. This is impossible as the stream is already closed.

    You need to create a ByteArrayOutputStream like this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    

    And use this in the PdfWriter:

    PdfWriter.getInstance(document, baos);
    

    Now you can get the PDF bytes like this:

    byte[] pdf = baos.toByteArray();
    

    Now you can encode these bytes and send them to the output stream.

    Encode:

    Assuming that you are using org.apache.commons.codec.binary.Base64 as explained in the answer to Base64 Encoding in Java, you can do this:

    byte[] base64 = Base64.encodeBase64(pdf);
    

    (There are other ways to do this.)

    Send to output stream:

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentType("application/pdf");
    response.setContentLength(base64.length);
    OutputStream os = response.getOutputStream();
    os.write(base64);
    os.flush();
    os.close();
    
    0 讨论(0)
提交回复
热议问题