In some circumstance where we need to create a copy of the existing pages in our PDF document instead of copying the entire file, in particular, if we have to create hundreds copies of a certain page, it can be tedious to copy the page one after another. This article demonstrates a solution for how to duplicate a page in a PDF document and create multiple copies at a time using Spire.PDF.
In this example, I prepare a sample PDF file that only contains one page and eventually I’ll create ten copies of this page in the same document. Main method would be as follows:
Code Snippet:
Step 1: Create a new PDF document and load the sample file.
PdfDocument pdf = new PdfDocument("Sample.pdf");
Step 2: Get the first page from PDF, get the size of the page. Create a new instance of Pdf Template object based on the content and appearance of the first page.
PdfPageBase page = pdf.Pages[0]; SizeF size = page.Size; PdfTemplate template = page.CreateTemplate();
Step 3: Create a new PDF page with the method Pages.Add() based on the size of the first page, draw the template on the new page at the specified location. Use a for loops to get more copies of this page.
for (int i = 0; i < 10; i++) { page = pdf.Pages.Add(size, new PdfMargins(0)); page.Canvas.DrawTemplate(template, new PointF(0, 0)); }
Step 4: Save the file.
pdf.SaveToFile("Result.pdf");
Output:
Ten copies of the first page have been created in the sample PDF document.
Full Code:
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace DuplicatePage { class Program { static void Main(string[] args) { PdfDocument pdf = new PdfDocument("Sample.pdf"); PdfPageBase page = pdf.Pages[0]; SizeF size = page.Size; PdfTemplate template = page.CreateTemplate(); for (int i = 0; i < 10; i++) { page = pdf.Pages.Add(size, new PdfMargins(0)); page.Canvas.DrawTemplate(template, new PointF(0, 0)); } pdf.SaveToFile("Result.pdf"); } } }
Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports System.Drawing Namespace DuplicatePage Class Program Private Shared Sub Main(args As String()) Dim pdf As New PdfDocument("Sample.pdf") Dim page As PdfPageBase = pdf.Pages(0) Dim size As SizeF = page.Size Dim template As PdfTemplate = page.CreateTemplate() For i As Integer = 0 To 9 page = pdf.Pages.Add(size, New PdfMargins(0)) page.Canvas.DrawTemplate(template, New PointF(0, 0)) Next pdf.SaveToFile("Result.pdf") End Sub End Class End Namespace