What is the optimum way to merge 2 PDF files with ITextSharp in C#? I'm using ASP.NET/.NET3.5.
-
1I've used code based on the following article with success: Simple .NET PDF Merger– Jay RiggsFeb 9, 2010 at 22:57
-
iTextSharp is now called "iText 7 for .NET"or "itext7-dotnet" on github: link. It's recommended to add itext7 with Nuget to your solution.– Peter HuberAug 29, 2020 at 4:44
Add a comment
|
2 Answers
public static void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
//fixed typo
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
});
}
}
-
How can I use this function? Say, you have a generated pdf and append it to a physical file pdf? Oct 13, 2015 at 15:34
-
2Please note that this answer is wrong. It throws away all interactivity and it can result in bloated files if the different PDFs contain identical resources. The only correct answer is an answer that uses
PdfSmartCopy
which is another class that is available in iTextSharp. Apr 1, 2016 at 10:19 -
-
I would vote down @BrunoLowagie comment if I could, it isn't actually relevant to question and it is just him advertising his proprietary version of iTextSharp Jul 28, 2017 at 15:41
-
@BrunoLowagie does the PdfSmartCopy retains the ADA compliance properties if merged two ADA compliant pdfs?– ScottSJun 15 at 12:30
The last answer works if you don't want to delete the original files. In my case, I want to delete and when I tried I got exception. My solution is:
public static bool MergePDFs(List<String> InFiles, String OutFile)
{
bool merged = true;
try
{
List<PdfReader> readerList = new List<PdfReader>();
foreach (string filePath in InFiles)
{
PdfReader pdfReader = new PdfReader(filePath);
readerList.Add(pdfReader);
}
//Define a new output document and its size, type
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Create blank output pdf file and get the stream to write on it.
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OutFile, FileMode.Create));
document.Open();
foreach (PdfReader reader in readerList)
{
PdfReader.unethicalreading = true;
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
foreach (PdfReader reader in readerList)
{
reader.Close();
}
}
catch (Exception ex)
{
merged = false;
}
return merged;
}
I copied the code from Original Code
-
Slight modifications to handle rotation of pages, etc, but apart from that, it easily replaced the code in my project that was locking files..– AdsMay 3, 2016 at 2:25