I have to offer some export functions to my website such as CSV or PDF. Is there a powerful and free tool for Java to convert HTML pages to PDF format?
Chrome has a built-in PDF viewer and can open the PDF files. When Chrome is selected as the PDF viewer, the PDF files will change to Chrome HTML.
Using Flying Saucer API
with iText PDF
you can convert HTML content to PDF.
Following examples help you in understanding, to some extent, conversion of XHTML to PDF.
Examples Using Flying Saucer API:
You require following libraries:
You can find these resources in flyingsaucer-R8.zip
.
Example1: Using XML Resource:
// if you have html source in hand, use it to generate document object
Document document = XMLResource.load( new ByteArrayInputStream( yourXhtmlContentAsString.getBytes() ) ).getDocument();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument( document, null );
renderer.layout();
String fileNameWithPath = outputFileFolder + "PDF-XhtmlRendered.pdf";
FileOutputStream fos = new FileOutputStream( fileNameWithPath );
renderer.createPDF( fos );
fos.close();
System.out.println( "File 1: '" + fileNameWithPath + "' created." );
Example2: Using XHTML direct input to Document:
ITextRenderer renderer = new ITextRenderer();
// if you have html source in hand, use it to generate document object
renderer.setDocumentFromString( yourXhtmlContentAsString );
renderer.layout();
String fileNameWithPath = outputFileFolder + "PDF-FromHtmlString.pdf";
FileOutputStream fos = new FileOutputStream( fileNameWithPath );
renderer.createPDF( fos );
fos.close();
System.out.println( "File 2: '" + fileNameWithPath + "' created." );
Examples Using iText API:
You require following libraries:
You can find these resources at here.
Example3: Using HTML Worker:
com.itextpdf.text.Document document =
new com.itextpdf.text.Document( com.itextpdf.text.PageSize.A4 );
String fileNameWithPath = outputFileFolder + "PDF-HtmlWorkerParsed.pdf";
FileOutputStream fos = new FileOutputStream( fileNameWithPath );
com.itextpdf.text.pdf.PdfWriter pdfWriter =
com.itextpdf.text.pdf.PdfWriter.getInstance( document, fos );
document.open();
//**********************************************************
// if required, you can add document meta data
document.addAuthor( "Ravinder" );
//document.addCreator( creator );
document.addSubject( "HtmlWoker Parsed Pdf from iText" );
document.addCreationDate();
document.addTitle( "HtmlWoker Parsed Pdf from iText" );
//**********************************************************/
com.itextpdf.text.html.simpleparser.HTMLWorker htmlWorker =
new com.itextpdf.text.html.simpleparser.HTMLWorker( document );
htmlWorker.parse( new StringReader( sb.toString() ) );
document.close();
fos.close();
System.out.println( "File 3: '" + fileNameWithPath + "' created." );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With