简体   繁体   English

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

[英]How do I add a border to a page using iTextSharp?

Is it possible to add a border to a page in a PDF document using iTextSharp ?是否可以使用iTextSharp为 PDF 文档中的页面添加边框? I'm generating the PDF file from scratch, so I don't need to add borders to an already existing document.我正在从头开始生成 PDF 文件,因此我不需要为已经存在的文档添加边框。

Here's my code for example:例如,这是我的代码:

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();

Here is an answer (adapted from Mark Storer) in C#.这是 C# 中的答案(改编自 Mark Storer)。 This example uses the margins of the page to draw the border, which I sometimes find useful for debugging the page layout.此示例使用页面的边距来绘制边框,有时我发现这对调试页面布局很有用。

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();
}

I suggest you get the current page's direct content as you generate it, and your border with PdfContentByte .我建议您在生成当前页面时获取当前页面的直接内容,并使用PdfContentByte进行边框。

You'll probably want a PdfPageEventHelper -derived class that does its drawing in the onEndPage event.您可能需要一个PdfPageEventHelper派生的 class 来在 onEndPage 事件中进行绘图。

You can query the current page size via the document parameter's getPageSize() , and use that (tweaked a bit) to draw your borders.您可以通过document参数的getPageSize()查询当前页面大小,并使用它(稍微调整一下)来绘制边框。 Given that you're using iTextSharp, you probably have a PageSize property instead of a "get" method.鉴于您使用的是 iTextSharp,您可能有一个PageSize属性而不是“get”方法。

Something like:就像是:

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();
}

Note that you can actually pass a Rectangle into content.rectangle() , at which point that rectangle's border & fill settings are used.请注意,您实际上可以将Rectangle传递给content.rectangle() ,此时使用该矩形的边框和填充设置。 I figured that might be a little confusing, so didn't code it that way.我认为这可能有点令人困惑,所以没有这样编码。

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();

I was able to do add red border to an existing PDF我能够为现有的 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM