更新时间:2023-01-30 17:36:23
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." );