2016-08-24 85 views
0

我打算通過使用iTextSharp的創建發票頂部的HTML表格,裏面我的發票,它由3個部分,它們在頁面的頂部iTextSharp的 - 重複在每一頁上

  1. 表(包括所有的供應商信息)
  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(); 

但我不知道如何在每個頁面上插入表格。我打算使用html表格,因爲它需要控制很多東西,比如不同的供應商,地址,顯示/隱藏或取消的圖像。請幫忙。

回答

1

您的問題已被詢問過。請參閱官方文檔中的How to add HTML headers and footers to a page?,或在StackOverflow上查看How to add HTML headers and footers to a page?

Roman Sidorov的回答是錯誤的,因爲Roman假定您從代碼中觸發NewPage()。這並非總是如此。您將一張表添加到Document,並且該表跨越多個頁面。這意味着iText會在內部觸發NewPage()函數。

您可以使用頁面事件將內容添加到創建的每個頁面。在執行NewPage()操作之前觸發OnEndPage()事件。這是當你添加額外的內容到當前頁面。執行NewPage()操作後立即觸發OnStartPage()事件。禁止在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?的回答中有解釋。官方文檔的page events部分中還有許多其他示例。

+0

感謝您的回答@Bruno Lowagie我想用HTML來做標題,因爲裏面的表包含許多信息,如字體樣式,圖像,地址,電話等等。對於我而言,如果不使用html表格,將所有信息排列在標題內對我來說是一項相當大的挑戰。或者你有任何教程/設計頭的解決方案?感謝您再次回答 – 120196

+0

不要期望XML Worker以與HTML中定義的方式完全相同的方式呈現表格。您似乎正在使用iTextSharp 5.在這種情況下,您可以閱讀「iText in Action - 第二版」。但最新版本是iText 7,以及如何使用iText 7在這裏解釋:[iText 7:構建塊](http://developers.itextpdf.com/content/itext-7-building-blocks/)。 iText 5和iText 7之間有很大的區別。 –

+0

Hi @Bruno Lowagie,對不起,我是新手編程,請問實現iText 7和iTextSharp 5一樣嗎?只需將該dll添加到Visual Studio中作爲參考?謝謝 – 120196