Question

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.

Was it helpful?

Solution

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:

OTHER TIPS

The other thing you can do if you have some partial control over the HTML and only need to escape certain items is follow the example in the java.net article to swap out undesirable elements by replacing them in ContentCaptureServletResponse:

public String getContent(){
    writer.flush();
    String xhtmlContent = new String(contentBuffer.toByteArray());
    xhtmlContent = xhtmlContent.replaceAll("<thead>|</thead>","");
    return xhtmlContent; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top