Wednesday, March 26, 2014

How to generate styled PDF in Liferay PrimeFaces Portlet with iText

In the previous post,
How to generate PDF in Liferay PrimeFaces Portlet with iText shows how to generate a PDF document, unfortunately, the generated PDF is not able to handle style class.

eg,
<!DOCTYPE HTML><html><body>Generate <strong>PDF</strong> Test</body></html>
can be generated without any problem. 

but, 
<!DOCTYPE HTML><html><body>Generate <span style='color: red;'>PDF</span> Test</body></html>
is unable to generate the text with red color.

To be able to generate PDF with advanced/complex style, we have to use HTMLWorker instead of ITextReader.

and replace the getPdfStream() method with the below new getPdfStream() method in step 1.
public byte[] getPdfStream() {

    byte[] pdf = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String html = "<!DOCTYPE HTML><html><body>Generate <span style='color: red;'>PDF</span> Test</body></html>";
 try {   
  Document document = new Document(PageSize.A4);
  PdfWriter writer = PdfWriter.getInstance(document, baos); 

  document.open();  

  HTMLWorker htmlWorker = new HTMLWorker(document); 
  htmlWorker.parse(new StringReader(html));

  document.close();
 } catch(Exception e) {
  e.printStackTrace();
 }
 return baos.toByteArray();
}


Done!!


No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...