DaNet
DaNet

Reputation: 438

Using PdfStamper to add a rectangle

Hi I have a pdf I created using itextsharp.

Using pdfreader I am reading the created pdf into a pdfstamper.

Now I am trying to use the pdfstamper to add a black rectangle the size of the page on all pages. How do i do this?

Also I cannot use document to add the rectangle because the stream is close!

    MemoryStream stream = new MemoryStream();

    PdfReader pdfReader = new PdfReader(output.ToArray());
    PdfStamper stamper = new PdfStamper(pdfReader, stream);

    for (int x = 0; x < stamper.Reader.NumberOfPages; x++)
    {
        Rectangle rectangle = document.PageSize;
        rectangle.BackgroundColor = new BaseColor(0, 0, 0);
        //stamper.Writer.AcroForm.
        //document.Add(rectangle);
    }

    output.Close();
    pdfReader.Close();
    stamper.Close();

Upvotes: 2

Views: 17249

Answers (1)

Chris Haas
Chris Haas

Reputation: 55417

If you want to draw using the PdfStamper then you need to use the PdfContentByte which you can get by calling stamper.GetOverContent(pageNum). There's a specific command on that object called Rectangle which does exactly what you want it to do. Also, remember that pages within a PDF start numbering at one and not zero.

Below is a full working C# 2010 WinForm app targeting iTextSharp 5.1.1.0 that should do what you're looking for, I think. You'll need to modify it to support the MemoryStream but that should be pretty easy.

using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "input.pdf");
            string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.pdf");

            PdfReader pdfReader = new PdfReader(inputFile);
            using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(pdfReader, fs))
                {
                    int PageCount = pdfReader.NumberOfPages;
                    for (int x = 1; x <= PageCount; x++)
                    {
                        PdfContentByte cb = stamper.GetOverContent(x);
                        iTextSharp.text.Rectangle rectangle = pdfReader.GetPageSizeWithRotation(x);
                        rectangle.BackgroundColor = BaseColor.BLACK;
                        cb.Rectangle(rectangle);
                    }
                }
            }

            this.Close();
        }
    }
}

Upvotes: 5

Related Questions