iTextsharp - 在每个页面顶部重复 html table

iTextsharp - Repeat a html table on top of every page

我计划使用 iTextsharp 创建发票,在我的发票中,它由 3 个部分组成,它们是

  1. table 在页面顶部(包括所有供应商信息)
  2. gridview(购买项目)
  3. 签名部分(仅在发票的最后一页)

到目前为止,我使用 Pdfptable + splitlate

完成了 gridview 部分
       PdfPTable table = new PdfPTable(gv.Columns.Count);
       table.AddCell(new PdfPCell(new Phrase(cellText, fontH1)));
       ...
       ...
        //create PDF document
        Document pdfDoc = new Document(PageSize.A4, -30, -30, 15f, 15f);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        pdfDoc.Add(table);
        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;" + "filename=GridViewExport.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();

但我不知道如何在每一页上插入 table。我打算使用 html table 因为它需要控制很多东西,比如差异供应商、地址、show/hide 或取消的图像。请帮忙。

你的问题之前有人问过。请参阅 Whosebug 上的 How to add HTML headers and footers to a page? in the official documentation, or take a look at

Roman Sidorov 的回答是错误的,因为 Roman 假定您从代码中触发 NewPage()。这并不总是正确的。您将 table 添加到 Document,并且 table 跨越多个页面。这意味着 iText 在内部触发 NewPage() 函数。

您可以使用页面事件向创建的每个页面添加内容。 OnEndPage() 事件在执行 NewPage() 操作之前触发。这是您向当前页面添加额外内容的时候。 OnStartPage() 事件在执行 NewPage() 操作后立即触发。 OnStartPage()事件中禁止添加内容。参见 iTextSharp - Header and Footer for all pages

这是 Java 中的页面事件实现示例:

public class HeaderFooter extends PdfPageEventHelper {
    protected ElementList header;
    protected ElementList footer;
    public HeaderFooter() throws IOException {
        header = XMLWorkerHelper.parseToElementList(HEADER, null);
        footer = XMLWorkerHelper.parseToElementList(FOOTER, null);
    }
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            ColumnText ct = new ColumnText(writer.getDirectContent());
            ct.setSimpleColumn(new Rectangle(36, 832, 559, 810));
            for (Element e : header) {
                ct.addElement(e);
            }
            ct.go();
            ct.setSimpleColumn(new Rectangle(36, 10, 559, 32));
            for (Element e : footer) {
                ct.addElement(e);
            }
            ct.go();
        } catch (DocumentException de) {
            throw new ExceptionConverter(de);
        }
    }
}

您可以轻松地将其移植到 C#。我使用这个答案是因为它是对字面问题的字面答案。但是:为什么要在 HTML 中定义页眉(或页脚)。这没有意义,是吗?

为什么不创建一个 PdfPTable 并将其添加到页面事件中的每个页面。这在官方文档的问题 How to add a table as a header? There are many other examples in the page events 部分的答案中进行了解释。