how to generate pdf from xhtml page dynamically using itext+flying saucer with java

mdp picture mdp · Oct 15, 2012 · Viewed 10.1k times · Source

I am using iText+flying saucer for the first time with xhtml pages using JSF 2.0 for simple registration form with regular input fields like firstName,lastName,phone number etc.Once user enters all the data and click on "NEXT" button I have to convert this XHTML page with User data into pdf.How can i exactly get the source HTML of this page with all the styles included in the page and convert it to pdf.Currently I am tying like this.

public void createPDF() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpSession session = (HttpSession) externalContext.getSession(true);
    String url = "http://localhost:8080/MyPROJECT/faces/page1.xhtml;JSESSIONID=" + session.getId();
    try {
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(url);
    renderer.layout();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    response.reset();
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition","C://user//first.pdf");
    OutputStream browserStream = response.getOutputStream();
    renderer.createPDF(browserStream);
    browserStream.close();
    session.invalidate();
    } catch (Exception ex) {
       ex.printStackTrace();
    }
    facesContext.responseComplete();
}

But it's throwing me this exception.

ERROR:  'The string "--" is not permitted within comments.'
org.xhtmlrenderer.util.XRRuntimeException: Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException: The string "--" is not permitted within comments.

Is this the right way to get my page using above URL.Does that URL get my page with User Data on click of NEXT Button and convert it pdf or am I trying with wrong code.Please help me. Examples appreciated.

Answer

ollo picture ollo · Oct 15, 2012

This exceptions sounds more like a problem in the (x)html of your website. Is there something like <!-- some -- comments --> in your html?

Flying Saucer throws this exception because there's a -- somewhere in a comment block. Check this up and if possible try it without -- between <!-- and -->.

However, since FS will fail on every little misstake in (X)HTML / XML (as noted in the readme), its often a good idea to use a HTML Cleaner before processing a website.

Here are two examples: