使用Java在iTextPDF中将html内容设置为页眉和页脚

时间:2015-02-02 11:46:33

标签: java itext html-to-pdf itextpdf

在我的应用程序中,我从html内容生成报告。为此,我使用带有XMLWorker 5.5.0的iTextPDF库5.5.0。最终用户可以使用tinyMC编辑器设计报告的内容(页眉,页脚,主题)。我将这些HTML内容存储在DB中。请注意,此HTML内容可能包含图像,表格或tinyMC允许的任何内容。现在,当用户尝试生成报告时,我从数据库中获取数据,并尝试使用下面给出的代码从HTML生成页眉和页脚。

       /**
         * Adds the header and the footer.
         * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
         *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
         */
        public void onEndPage(PdfWriter writer, Document document) {
            Phrase footerPhrase = new Phrase();

            DBFooter = "<table width='200 border='1' cellpadding='1' cellspacing='1'><tbody><tr><td>content1</td><td>content2</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td>
            </tr><tr><td>jhvhjvh</td><td><img src='D:\DemoApp\images\User1.png' width='48' height='48' alt='' /></td></tr></tbody></table>
            <p style='text-align: center;'>This is the footer</p>"

            CSSResolver cssResolver = new StyleAttrCSSResolver();
            CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS.getBytes()));
            cssResolver.addCss(cssFile);

            // HTML
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

            // Pipelines
            ElementList elements = new ElementList();
            ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
            HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
            CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

            // XML Worker
            XMLWorker worker = new XMLWorker(css, true);
            XMLParser p = new XMLParser(worker);
            try {
                p.parse(new ByteArrayInputStream(DBFooter.toString().getBytes()));
            } catch (IOException e) {
            }
            footerPhrase.addAll(elements);

            Rectangle rect = writer.getBoxSize("art");
            switch (writer.getPageNumber() % 2) {
            case 0:
                ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, header[0], rect.getRight(),
                                           rect.getTop(), 0);
                break;
            case 1:
                ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, header[1], rect.getLeft(),
                                           rect.getTop(), 0);
                break;
            }

            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, footerPhrase,
                                       (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 50, 0);
        }

我已跟随this link添加页眉页脚。并按上述方式更改了onEndPage函数。

问题是上面的代码只打印&#34; 这是页脚&#34;从页脚的内容。它没有显示表格。如何在页眉/页脚中添加HTML内容。

请注意,我可以在报告正文中显示html内容(包括表/图像等),但不能在页眉/页脚中显示。

1 个答案:

答案 0 :(得分:0)

使用itext sharp xml worker的页面事件和元素处理程序管理在C#中添加html页眉和页脚

    /// <summary>
    /// returns pdf in bytes.
    /// </summary>
    /// <param name="contentsHtml">contents.</param>
    /// <param name="headerHtml">header contents.</param>
    /// <param name="footerHtml">footer contents.</param>
    /// <returns></returns>
    public Byte[] GetPDF(string contentsHtml, string headerHtml, string footerHtml)
    {
        // Create a byte array that will eventually hold our final PDF
        Byte[] bytes;

        // Boilerplate iTextSharp setup here

        // Create a stream that we can write to, in this case a MemoryStream
        using (var ms = new MemoryStream())
        {
            // Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
            using (var document = new Document(PageSize.A4, 40, 40, 120, 120))
            {
                // Create a writer that's bound to our PDF abstraction and our stream
                using (var writer = PdfWriter.GetInstance(document, ms))
                {
                    // Open the document for writing
                    document.Open();

                    var headerElements = new HtmlElementHandler();
                    var footerElements = new HtmlElementHandler();

                    XMLWorkerHelper.GetInstance().ParseXHtml(headerElements, new StringReader(headerHtml));

                    XMLWorkerHelper.GetInstance().ParseXHtml(footerElements, new StringReader(footerHtml));

                    writer.PageEvent = new HeaderFooter(headerElements.GetElements(), footerElements.GetElements());

                    // Read your html by database or file here and store it into finalHtml e.g. a string
                    // XMLWorker also reads from a TextReader and not directly from a string
                    using (var srHtml = new StringReader(contentsHtml))
                    {
                        // Parse the HTML
                        iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, srHtml);
                    }

                    document.Close();
                }
            }

            // After all of the PDF "stuff" above is done and closed but **before** we
            // close the MemoryStream, grab all of the active bytes from the stream
            bytes = ms.ToArray();
        }
        return bytes;
    }
}

页面事件和元素处理程序代码在这里

public partial class HeaderFooter : PdfPageEventHelper
{
    private ElementList HeaderElements { get; set; }
    private ElementList FooterElements { get; set; }

    public HeaderFooter(ElementList headerElements, ElementList footerElements)
    {
        HeaderElements = headerElements;
        FooterElements = footerElements;
    }

    public override void OnEndPage(PdfWriter writer, Document document)
    {
        base.OnEndPage(writer, document);
        try
        {
            ColumnText headerText = new ColumnText(writer.DirectContent);
            foreach (IElement e in HeaderElements)
            {
                headerText.AddElement(e);
            }
            headerText.SetSimpleColumn(document.Left, document.Top, document.Right, document.GetTop(-100), 10, Element.ALIGN_MIDDLE);
            headerText.Go();

            ColumnText footerText = new ColumnText(writer.DirectContent);
            foreach (IElement e in FooterElements)
            {
                footerText.AddElement(e);
            }
            footerText.SetSimpleColumn(document.Left, document.GetBottom(-100), document.Right, document.GetBottom(-40), 10, Element.ALIGN_MIDDLE);
            footerText.Go();
        }
        catch (DocumentException de)
        {
            throw new Exception(de.Message);
        }
    }
}

public class HtmlElementHandler : IElementHandler
{
    public ElementList Elements { get; set; }

    public HtmlElementHandler()
    {
        Elements = new ElementList();
    }

    public ElementList GetElements()
    {
        return Elements;
    }

    public void Add(IWritable w)
    {
        if (w is WritableElement)
        {
            foreach (IElement e in ((WritableElement)w).Elements())
            {
                Elements.Add(e);
            }
        }
    }
}