JAVA: passing an input or output stream to ITextRenderer (xhtml to pdf converter)

mohammad picture mohammad · Mar 11, 2013 · Viewed 9.2k times · Source

I want to convert my XHTML text to a PDF. I converted it to FileOutputStream but I ca'nt find a way to pass it as an input to the ITextRenderer. Is that possible, and how?

the code :

String finalXhtml=xhtmlparser(xmlText);
ByteArrayInputStream finalXhtmlStream = new ByteArrayInputStream(finalXhtml.getBytes());

 String HTML_TO_PDF = "ConvertedFile.pdf";
 OutputStream os = new FileOutputStream(HTML_TO_PDF);       

  ITextRenderer renderer = new ITextRenderer();
      //   renderer.loadDocument(finalXhtmlStream);  i can pass a file here can i pass an input or output stream ?     
         renderer.layout();
         renderer.createPDF(os) ;    
         os.close();
   System.out.println("done.");

note: I can pass a file to the ITextRenderer as following:

 String File_To_Convert = "report.xhtml";
 String url = new File(File_To_Convert).toURI().toURL().toString();
 String HTML_TO_PDF = "ConvertedFile.pdf";
 OutputStream os = new FileOutputStream(HTML_TO_PDF);       

 ITextRenderer renderer = new ITextRenderer();
     renderer.setDocument(url);      
     renderer.layout();
     renderer.createPDF(os);
 os.close();
   System.out.println("done.");

please let me know if I have to provide more details.

Answer

shrey picture shrey · Dec 30, 2013

I am using following code to export HTML data to PDF with following code:

renderer.setDocumentFromString(htmls.toString());
renderer.layout();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + ".pdf\"");
renderer.createPDF(outputStream);
renderer.createPDF(fos);

Now here I am using inline CSS to generate PDF using style but is there any option that I can use setDocumentFromString() function by loading external CSS.