Adding Text to a multipage pdf

Hello,
im trying to add a text to every page of a pdf but only the last page has the text. What am i doing wrong?

TextFragment textFragment = new TextFragment("text");
[...]

 foreach (Aspose.Pdf.Page page in asposeDoc.Pages)
 {
                    textFragment.Position = new Position(X, Y);
                    textBuilder = new TextBuilder(page);
                    textBuilder.AppendText(textFragment);     
 }

[...]

MemoryStream ms1 = new MemoryStream();
asposeDoc.Save(ms1);

@BSchwab

Can you please share the complete runnable code snippet which can reproduce the same issue that you are facing? We will try to replicate it at our side and address it accordingly.

This is an example code. Only the last page has the text “text”.

  public void AddTextTest()
        {
            Aspose.Pdf.Document asposeDoc = new Aspose.Pdf.Document(@"C:\temp\test.pdf");
            
            TextFragment textFragment = new TextFragment("text");
            textFragment.TextState.Font = FontRepository.FindFont("Arial");
            textFragment.Position = new Position(100, 100);

            foreach (Aspose.Pdf.Page page in asposeDoc.Pages)
            {
                TextBuilder textBuilder = new TextBuilder(page);
                textBuilder.AppendText(textFragment);
            }

            asposeDoc.Save(@"C:\temp\test_new.pdf");
        }

@BSchwab

We have noticed that the code snippet involves a sample PDF document as you are not creating one from the scratch. Could you please share the sample used PDF file as well so that we can test the scenario in our environment and address it accordingly?

You can use every multipage pdf in the world.
Nevertheless i uploaded a file: test.pdf (133.2 KB)

@BSchwab

We always request for a sample file for testing because PDF documents have different structures. Even two identical PDF documents can have different structures. Nevertheless, the PDF you shared has only one page and we could not perform complete test on it. However, we have tested using one of our sample files and noticed the same issue that you mentioned. We shifted the logic to initialize text fragment inside the loop and issue was resolved.

Aspose.Pdf.Document asposeDoc = new Aspose.Pdf.Document(dataDir + @"test.pdf");

foreach (Aspose.Pdf.Page page in asposeDoc.Pages)
{
 TextFragment textFragment = new TextFragment("text");
 textFragment.TextState.Font = FontRepository.FindFont("Arial");
 textFragment.Position = new Position(100, 100);
 TextBuilder textBuilder = new TextBuilder(page);
 textBuilder.AppendText(textFragment);
}

asposeDoc.Save(dataDir + @"test_new.pdf");

Please use the code like above and let us know in case you still notice any issue.

This works. Thank you.

1 Like