2017-04-12 192 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

其添加到最后一页 –