Search code examples
javaservletsweb-applicationsitextflying-saucer

HTML to PDF using Flying Saucer: Internal CSS showing in PDF page


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    try {
        StringBuffer buffer = new StringBuffer();
        buffer.append("<html>");
        buffer.append("<head>");
        buffer.append("<style type='text/css'>");
        buffer.append("@page {background-color: #f0f0f0;}");
        buffer.append("</style>");
        buffer.append("</head>");
        buffer.append("<body>");
        buffer.append("<h2>Hello</h2>");
        buffer.append("</body>");
        buffer.append("</html>");
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.parse(new StringBufferInputStream(buffer.toString()));
        OutputStream os = response.getOutputStream();

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(doc, null);
        renderer.layout();
        renderer.createPDF(os);

        os.close();
        }

What happens when it displays the pdf the css works correctly and displays a gray background, however, it displays the following text:@page {background-color: #f0f0f0;}Hello. How do I get the styling text to stop showing up in the pdf?


Solution

  • If you replace:

    @page {background-color: #f0f0f0;}
    

    by

    <!--
        @page {background-color: #f0f0f0;}
    -->
    

    then the <style> tag will recognize the style, but the style won't "count" as HTML because we've put it inside a comment.