Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlUnit and saving page as PDF

In the Java EE environment, I want to load an XML and XSL file, render the output to a browser window, and save the rendered page as PDF.

I would like to do it all programmatically. I was looking at HtmlUnit to use as a headless browser. That part seems to work, but does HtmlUnit have any API to invoke a "print" function or similar function to persisted the rendered output? I was thinking of some way to link it in with iText.

like image 368
OldProgrammer Avatar asked Apr 22 '26 21:04

OldProgrammer


1 Answers

I would recommend trying out flying-saucer which in this case basically is a CSS/XHTML enabled iText wrapper.

I wrote a simple example below. Don't forget the necessary dependencies for HtmlUnit and flying-saucer.

//Set up a new WebClient using your favourite settings
WebClient webClient = new WebClient();

//Fetch page
HtmlPage page = webClient.getPage("url-to-target.resource");

//Set PDF target output file
String outputFile = "firstdoc.pdf";
OutputStream os = new FileOutputStream(outputFile);

//Set up flying-saucer IText based renderer 
ITextRenderer renderer = new ITextRenderer();

//Create PDF
renderer.setDocumentFromString(page.asXml();
renderer.layout();
renderer.createPDF(os);

os.close();
like image 63
OakNinja Avatar answered Apr 28 '26 06:04

OakNinja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!