itextsharp add 1 page template to all pages

萝らか妹 提交于 2019-12-10 19:33:08

问题


I'm creating a PDF file dynamically in an ASP.Net application. The data can vary from spanning 1 page to over 10 pages. I'm using PdpfTables and Cells to align the data which is working perfectly. IT's creating pages as it needs new pages. The only problem is I can't get it to add my template to all pages, only the first page.

My Template is a 1 page PDF file. To add it to the first page I'm using the following code

PdfContentByte cb = writer.DirectContent;
cb.AddTemplate(page, 0, 0);

As I said, this works for the first page fine but not any pages after that. So I tried adding the following code just before I close all the streams, but it does nothing

for (var i = 2; i <= writer.CurrentPageNumber; i++)
{
    var y = (writer.PageSize.Height * (i - 1));
    cb.AddTemplate(page, 0, y);
}

I've not really found anything on the net relating to my problem exactly, but those issues that are out there which are similar didn't help.

Any advice would be great, thanks.


回答1:


If you want something to happen on each page, you should use page events and act in case of an OnEndPage call. The Webified iTextSharp Example Stationery.cs shows how to do that. It essentially post-initializes the PdfWriter to use an inner helper class as page event listener and retrieves the background:

PdfWriter writer = PdfWriter.GetInstance(document, ms);
[...]
writer.PageEvent = new TemplateHelper(this);
PdfReader reader = new PdfReader(stationary);
page = writer.GetImportedPage(reader, 1);

page is a member variable:

private PdfImportedPage page;

It is used by the TemplateHelper inner helper class:

class TemplateHelper : PdfPageEventHelper {
  private Stationery instance;
  public TemplateHelper() { }
  public TemplateHelper(Stationery instance) { 
    this.instance = instance;
  }
  /**
   * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
   *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
   */
  public override void OnEndPage(PdfWriter writer, Document document) {
    writer.DirectContentUnder.AddTemplate(instance.page, 0, 0);
  }
}


来源:https://stackoverflow.com/questions/16917433/itextsharp-add-1-page-template-to-all-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!