Friday 12 August 2016

Generating the Pdf from HTML

Generating PDF from PDF template is a time & memory consuming process. It's sometime not feasible to use it while processing larger data set.

One of the very good features of creating PDF using HTML is appropriate and simple to use and easy to maintain.

There are many libraries are available for reference  PDF library link 

I will be discuss here itextpdf library of creation as it is simple and easy to maintain. For the Maven based project pom entry :

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->    
<dependency>
    &lt;d&gt;<groupid>com.itextpdf</groupid>
    <artifactid>itextpdf</artifactid>
    <version>5.5.9</version>
</dependency>
   
 

Following is the code snippet to use for conversion of html into pdf :
import com.itextpdf.text.Document;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
@SuppressWarnings("deprecation")
public static void createPDFUsingHtml(String htmlFilePath,String outputPDFFilePath){
try {
Document document = new Document();
OutputStream file = new FileOutputStream(outputPDFFilePath);
PdfWriter writer = PdfWriter.getInstance(document,file );
///if want to keep password encrypted then add password here else passwordless pdf will be created
writer.setEncryption("".getBytes(), "".getBytes(),PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
String htmlcontent = readFile(htmlFilePath);
htmlWorker.parse(new StringReader(htmlcontent));
document.close();
} catch (Exception e)
{
e.printStackTrace();
}
}

When run a main  program on the html  test.html


   
public static void main(String[] args){
createPDFUsingHtml("/Users/test/test.html", "/Users/test/test.pdf");
}

Output of the created pdf : test.pdf

Your PDF is ready with a very  simple way and doesn't require any extra effort of creation of the pdf template. Instead just make a simple HTML  template which can be created from any online tool .
Just make your html ready and then your PDF will be created immediately.

Enjoy Coding !!!!



No comments:

Post a Comment