Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp - Position text on top of existing contents

Tags:

c#

itext

I have been able to absolute position the new text with x,y co-ordinates but the new text hides behind the existing image. I played around with Stamper, OverContent but with no success.

Here's the code I am using:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(fileNameExisting), null);
Rectangle size = reader.GetPageSizeWithRotation(1);

using (var outStream = new FileStream(fileNameNew, FileMode.Create))
{
    Document document = new Document(size);
    PdfWriter writer = PdfWriter.GetInstance(document, outStream);

    document.Open();
    try
    {
        PdfContentByte cb = writer.DirectContent;

        cb.BeginText();
        try
        {
            cb.SetFontAndSize(BaseFont.CreateFont(), 12);
            cb.SetTextMatrix(10, 100);
            cb.ShowText("My new text");
        }
        finally
        {
            cb.EndText();
        }

        PdfImportedPage page = writer.GetImportedPage(reader, 1);
        cb.AddTemplate(page, 0, 0);

    }
    finally
    {
        document.Close();
        writer.Close();
        reader.Close();
    }
}
like image 375
Jags Avatar asked Dec 16 '25 17:12

Jags


1 Answers

just realised the mistake in my code. GetImportedPage should have been called before setting the text. Here's the updated code:

          try
          {
            PdfImportedPage page = writer.GetImportedPage(reader, 1);
            cb.AddTemplate(page, 0, 0);
            cb.SetFontAndSize(BaseFont.CreateFont(), 12);
            cb.SetTextMatrix(10, 100);
            cb.ShowText("rando text");

          }
like image 113
Jags Avatar answered Dec 19 '25 05:12

Jags



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!