使用Flying Saucer的HTML到PDF:在PDF页面中显示内部CSS

时间:2015-04-21 21:25:21

标签: java servlets web-applications itext flying-saucer

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();
        }

当显示pdf css正常工作并显示灰色背景时会发生什么,但是,它会显示以下文本:@page {background-color:#f0f0f0;} Hello。如何让样式文本停止显示在pdf中?

1 个答案:

答案 0 :(得分:1)

如果替换:

@page {background-color: #f0f0f0;}

通过

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

然后<style>标记将识别该样式,但该样式不会“计数”为HTML,因为我们已将其置于注释中。