ketan sharma
ketan sharma

Reputation: 103

Save itext pdf as blob without physical existence.

I am using this code to generate PDF using iText. First it creates HTML to PDF after that it converts that PDF in byte array or in BLOB or in byte array. I dont want to create any physical stores of pdf on my server. First i want to convert HTML to blob of PDF using itext, And after that i want to store that blob in my DB(Stores in DB i will done).

          String userAccessToken=requests.getSession()
                    .getAttribute("access_token").toString();
          Document document = new Document(PageSize.LETTER);
          String name="/pdf/invoice.pdf";
          PdfWriter pdfWriter = PdfWriter.getInstance
               (document, new FileOutputStream(requests.getSession().getServletContext().getRealPath("")+"/assets"+name));
          document.open();
          document.addAuthor("Real Gagnon");
          document.addCreator("Real's HowTo");
          document.addSubject("Thanks for your support");
          document.addTitle("Please read this ");
          XMLWorkerHelper worker = XMLWorkerHelper.getInstance();

          //data is an html string 
          String str = data;
          worker.parseXHtml(pdfWriter, document, new StringReader(str));
          document.close();
          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
          PdfWriter.getInstance(document, byteArrayOutputStream);
          byte[] pdfBytes = byteArrayOutputStream.toByteArray();

          link=name;
          System.out.println("Byte array is "+pdfBytes);

PROBLEM:- Convert html to pdf BLOB using itext, Without physical existence of PDF.

Upvotes: 2

Views: 2962

Answers (2)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

The other answer to this question is almost correct, but not quite.

You can use any OutputStream when you create a PdfWriter. If you want to create a file entirely in memory, you can use a ByteArrayOutputStream like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, baos);
document.open();
// add stuff
document.close();
byte[] pdf = baos.toByteArray();

In short: you first create a ByteArrayOutputStream, you pass this OutputStream to the PdfWriter and after the document is closed, you can get the bytes from the OutputStream.

(In the other answer, there was no way to retrieve the bytes. Also: it is important that you don't try to retrieve the bytes before the document is closed.)

Upvotes: 2

fateddy
fateddy

Reputation: 7157

Write into a ByteArrayOutputStream (instead of a FileOutputStream):

PdfWriter pdfWriter = PdfWriter.getInstance
           (document, new ByteArrayOutputStream());

Upvotes: 0

Related Questions