I’ve decided to start a new series of ‘quick tip’ posts. Each post will be short and focused on a particular problem, an interesting technique, or to improve your productivity.
What we want to do
A common requirement in web apps is the ability to generate a PDF file with dynamic content. There are libraries available that allow you to build the PDF using a low-level approach, step by step. However, a much simpler way that might work for you is to just use regular HTML pages and transform them into PDF. We’ll be using the great iTextPdf library.
How to do it
The first thing we need is the ability to convert Wicket Webpages, Panels, and Components into an HTML string. Fortunately, Wicket makes this very easy for us!
public static String renderPanelToString(Panel panel) {
CharSequence cs = ComponentRenderer.renderComponent(panel);
return cs != null ? cs.toString() : "";
}
public static String renderPageToString(PageProvider pp) {
CharSequence cs = ComponentRenderer.renderPage(pp);
return cs != null ? cs.toString() : "";
}
Using these utility methods we can now convert any WebPage or Panel into a string.
Now let’s create a service class that will utilize iTextPdf to convert HTML into PDF:
public class PdfService {
public void printUrlToPdf(String html, OutputStream output) {
try {
String xhtml = convertHtmlToXHTML(html);
Document document = new Document(PageSize.LETTER.rotate());
PdfWriter writer = PdfWriter.getInstance(document, output);
writer.setInitialLeading(12.5f);
document.open();
document.newPage();
Paragraph p1 = new Paragraph();
ElementList list = XMLWorkerHelper.parseToElementList(xhtml, null);
p1.addAll(list);
document.add(p1);
document.close();
} catch (Exception e) {
}
}
private String convertHtmlToXHTML(String input) {
org.jsoup.nodes.Document d = Jsoup.parse(input, "US-ASCII");
d.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
return d.html();
}
}
You’ll notice that we first have to convert the HTML into strict XHTML for this to work. This is meant as a simple starting example, but you may need to do further transformations of your HTML in order for it to look good inside of the PDF. You may need to transform some tags such as spans and header tags into divs.
How to use it
Now let’s look at how to actually use our PdfService class. We create a resource stream that will be attached to the current request cycle and when the user navigates to this page, they will be prompted to download the PDF as file named “export.pdf”.
public class PrintPdfTestPage extends WebPage {
@SpringBean private PdfService pdfService;
public PrintPdfTestPage() throws IOException {
super();
try (AbstractResourceStreamWriter resourceStream = new AbstractResourceStreamWriter() {
@Override
public void write(OutputStream output) {
String html = UIHelpers.renderPageToString(new PageProvider(PageSizeTest2.class, new PageParameters()));
pdfService.printUrlToPdf(html, output);
}
}) {
RequestCycle.get().scheduleRequestHandlerAfterCurrent(
new ResourceStreamRequestHandler(resourceStream).setFileName("export.pdf").setContentDisposition(ContentDisposition.ATTACHMENT));
}
}
}
You can also generate the PDF in response to a button click using the technique discussed here.
download = new AJAXDownload() {
@Override
public void onRequest() {
try (AbstractResourceStreamWriter resourceStream = new AbstractResourceStreamWriter() {
@Override
public void write(OutputStream output) {
String html = UIHelpers.renderPageToString(new PageProvider(PageSizeTest2.class, new PageParameters()));
pdfService.printUrlToPdf(html, output);
}
}) {
getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(
new ResourceStreamRequestHandler(resourceStream).setFileName("export.pdf").setContentDisposition(ContentDisposition.ATTACHMENT));
} catch (IOException e) {
}
}
};
testForm.add(new SingleClickAjaxButton("singleClickBtn", testForm, true, null) {
@Override
protected void onSubmit(AjaxRequestTarget target) {
download.initiate(target);
}
}.add(download));
Conclusion
I hope this is enough to get you started. There are a lot of other cools things you can do with iTextPdf.
- Add custom CSS files
- Add watermark images to each page
- Create PDF’s from merging several Wicket pages or panels together
You can find the full source on GitHub.