java - How to get the OutputStream of a written PDF from iText -


i need in getting , storing written pdf itext in outputstream , convert inputstream.

the code of writing pdf below:

public void  createpdf() throws ioexception {       try{         document doc = new document(pagesize.a4, 50, 50, 50, 50);         outputstream out = new bytearrayoutputstream();                     pdfwriter writer = pdfwriter.getinstance(doc, out);          doc.open();         pdfptable table = new pdfptable(1);         pdfpcell cell = new pdfpcell(new phrase("first pdf"));         cell.setborder(rectangle.no_border);         cell.setrundirection(pdfwriter.run_direction_ltr);         table.addcell(cell);         doc.add(table);         doc.close();        }         catch (exception e) {           e.printstacktrace();                 }     }  

so seeking write pdf in outputstream , convert inputstream.

i need inputstream value can pass line file download:

streamedcontent file = new defaultstreamedcontent(inputstream, "application/pdf", "xxx.pdf"); 

updated jon answer:

public inputstream createpdf1() throws ioexception {     document doc = new document(pagesize.a4, 50, 50, 50, 50);     try {              bytearrayoutputstream out = new bytearrayoutputstream();                     pdfwriter writer;             try {                 writer = pdfwriter.getinstance(doc, out);             } catch (documentexception e) {             }             doc.open();         pdfptable table = new pdfptable(1);         pdfpcell cell = new pdfpcell(new phrase("first pdf"));         cell.setborder(rectangle.no_border);         cell.setrundirection(pdfwriter.run_direction_ltr);         table.addcell(cell);         doc.add(table);          }         catch ( exception e)         {         e.printstacktrace();         }     return new bytearrayinputstream(out.tobytearray()); } 

you should change declaration of out of type bytearrayoutputstream rather outputstream. can call bytearrayoutputstream.tobytearray() bytes, , construct bytearrayinputstream wrapping that.

as aside, wouldn't catch exception that, , i'd use try-with-resources statement close document, assuming implements autocloseable. it's idea follow java naming conventions. example, might have:

public inputstream createpdf() throws ioexception {     bytearrayoutputstream out = new bytearrayoutputstream();                 try (document doc = new document(pagesize.a4, 50, 50, 50, 50)) {         pdfwriter writer = pdfwriter.getinstance(doc, out);         doc.open();         pdfptable table = new pdfptable(1);         pdfpcell cell = new pdfpcell(new phrase("first pdf"));         cell.setborder(rectangle.no_border);         cell.setrundirection(pdfwriter.run_direction_ltr);         table.addcell(cell);         doc.add(table);     }     return new bytearrayinputstream(out.tobytearray()); } 

Comments