2017-07-01 73 views
0

我將this java code轉換爲C#,但是我明顯錯過了一些東西,因爲頭文件不在我的.pdf文檔中。如何將iTextSharp的標題打印到.pdf文件中?

這裏的轉換代碼:

public HttpResponseMessage CreatePdf() 
     { 
      HeaderTable HeaderTable = new HeaderTable(); 
      // step 1 
      Document document = new Document(PageSize.A4, 36, 36, 20 + HeaderTable.getTableHeight(), 36); 
      // step 2 
      var memoryStream = new MemoryStream(); 
      PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); 
      writer.CloseStream = false; 

      writer.PageEvent = HeaderTable; 
      // step 3 
      document.Open(); 
      // step 4 
      for (int i = 0; (i< 50); i++) { 
       document.Add(new Paragraph("Hello World!")); 
      } 

      document.NewPage(); 
      document.Add(new Paragraph("Hello World!")); 
      document.NewPage(); 
      document.Add(new Paragraph("Hello World!")); 
      // step 5 
      document.Close(); 

      memoryStream.Seek(0, SeekOrigin.Begin); 

      return new HttpResponseMessage 
      { 
       Content = new StreamContent(memoryStream) 
       { 
        Headers = 
        { 
         ContentType = new MediaTypeHeaderValue("application/pdf"), 
         ContentDisposition = new ContentDispositionHeaderValue("attachment") 
         { 
          FileName = "TEST.pdf" 
         } 
        } 
       }, 
       StatusCode = HttpStatusCode.OK 
      }; 
     } 

     public class HeaderTable : PdfPageEventHelper 
     { 
      protected PdfPTable table; 

      protected float tableHeight; 

      public HeaderTable() 
      { 
       table = new PdfPTable(1); 
       table.TotalWidth = 523; 
       table.LockedWidth = true; 
       table.AddCell("Header row 1"); 
       table.AddCell("Header row 2"); 
       table.AddCell("Header row 3"); 
       tableHeight = table.TotalHeight; 
      } 

      public float getTableHeight() 
      { 
       return tableHeight; 
      } 

      public void onEndPage(PdfWriter writer, Document document) 
      { 
       table.WriteSelectedRows(0, -1, document.Left, (document.Top + ((document.TopMargin + tableHeight)/2)), writer.DirectContent); 
      } 
     } 

我敢肯定,我做了一個簡單的錯誤,但我沒有找到它呢。請幫忙。

回答

0

好吧,我想通了。 相反的:

public class HeaderTable : PdfPageEventHelper 

public void onEndPage(PdfWriter writer, Document document) 

我應該寫:

public partial class HeaderTable : PdfPageEventHelper 

public override void OnEndPage(PdfWriter writer, Document document) 
+0

'partial'不應該是必要的(除非您已拆分您的por中的HeaderTable定義t)中,重要的部分是*覆蓋*使用*正確的方法名稱*(在iTextSharp中,以大寫字母開頭的方法的.Net約定被遵循,在iText/Java中以小寫字母開頭的方法的Java約定)。 – mkl

相關問題