Though there are lots of articles illustrate how to merge PDF files, I didn’t find a solution about merge PDF pages among them. In this article, I will share you with how to merge two PDF pages into a single page in C# and VB.NET.
The library used
Free Spire.PDF for .NET
You can get the dll of the Free Spire.PDF for .NET library by downloading from the official website or installing from NuGet.org.
Merge PDF Pages
In fact, there is no direct way to merge two or more PDF pages into a single page, you can't do this even in Adobe Acrobat. Free Spire.PDF provides a CreateTemplate() method and a DrawTemplate() method which allows you to create templates of PDF pages and draw the templates to a new page, using these two methods, you’re able to merge PDF pages.
The following example shows how to merge two PDF pages inside a PDF file into a single page.
C# Language
- using Spire.Pdf;
- using Spire.Pdf.Graphics;
- using System.Drawing;
- namespace MergeAndSplitPdfPages
- {
- class Program
- {
- static void Main(string[] args)
- {
- //Load a Pdf document
- PdfDocument doc = new PdfDocument("Sample.pdf");
- //Get the first page
- PdfPageBase page1 = doc.Pages[0];
- //Get the second page
- PdfPageBase page2 = doc.Pages[1];
- //Create a template for page 2
- PdfTemplate template = page2.CreateTemplate();
- //Set transparency
- page2.Canvas.SetTransparency(1f, 1f, PdfBlendMode.Overlay);
- //Draw the template to specified location of the first page
- page1.Canvas.DrawTemplate(template, new PointF(0, 150));
- //Remove the second page
- doc.Pages.RemoveAt(1);
- //Save the document
- doc.SaveToFile("MergePdfPages.pdf");
- }
- }
- }
- Imports Spire.Pdf
- Imports Spire.Pdf.Graphics
- Imports System.Drawing
- Namespace MergeAndSplitPdfPages
- Class Program
- Private Shared Sub Main(ByVal args As String())
- Dim doc As PdfDocument = New PdfDocument("Sample.pdf")
- Dim page1 As PdfPageBase = doc.Pages(0)
- Dim page2 As PdfPageBase = doc.Pages(1)
- Dim template As PdfTemplate = page2.CreateTemplate()
- page2.Canvas.SetTransparency(1F, 1F, PdfBlendMode.Overlay)
- page1.Canvas.DrawTemplate(template, New PointF(0, 150))
- doc.Pages.RemoveAt(1)
- doc.SaveToFile("MergePdfPages.pdf")
- End Sub
- End Class
- End Namespace
Output:
Comments
Post a Comment