Adding text to a pdf

Hello,

I have used PdfLoadedDocument and document.Pages.Insert to add a new page to the beginning of my document. I would like to add text to the first page (the one created with the Pages.Insert()) but it doesnt seem like its possible. Im getting a NullException when i try this. 


 //Load the PDF document

            PdfLoadedDocument document = new PdfLoadedDocument(dlFile);


//Insert a new page into the document

            document.Pages.Insert(0,PdfPageSize.Letter);


//Adding Text to First Page

            PdfLoadedPage page = document.Pages[0] as PdfLoadedPage;

            PdfGraphics graphics = page.Graphics;

            PdfFont graphicFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

            graphics.DrawString("Test", graphicFont, PdfBrushes.Black, new PointF(0, 0));

 //End Adding text to first page


1 Reply

GK Gowthamraj Kumar Syncfusion Team August 16, 2021 10:53 AM UTC

Hi Shane, 
 
Thank you for contacting Syncfusion support.

Yes. We can draw the text on first page which newly inserted on existing PDF document. Please try the below modified code snippet on your end and let us know the result.
 
 
//Load the PDF document 
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("../../Input.pdf"); 
 
PdfMargins margin = new PdfMargins(); 
margin.All = 0; 
 
//Insert a new page in the beginning of the document 
loadedDocument.Pages.Insert(0,PdfPageSize.Letter, margin); 
 
PdfPageBase page = loadedDocument.Pages[0] as PdfPageBase; 
 
PdfGraphics graphics = page.Graphics; 
 
PdfFont graphicFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); 
 
graphics.DrawString("Test", graphicFont, PdfBrushes.Black, new PointF(0, 0)); 
 
//Save and close the document 
 
loadedDocument.Save("../../Output.pdf"); 
 
loadedDocument.Close(true); 
 
Please let us know if you need any further assistance with this. 
 
Regards, 
Gowthamraj K 


Loader.
Up arrow icon