简体   繁体   English

使用飞碟将HTML转换为PDF:PDF页面中显示内部CSS

[英]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. 当它显示pdf时,css可以正常工作并显示灰色背景,但是会显示以下文本:@page {background-color:#f0f0f0;}您好。 How do I get the styling text to stop showing up in the pdf? 如何获取样式文本以使其停止显示在pdf中?

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. 那么<style>标记将识别该样式,但是该样式不会“计数”为HTML,因为我们已将其放入注释中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM