Merge PDF Files and Add Page Number in C#/VB.NET

After searching so much information about PDF merge, it is easy to find that whether you merge PDF files online or use C#/VB.NET to realize this task, you never escape worrying some important points such as the safety of your PDF file, so much time it costs or whether the merged file supports to print page number and so on. However, as long as you come here, these troubles will not appear. This section will specifically introduce you a secure solution to merge PDF files into one with C#, VB.NET via a .NET PDF component Spire.PDF for .NET.

Spire.PDF for .NET, built from scratch in C#, enables programmers and developers to create, read, write and manipulate PDF documents in .NET applications without using Adobe Acrobat or any external libraries. Using Spire.PDF for .NET, you not only can quickly merge PDF files but also enables you to print PDF page with page number. Now please preview the effective screenshot below:

Merge PDF Documents

Before following below procedure, please download Spire.PDF for .NET and install it on system.

Step1: You can use the String array to save the names of the three PDF files which will be merged into one PDF and demonstrate Spire.Pdf.PdfDocument array. Then, load three PDF files and select the first PdfDocument for the purpose of merging the second and third PDF file to it. In order to import all pages from the second PDF file to the first PDF file, you need to call the method public void AppendPage(PdfDocument doc). Also by calling another method public PdfPageBase InsertPage(PdfDocument doc, int pageIndex),every page of the third PDF file can be imported to the first PDF file.

[C#]
private void button1_Click(object sender, EventArgs e)
        {
            //pdf document list
            String[] files = new String[]
            {
                @"..\PDFmerge0.pdf",
                @"..\ PDFmerge1.pdf",
                @"..\ PDFmerge2.pdf"
            };
            //open pdf documents            
            PdfDocument[] docs = new PdfDocument[files.Length];
            for (int i = 0; i < files.Length; i++)
            {
                docs[i] = new PdfDocument(files[i]);
            }
            //append document
            docs[0].AppendPage(docs[1]);

            //import PDF pages
            for (int i = 0; i < docs[2].Pages.Count; i = i + 2)
            {
                docs[0].InsertPage(docs[2], i);
            }
[VB.NET]
 Private Sub button1_Click(sender As Object, e As EventArgs)
	'pdf document list
	Dim files As [String]() = New [String]() {"..\PDFmerge0.pdf", "..\ PDFmerge1.pdf", "..\ PDFmerge2.pdf"}
	'open pdf documents            
	Dim docs As PdfDocument() = New PdfDocument(files.Length - 1) {}
	For i As Integer = 0 To files.Length - 1
		docs(i) = New PdfDocument(files(i))
	Next

	'append document
	docs(0).AppendPage(docs(1))

	'import PDF pages
	Dim i As Integer = 0
	While i < docs(2).Pages.Count
		docs(0).InsertPage(docs(2), i)
		i = i + 2
	End While

Step2: Draw page number in the first PDF file. In this step, you can set PDF page number margin by invoking the class Spire.Pdf.Graphics. PdfMargins. Then, Call the custom method DrawPageNumber(PdfPageCollection pages, PdfMargins margin, int startNumber, int pageCount) to add page number in the bottom of every page in the first PDF. Please see the detail code below:

[C#]
           //set PDF margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;
            this.DrawPageNumber(docs[0].Pages, margin, 1, docs[0].Pages.Count);

          private void DrawPageNumber(PdfPageCollection pages, PdfMargins margin, int startNumber, int pageCount)
          {
            foreach (PdfPageBase page in pages)
            {
                page.Canvas.SetTransparency(0.5f);
                PdfBrush brush = PdfBrushes.Black;
                PdfPen pen = new PdfPen(brush, 0.75f);
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 9f, System.Drawing.FontStyle.Italic), true);
                PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
                format.MeasureTrailingSpaces = true;
                float space = font.Height * 0.75f;
                float x = margin.Left;
                float width = page.Canvas.ClientSize.Width - margin.Left - margin.Right;
                float y = page.Canvas.ClientSize.Height - margin.Bottom + space;
                page.Canvas.DrawLine(pen, x, y, x + width, y);
                y = y + 1;
                String numberLabel
                    = String.Format("{0} of {1}", startNumber++, pageCount);
                page.Canvas.DrawString(numberLabel, font, brush, x + width, y, format);
                page.Canvas.SetTransparency(1);
            }
        }
[VB.NET]
       'set PDF margin
	Dim unitCvtr As New PdfUnitConvertor()
	Dim margin As New PdfMargins()
	margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	margin.Bottom = margin.Top
	 margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	margin.Right = margin.Left
	Me.DrawPageNumber(docs(0).Pages, margin, 1, docs(0).Pages.Count)

       Private Sub DrawPageNumber(pages As PdfPageCollection, margin As PdfMargins, startNumber As Integer, pageCount As Integer)
	For Each page As PdfPageBase In pages
		page.Canvas.SetTransparency(0.5F)
		Dim brush As PdfBrush = PdfBrushes.Black
		Dim pen As New PdfPen(brush, 0.75F)
		Dim font As New PdfTrueTypeFont(New Font("Arial", 9F, System.Drawing.FontStyle.Italic), True)
		Dim format As New PdfStringFormat(PdfTextAlignment.Right)
		format.MeasureTrailingSpaces = True
		Dim space As Single = font.Height * 0.75F
		Dim x As Single = margin.Left
		Dim width As Single = page.Canvas.ClientSize.Width - margin.Left - margin.Right
		Dim y As Single = page.Canvas.ClientSize.Height - margin.Bottom + space
		page.Canvas.DrawLine(pen, x, y, x + width, y)
		y = y + 1
		Dim numberLabel As [String] = [String].Format("{0} of {1}", System.Math.Max(System.Threading.Interlocked.Increment(startNumber),startNumber - 1), pageCount)
		page.Canvas.DrawString(numberLabel, font, brush, x + width, y, format)
		page.Canvas.SetTransparency(1)
	Next
End Sub

The PDF merge code can be very long when you view it at first sight, actually, if you do not need to add page number in your merged PDF, steps two should be avoided. However, in many cases, page number brings great convenience for users to read PDF as well as print it. Spire.PDF for .NET can satisfy both your requirements of merging PDF files and adding page numbers in the merged PDF file.