如何使用iTextSharp为页面添加边框

本文关键字:添加 边框 何使用 iTextSharp | 更新日期: 2023-09-27 17:58:59

是否可以使用iTextSharp为PDF文档中的页面添加边框?我从头开始生成PDF文件,所以我不需要为现有文档添加边框。

以下是我的代码示例:

Document pdfDocument = new Document(PageSize.LETTER);
Font headerFont = new Font(baseFont, 13);
Font font = new Font(baseFont, 10);
PdfWriter writer = PdfWriter.GetInstance(pdfDocument, 
                                         new FileStream(fileName, FileMode.Create));
pdfDocument.Open();
//I add IElements here.
pdfDocument.Close();

如何使用iTextSharp为页面添加边框

以下是C#中的一个答案(改编自Mark Storer)。这个例子使用页面的边距来绘制边框,我有时会发现这对调试页面布局很有用。

public override void OnEndPage(PdfWriter writer, Document document)
{
    base.OnEndPage(writer, document);
    var content = writer.DirectContent;
    var pageBorderRect = new Rectangle(document.PageSize);
    pageBorderRect.Left += document.LeftMargin;
    pageBorderRect.Right -= document.RightMargin;
    pageBorderRect.Top -= document.TopMargin;
    pageBorderRect.Bottom += document.BottomMargin;
    content.SetColorStroke(BaseColor.RED);
    content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);
    content.Stroke();
}

我建议您在生成当前页面时获取其直接内容,并使用PdfContentByte获取边框。

您可能需要一个PdfPageEventHelper派生的类,它在onEndPage事件中进行绘图。

您可以通过document参数的getPageSize()查询当前页面大小,并使用它(稍微调整一下)绘制边框。假设您使用的是iTextSharp,那么您可能有一个PageSize属性而不是"get"方法。

类似于:

public void onEndPage(PdfWriter writer, Document doc) {
  PdfContentByte content = writer.getDirectContent();
  Rectangle pageRect = doc.getPageSize();
  pageRect.setLeft( pageRect.getLeft() + 10 );
  pageRect.setRight( pageRect.getRight() - 10 );
  pageRect.setTop( pageRect.getTop() - 10 );
  pageRect.setBottom( pageRect.getBottom() + 10 );
  content.setColorStroke( Color.red );
  content.rectangle(pageRect.getLeft(), pageRect.getBottom(), pageRect.getWidth(), pageRect.getHeight());
  content.stroke();
}

请注意,您实际上可以将Rectangle传递到content.rectangle()中,此时该矩形的边界&使用填充设置。我觉得这可能有点令人困惑,所以没有这样编码。

PdfContentByte content = pdfwrite1.DirectContent;
            Rectangle rectangle = new Rectangle(doc.PageSize);
            rectangle.Left += doc.LeftMargin;
            rectangle.Right -= doc.RightMargin;
            rectangle.Top -= doc.TopMargin;
            rectangle.Bottom += doc.BottomMargin;
            content.SetColorStroke(BaseColor.BLACK);
            content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
            content.Stroke();

我能够为现有的PDF 添加红色边框

public void createPdf(PdfReader  pdfReader)
        throws DocumentException, IOException {
    String userDir = System.getProperty("user.dir");
    System.out.println("userDir = " + userDir);
    RESULT  = userDir + "/work/"+"sample.pdf";
    // step 1
    Document document = new Document();
    // step 2
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
    // step 3
    document.open();
    int noOfPages = pdfReader.getNumberOfPages();
    for (int page = 0; page < noOfPages; ) {
        if(page==0) {
            PdfImportedPage immportedPage = copy.getImportedPage(pdfReader, ++page);
            PageStamp stamp = copy.createPageStamp(immportedPage);
            PdfContentByte canvas = stamp.getOverContent();
            drawPageBorder(canvas, PageSize.A4.getWidth(), PageSize.A4.getHeight());
            stamp.alterContents();
            copy.addPage(immportedPage);
        } else {
            copy.addPage(copy.getImportedPage(pdfReader, ++page));
        }
    }
    copy.freeReader(pdfReader);
    pdfReader.close();
    // step 4
    document.close();
}
public void drawPageBorder(PdfContentByte content, float width, float height) {
    content.saveState();
    PdfGState state = new PdfGState();
    state.setFillOpacity(0.0f);
    content.setGState(state);
    content.setColorStroke(BaseColor.RED);
    content.setLineWidth(6);
    content.rectangle(5, 5, width, height);
    content.fillStroke();
    content.restoreState();
}
protected void GenerateReport(object sender, EventArgs e)
{
    Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
    Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
        Phrase phrase = null;
        PdfPCell cell = null;
        PdfPTable table = null;
 
        document.Open();
 
        //Header Table
        table = new PdfPTable(1);
        table.TotalWidth = 400f;
        table.LockedWidth = true;
        table.SetWidths(new float[] { 1f });
 
        //Company Name and Address
        phrase = new Phrase();
        phrase.Add(new Chunk("Microsoft Northwind Traders Company'n'n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.RED)));
        phrase.Add(new Chunk("107, Park site,'n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("Salt Lake Road,'n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("Seattle, USA", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
        cell.VerticalAlignment = PdfCell.ALIGN_TOP;
        table.AddCell(cell);
 
        document.Add(table);
 
        table = new PdfPTable(2);
        table.HorizontalAlignment = Element.ALIGN_LEFT;
        table.SetWidths(new float[] { 0.3f, 1f });
        table.SpacingBefore = 20f;
 
        //Employee Details
        cell = PhraseCell(new Phrase("Employee Record", FontFactory.GetFont("Arial", 12, Font.UNDERLINE, Color.BLACK)), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        table.AddCell(cell);
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 30f;
        table.AddCell(cell);
 
        table = new PdfPTable(2);
        table.SetWidths(new float[] { 0.5f, 2f });
        table.TotalWidth = 340f;
        table.LockedWidth = true;
        table.SpacingBefore = 20f;
        table.HorizontalAlignment = Element.ALIGN_RIGHT;
 
        phrase = new Phrase();
        phrase.Add(new Chunk("Mr. Mudassar Ahmed Khan'n", FontFactory.GetFont("Arial", 10, Font.BOLD, Color.BLACK)));
        phrase.Add(new Chunk("(Moderator)", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)));
        cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
        cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
        cell.Colspan = 2;
        table.AddCell(cell);
 
        cell = PhraseCell(new Phrase(" "), PdfPCell.ALIGN_LEFT);
        cell.Colspan = 2;
        table.AddCell(cell);
 
        //Employee Id
        table.AddCell(PhraseCell(new Phrase("Employee code:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        table.AddCell(PhraseCell(new Phrase("0001", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 10f;
        table.AddCell(cell);
 
 
        //Address
        table.AddCell(PhraseCell(new Phrase("Address:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        phrase = new Phrase(new Chunk("507 - 20th Ave. E.'nApt. 2A'n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("Seattle'n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("WA USA 98122", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        table.AddCell(PhraseCell(phrase, PdfPCell.ALIGN_LEFT));
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 10f;
        table.AddCell(cell);
 
        //Date of Birth
        table.AddCell(PhraseCell(new Phrase("Date of Birth:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        table.AddCell(PhraseCell(new Phrase("25 FEBRUARY", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 10f;
        table.AddCell(cell);
        document.Add(table);
 
        //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();
 
        document.Close();
        byte[] bytes = memoryStream.ToArray();
        memoryStream.Close();
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=Employee.pdf");
        Response.ContentType = "application/pdf";
        Response.Buffer = true;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(bytes);
        Response.End();
        Response.Close();
    }
}
 
private static PdfPCell PhraseCell(Phrase phrase, int align)
{
    PdfPCell cell = new PdfPCell(phrase);
    cell.BorderColor = Color.WHITE;
    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    return cell;
}