Itextsharp为所有pdf页面添加边框

时间:2017-04-12 05:02:03

标签: c# pdf itext

我正在以PDF格式添加大表(PDF格式约4至5页)。 我使用下面的代码在PDF中添加Big table(大约4到5页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,因此可能无法实现事件监听器。

更新 我的类定义如下:(是否可以覆盖Page Event(onEndPage))

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

1 个答案:

答案 0 :(得分: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

相关问题