How do I add a border to a page using iTextSharp?

2019-04-23 13:27发布

问题:

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

回答1:

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


回答2:

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.



回答3:

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