You can't read a file and write to it simultaneously. Think of how Word works: you can't open a Word document and write directly to it. Word always creates a temporary file, writes the changes to it, then replaces the original file with it and then throws away the temporary file.
You can do that too:
- read the original file with
PdfReader
,
- create a temporary file for
PdfStamper
, and when you're done,
- replace the original file with the temporary file.
Or:
- read the original file into a
byte[]
,
- create
PdfReader
with this byte[]
, and
- use the path to the original file for
PdfStamper
.
This second option is more dangerous, as you'll lose the original file if you do something that causes an exception in PdfStamper
.
As for adding content with PdfStamper
, please take a look at the section entitled "Manipulating existing PDFs" in the free ebook The Best iText Questions on StackOverflow. You'll find questions such as:
All of these examples add content by creating a PdfContentByte
instance like this:
PdfContentByte canvas = stamper.getOverContent(pagenumber);
It's this canvas
you need to use when drawing a circle on the page with page number pagenumber
. It is important that you use the correct coordinates when you do this. That's explained here: How to position text relative to page using iText?
Update:
Json posted the following code in the comments:
string oldFile = @"C:\Users\ae40394\Desktop\hello.pdf";
string newFile = @"C:\Users\ae40394\Desktop\NEW.pdf";
// creating a reader with the original PDF
PdfReader reader = new PdfReader(oldFile);
Rectangle rect = reader.GetPageSize(1);
FileStream fs = new FileStream(newFile,FileMode.Create);
using (PdfStamper stamper = new PdfStamper(reader, fs)) {
// modify the pdf content
PdfContentByte cb = stamper.GetOverContent(1);
cb.SetColorStroke(iTextSharp.text.BaseColor.GREEN);
cb.SetLineWidth(5f);
cb.Circle(rect.GetLeft() + 30, rect.GetBottom() + 30 ,20f);
cb.Stroke();
}
reader.Close();
File.Replace(@"C:\Users\ae40394\Desktop\NEW.pdf", @"C:\Users\ae40394\Desktop\hello.pdf", @"C:\Users\ae40394\Desktop\hello.pdf.bac");
I slightly adapted the code, because:
- There is no need for a
Document
object,
- The
stamper
is closed when using
is closed,
- When the
stamper
is closed, so is the FileStream
- the coordinates of the circle were hard coded. I used the page size to make sure they are made relative to the origin of the coordinate system, although to be sure, you may also want to check if there's a Crop Box.