I have a PDF file and I want to add a simple number on each page.
Here is my code:
reader = new PdfReader(fileOut);
Document final = new Document(reader.GetPageSize(1));
PdfWriter w = PdfWriter.GetInstance(final, new FileStream(finalFile, FileMode.Create, FileAccess.Write));
w.SetFullCompression();
final.Open();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
final.NewPage();
PdfContentByte cb = w.DirectContent;
ControlNumberTimes(cb, "C"+i, 560, 725, 270, Element.ALIGN_LEFT);
cb.AddTemplate(w.GetImportedPage(reader, i), 0, 0);
}
final.Close();
reader.Close();
private static void ControlNumberTimes( PdfContentByte cb1, string control, int x, int y, int rotation, int allign )
{
cb1.BeginText();
cb1.SetColorFill(BaseColor.BLACK);
cb1.SetFontAndSize(BaseFont.CreateFont("C:\\windows\\Fonts\\times.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 7.5f);
cb1.ShowTextAligned(allign, control, x, y, rotation);
cb1.EndText();
}
Before adding this text, PDF file size is 3.6 Mb, after the size is 11 Mb. What I am doing wrong?
This is my code now:
string finalFile = System.IO.Path.GetDirectoryName(fileOut) + "\\" +
System.IO.Path.GetFileNameWithoutExtension(fileOut) + "_num.pdf";
reader = new PdfReader(fileOut);
using (FileStream fs = new FileStream(finalFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader, fs))
{
int pageCount = reader.NumberOfPages;
for (int i = 1; i <= pageCount; i++)
{
ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase(
$"C{i}"), 560, 725, 0);
}
}
}
The pdf file I can't share due of the confidential information.