Merge PDF File using itextsharp library


Merge any number of pdf file into one pdf file in C#.net using itextsharp dll

Here i develop a class for merge pdf file in to C#.net using free source dll itextsharp.
Requirement: download iTextSharp.dll from below link
http://sourceforge.net/projects/itextsharp/
U should have .net framework on your machine.
Just copy paste this class in your project and use it by creating object of that class and passing sourceFiles array which contain all pdf file name which u want to merge and one destinationFile which u need to resulting final pdf file.
Only u need to add reference of that dll in your project and this class is working very well.


using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class PdfMerge
{
public static void MergeFiles(string destinationFile, string[] sourceFiles)
{
try
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
// step 4: we add content
while (f < sourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
//Console.WriteLine("Processed page " + i);
}
f++;
if (f < sourceFiles.Length)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
}
}
// step 5: we close the document
document.Close();
}
catch(Exception e)
{
string strOb = e.Message;
}
}

public int CountPageNo(string strFileName)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(strFileName);
// we retrieve the total number of pages
return reader.NumberOfPages;
}
}


Reference: http://sourceforge.net/projects/itextsharp/


Comments

Author: Scott05 Mar 2010 Member Level: Bronze   Points : 1

This is fantastic. We probably saved $250 by using this suggestion. The string array that contains the source files is a little sensitive...I had better luck passing this in using an array of unknown/unspecified length. Other than that, it was great.

Author: dot net noob28 Mar 2010 Member Level: Bronze   Points : 2

Hi Arvind: I tried your code in a web project, and when I pass the destination file name and a string array of pdfs to be merged, I don't receive any errors but the destination file is not written. If this was a directory permissions error, would I see a compilation error occur on this line?

Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream(destinationFile, FileMode.Create))

If not, why else would the file not be created?

I'm passing a destination file like:
"C:\test\mycombined.pdf"

and a string like:
Dim myTempArr() As String = {"C:\test\file1.pdf", "C:\test\file2.pdf"}

Author: Scott30 Mar 2010 Member Level: Bronze   Points : 2

Noob,

I translated my C# into VB and it worked on the 1st try.

1. include/import iTextSharp.text and iTextSharp.text.pdf
2. Put PdfMerge.cs (attached) somewhere in the App_Code folder. I got this from Arvind kumar's code sample (above)
3. Write this simple test web page in VB:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim anArrayOfPDFs() As String = {"C:\Inetpub\wwwroot\PDFs\whatever.pdf", "C:\Inetpub\wwwroot\PDFs\whatever2.pdf"}
PdfMerge.MergeFiles("C:\Inetpub\wwwroot\PDFs\Destination.pdf", anArrayOfPDFs)

End Sub

If you can't get this working, perhaps you need further experience using class files. Or you might have a problem with permissions in the folder you are trying to write to. Note that the class file is written in C#, but it doesn't really matter. You can call a class file from a VB or a C# web page.

Author: Scott31 Mar 2010 Member Level: Bronze   Points : 2

Here is code to create a hello world using the iTextSharp DLL. I am using a stringbuilder to minimize string manipulation overhead.


using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;

public partial class PDFiTextSharpTEST2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Document document = new Document();

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("C:\\Inetpub\\wwwroot\\PDFs\\Destination1.pdf", FileMode.Create));
// open the document
document.Open();
document.Add(new Paragraph(BuildHelloWorld()));
document.Close();
}

// use a stringbuilder, as that is efficient for string manipulation and is considered a best practice.
protected string BuildHelloWorld()
{
StringBuilder retval = new StringBuilder();
retval.Append("Hello, world!");
return retval.ToString();
}
}

Guest Author: arthi10 May 2012

Hi i have used the code which is there in the first ..
Here its adding the all the pdf files in one pdf file but mine problem is its not adding the details in that pdf from other pdf..


please help me how to over come from this...

Guest Author: Brian18 Sep 2012

What versions of the itextsharp.dll do I need? I tried with 4.x.x and a new PDF file gets created in the correct location, but it never completes. You can't open it, it says the file is still in use. If I reboot the server, I can access it, but it errors out as it isn't a complete file (1KB).

Thanks!

Guest Author: atul kumar15 Sep 2013

awesome man... You saved my days of effort. this is what i was looking for and it worked seamlessly

Author: Morten17 Mar 2014 Member Level: Bronze   Points : 0

Does anyone have an example of an .aspx file using this class?

Author: Arvind kumar05 Mar 2015 Member Level: Gold   Points : 0

Thanks to all....

Hi Morten, Yes I have implemented this code in aspx file, you can use this in you code easily.