开发者

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? I'm generating the PDF file from scratch, so I don't need to add borders to 开发者_Python百科an already existing document.

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#. 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.

You'll probably want a PdfPageEventHelper-derived class that does its drawing in the onEndPage event.

You can query the current page size via the document parameter's getPageSize(), and use that (tweaked a bit) to draw your borders. Given that you're using iTextSharp, you probably have a PageSize property instead of a "get" method.

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. 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

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜