The following example demonstrates how to insert a page into an existing PDF document.
It also briefly covers how to create the initial document, add a new page to it, add text on the various pages of the document & then save said document with the newly inserted content.
| Insert pages at a specific location in the PDF document (C#) |
Copy Code |
|---|---|
public static void InsertPage() { Console.WriteLine( "=== INSERT PAGE ===" ); var outputFileName = "InsertPage.pdf"; var outputPath = PagesSample.PagesSampleOutputDirectory + outputFileName; // Creates a PdfDocument. using( var pdfoutput = PdfDocument.Create( outputPath ) ) { // Gets the first Page of the document. var page = pdfoutput.Pages.First(); // Adds a title. var titleStyle = TextStyle.WithFont( pdfoutput.Fonts.GetStandardFont( StandardFontType.Helvetica ), 15d ); page.AddParagraph( "Insert Page", titleStyle, new ParagraphStyle( ParagraphHorizontalAlignment.Center ) ); // Defines a TextStyle to use for the following texts. var textStyle = TextStyle.WithFont( pdfoutput.Fonts.GetStandardFont( StandardFontType.Helvetica ), 18 ); // Adds text on the first Page. page.AddText( "This text is on FIRST page.", new Point( 30, 100 ), textStyle ); // Adds a new Page. page = pdfoutput.Pages.Add(); // Adds text on the added Page. page.AddText( "This text is on the LAST page.", new Point( 30, 100 ), textStyle ); // Inserts a new Page between the 2 firsts (at index 1). page = pdfoutput.Pages.Insert( 1 ); // Adds text on the inserted Page. page.AddText( "This text is on an INSERTED page.", new Point( 30, 100 ), textStyle ); // Saves the output document. pdfoutput.Save(); Console.WriteLine( $"Info exported to path: {outputFileName}" ); } } | |