How to export html page to pdf format?

html, java, pdf

Solution

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:

- core-renderer.jar

- iText-2.0.8.jar

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:

- core-renderer.jar

- itextpdf-5.2.1.jar

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." );

Problem

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?

Original source

Related problems