Convert HTML to PDF Using Java itextpdf

In this tutorial, we will introduce the way to convert html to a pdf file using java itextpdf.

1. Import packages

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.StringReader;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
import com.itextpdf.tool.xml.XMLWorkerHelper;

2. Create an empty pdf file

FileOutputStream file=new FileOutputStream(new File("output1.pdf"));
Document document=new Document();
PdfWriter writer=PdfWriter.getInstance(document, file);
document.open();

3. Add html content to pdf file

String k="<html><body>Cocyer.com</body></html>";
ByteArrayInputStream is=new ByteArrayInputStream(k.getBytes());
((com.itextpdf.tool.xml.XMLWorkerHelper) XMLWorkerHelper).getInstance().parseXHtml(writer,document,is);
document.close();
file.close();

Then we will convert html to pdf file.

Here is the full example code.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.StringReader;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class NewClass1 {
  private static Object XMLWorkerHelper;
    public static void main(String args[]){
    try {
      String k="<html><body>Cocyer.com</body></html>";
      FileOutputStream file=new FileOutputStream(new File("output1.pdf"));
      Document document=new Document();
      PdfWriter writer=PdfWriter.getInstance(document, file);
      document.open();
      ByteArrayInputStream is=new ByteArrayInputStream(k.getBytes());
      ((com.itextpdf.tool.xml.XMLWorkerHelper) XMLWorkerHelper).getInstance().parseXHtml(writer,document,is);
      document.close();
      file.close();
      System.out.println("done");
    }catch(Exception e) {
      e.printStackTrace();
    }
      
    }
}