2017-04-12 106 views
0

我在PDF中添加了Big table(大約覆蓋4到5頁的pdf)。 我正在使用下面的代碼在PDF中添加大表(大約覆蓋4到5頁的pdf)。 (代碼工作正常)Itextsharp將邊框添加到所有pdf頁面

private static String CreateTableDocument() 
    { 

     Document document = new Document(PageSize.A4, 0, 0, 50, 50); 


     PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("D:\\ttt.pdf", FileMode.Create)); 
     document.Open(); 

     PdfContentByte cb = writer.DirectContent; 
      // GetTable("1") is my custom method that will return big table that cover 4 to 5 pages -- no problem here - 
     document.Add(GetTable("1")); 

     document.Close(); 
     return ""; 
    } 

上面的代碼生成PDF成功,現在我想添加邊界到所有生成的頁面。 我搜索並發現它可能使用PdfContentByteRectangle,但它沒有添加邊界到所有頁面或可能是我缺少的東西。

其他選項可能使用PageEvent但我使用的是WEB API,因此可能無法實現事件偵聽器。

UPDATE: 我的類定義是象下面這樣:(是否有可能重寫頁面事件(的OnEndPage))

public class PDFTaskController : ApiController 
{ 
// here my all pdf task related methods i.e. CreateTableDocument() 
} 
+0

無論何時您想以類似的方式對所有生成的頁面*執行某些操作*,您通常會使用頁面事件(更確切地說是它們的「onEndPage」)。你已經閱讀過使用'PdfContentByte'方法。 – mkl

+0

是的。但我正在使用WEB API,因此無法重寫onEndPage。 –

+1

爲什麼WEB API會阻止使用'onEndPage'?這聽起來很荒謬。你甚至嘗試過使用頁面事件嗎? –

回答

0

如果你不能擁有的OnEndPage,你可以試試下面的代碼:

//Add border to page 
    PdfContentByte content = writer.DirectContent; 
    Rectangle rectangle = new Rectangle(document.PageSize); 
    rectangle.Left += document.LeftMargin; 
    rectangle.Right -= document.RightMargin; 
    rectangle.Top -= document.TopMargin; 
    rectangle.Bottom += document.BottomMargin; 
    content.SetColorStroke(Color.BLACK); 
    content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height); 
    content.Stroke(); 

根據this

+0

我不認爲它會爲所有頁面添加邊框。 –

+0

你試過了嗎?請讓我知道結果。 – 2017-04-12 06:39:16

+0

其添加到最後一頁 –