Category / Section
How to replace pages in a PDF document?
1 min read
The pages can be replaced in a PDF document using the PdfTemplate. Please find the code snippet and sample below for the same.
C#:
//Existing pdf with file path. string file1 = "../../Data/imageDoc.pdf"; //Loading File1 PdfLoadedDocument ldDoc1 = new PdfLoadedDocument(file1); //Gets the page collection of loaded document PdfLoadedPageCollection pageCollection = ldDoc1.Pages; //Removes the page at index zero pageCollection.RemoveAt(0); //Initializes font. PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); //Creates a new Pdf document PdfDocument doc = new PdfDocument(); //Adds a new page PdfPage page = doc.Pages.Add(); PdfGraphics g = page.Graphics; //Draws string in the new page. g.DrawString("Hello", font, PdfBrushes.Black, new PointF(0, 0)); //Creates template of replacing page. PdfTemplate template = page.CreateTemplate(); //Inserts new page at index zero in loaded document PdfPage newLoadedPage = pageCollection.Insert(0) as PdfPage; PdfGraphics lgraphics = newLoadedPage.Graphics; //Draw the template of the replacing page in the newly inserted loaded document page graphics. lgraphics.DrawPdfTemplate(template, PointF.Empty, page.GetClientSize()); //Save the document and dispose it ldDoc1.Save("sample.pdf"); ldDoc1.Close();
Sample Link:
https://www.syncfusion.com/downloads/support/directtrac/139783/ze/Template-650157397