푸터 콘텐츠로 바로가기
제품 비교

How to Merge PDF Files Using iTextSharp

Merging PDF documents is a common requirement in various software applications, such as document management systems, report generation tools, and more. In the .NET ecosystem, developers have several libraries at their disposal to manipulate PDF files. iTextSharp and IronPDF are two popular choices for working with PDFs in C# applications. In this article, we will explore how to merge PDFs using iTextSharp and compare it with IronPDF to help you make an informed decision when choosing a library for your PDF manipulation needs.

How to Merge PDF Files Using iTextSharp

Here's a step-by-step guide on how to merge PDFs using iTextSharp:

  1. Create a new Document object and specify a base path for your PDF files.
  2. Open the Document for editing.
  3. Define an array of PDF file names to merge.
  4. For each PDF file in the list, create a PdfReader, add its contents to the PdfCopy object, and then close the PdfReader.
  5. Close the Document, finalizing the merged PDF.

IronPDF

IronPDF Webpage is a .NET library that empowers developers to create, modify, and interact with PDF documents within their C# and .NET applications. It simplifies PDF-related tasks by offering features like PDF generation from scratch, HTML to PDF conversion, PDF manipulation (including adding, removing, and modifying content), interactive form handling, PDF merging and splitting, encryption, and cross-platform compatibility, making it a valuable tool for a wide range of applications requiring PDF document management and generation.

iTextSharp

iTextSharp has been replaced by iText 7, as it has reached its End-of-Life (EOL), with only security fixes in sight. It's highly recommended to use iText 7 or consider transitioning existing ones for new projects. iText 7 offers significant improvements, including HTML to PDF conversion, PDF redaction, SVG support, better language support, debugging tools, data extraction, and more modular functionality. It simplifies PDF document handling and is available under AGPL and Commercial licenses.

Install IronPDF Library

To install the IronPDF NuGet package in your Visual Studio project, you can follow these steps:

  1. Start by opening your project in Visual Studio where you want to use the IronPDF library.
  2. If you're using Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console.
  3. In the Package Manager Console, run the following command to install IronPDF:
Install-Package IronPdf

Visual Studio will download and install the package and its dependencies. You can monitor the progress in the Output window. Once the installation is complete, you can start using IronPDF in your C# code.

**How to Merge PDF Files Using iTextSharp: Figure 1 - The completed installation shown in the built-in terminal in Visual Studio.**

With IronPDF successfully installed, you can now start using it in your project. Include the necessary "using" statements in your code files and begin working with PDFs using IronPDF's functionality.

using IronPdf;
using IronPdf;
$vbLabelText   $csharpLabel

You can now access the features and functionality provided by IronPDF to work with PDF documents in your C# project. Remember to save your project and build it to ensure that the library is properly integrated.

Install iTextSharp PDF Library

To install the iTextSharp PDF library in a C# project, follow these steps:

  1. Open the C# project where you want to use the iTextSharp library in your preferred integrated development environment (IDE), such as Visual Studio.
  2. Go to Tools > NuGet Package Manager > Package Manager Console.
  3. In the Package Manager Console, run the following command:
Install-Package iTextSharp

This command tells NuGet (the package manager for Visual Studio) to download and install the iTextSharp package and its dependencies into your project.

NuGet will download and install the iTextSharp package and any required dependencies. You can monitor the installation progress in the Package Manager Console.

**How to Merge PDF Files Using iTextSharp:** Figure 2 - The completed installation shown in the built-in terminal in Visual Studio.

Once the installation is complete, you'll see a confirmation message in the Package Manager Console indicating that the iTextSharp package has been successfully installed. With iTextSharp successfully installed, you can now start using it in your project. Include the necessary using statements in your code files and begin working with PDFs using iTextSharp's functionality.

Merge PDFs to a Single PDF Document Using IronPDF

IronPDF provides a direct method to merge multiple PDF files into a single PDF. IronPDF offers great flexibility when it comes to merging PDF documents. The following sample code demonstrates the merging of PDFs into a single PDF file:

using IronPdf;
using System.Collections.Generic;

static void Main(string[] args)
{
    string basePath = @"D:\PDFFiles\";
    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Create a list to hold the PDF documents to be merged
    List<PdfDocument> docList = new List<PdfDocument>();

    // Add each PDF to the list
    foreach (string filename in pdfFiles)
    {
        docList.Add(new PdfDocument(basePath + filename));
    }

    // Merge the PDFs into one document
    var mergedPDF = PdfDocument.Merge(docList);

    // Save the merged PDF to the specified path
    mergedPDF.SaveAs(basePath + "mergePDFbyIronPDF.pdf");
}
using IronPdf;
using System.Collections.Generic;

static void Main(string[] args)
{
    string basePath = @"D:\PDFFiles\";
    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Create a list to hold the PDF documents to be merged
    List<PdfDocument> docList = new List<PdfDocument>();

    // Add each PDF to the list
    foreach (string filename in pdfFiles)
    {
        docList.Add(new PdfDocument(basePath + filename));
    }

    // Merge the PDFs into one document
    var mergedPDF = PdfDocument.Merge(docList);

    // Save the merged PDF to the specified path
    mergedPDF.SaveAs(basePath + "mergePDFbyIronPDF.pdf");
}
$vbLabelText   $csharpLabel

The above code uses the IronPDF library to merge two PDF files ("PdfFile_1.pdf" and "PdfFile_2.pdf") located in the specified base path ("D:\PDFFiles"). It creates a list of PdfDocument objects, adds the input PDFs to the list, merges them into a single PDF using PdfDocument.Merge, and saves the merged PDF as "mergePDFbyIronPDF.pdf" in the same base path.

The following is the sample PDFs used in this example:

**How to Merge PDF Files Using iTextSharp:** Figure 3 - A simple PDF file, with a title A Simple PDF File and some body text beneath, along with a single-page PDF article.

The following is the merged PDF file:

**How to Merge PDF Files Using iTextSharp:** Figure 4 - The combined PDF, with the simple PDF first and the article second.

Merge Multiple PDF Files using iTextSharp

iTextSharp does not provide a direct method to merge PDF files. However, we can achieve it by opening each input PDF and adding its content to the output document. The following sample code merges PDF files into a single PDF document:

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

static void Main(string[] args)
{
    // Create a new Document
    Document doc = new Document();

    string basePath = @"D:\PDFFiles\";

    // Create a PdfCopy instance to copy pages from source PDFs
    PdfCopy copy = new PdfCopy(doc, new FileStream(basePath + "mergePdf.pdf", FileMode.Create));

    // Open the document for writing
    doc.Open();

    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Loop through all the PDF files to be merged
    foreach (string filename in pdfFiles)
    {
        // Read the content of each PDF
        PdfReader reader = new PdfReader(basePath + filename);

        // Add the document to PdfCopy
        copy.AddDocument(reader);

        // Close the reader
        reader.Close();
    }

    // Close the Document
    doc.Close();
}
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

static void Main(string[] args)
{
    // Create a new Document
    Document doc = new Document();

    string basePath = @"D:\PDFFiles\";

    // Create a PdfCopy instance to copy pages from source PDFs
    PdfCopy copy = new PdfCopy(doc, new FileStream(basePath + "mergePdf.pdf", FileMode.Create));

    // Open the document for writing
    doc.Open();

    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Loop through all the PDF files to be merged
    foreach (string filename in pdfFiles)
    {
        // Read the content of each PDF
        PdfReader reader = new PdfReader(basePath + filename);

        // Add the document to PdfCopy
        copy.AddDocument(reader);

        // Close the reader
        reader.Close();
    }

    // Close the Document
    doc.Close();
}
$vbLabelText   $csharpLabel

The above code using iTextSharp merges two PDF files ("PdfFile_1.pdf" and "PdfFile_2.pdf") from the specified base path ("D:\PDFFiles") into a single PDF named "mergePdf.pdf." It accomplishes this by opening each input PDF, adding its content to the output document, and then closing the documents. The above code will merge multiple PDFs into one PDF.

We have used two input files as follows:

**How to Merge PDF Files Using iTextSharp:** Figure 5 - The same input PDFs as earlier.

The new file created by our code is as follows:

**How to Merge PDF Files Using iTextSharp:** Figure 6 - The combined PDF, with the simple PDF first and the article second.

Conclusion

In comparison to iTextSharp, IronPDF emerges as the superior choice for merging PDF documents in C# applications. While both libraries are capable, IronPDF offers a more user-friendly interface, modern features like HTML to PDF conversion, clear licensing options, straightforward integration through NuGet, and active development, collectively simplifying the merging process, reducing development time, and ensuring a more reliable solution for PDF-related tasks. Its user-friendly interface, robust feature set, and continuous development make IronPDF the superior solution for merging PDFs in C#.

참고해 주세요iText 7 is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by iText 7. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

자주 묻는 질문

C#에서 PDF 파일을 병합하려면 어떻게 해야 하나요?

IronPDF를 사용하여 C#에서 PDF 파일을 병합하려면 PdfDocument 개체 목록을 만들고 PdfDocument.Merge 메서드를 활용하여 단일 PDF 문서로 결합할 수 있습니다.

PDF 조작에 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 사용자 친화적인 인터페이스, HTML에서 PDF로의 변환, 대화형 양식 및 플랫폼 간 호환성과 같은 최신 기능을 제공하여 C# 애플리케이션에서 PDF를 효율적으로 조작할 수 있는 도구입니다.

Visual Studio용 C# 프로젝트에 PDF 라이브러리를 설치하려면 어떻게 하나요?

Visual Studio C# 프로젝트에 IronPDF를 설치하려면 패키지 관리자 콘솔에서 'Install-Package IronPDF' 명령을 실행하여 NuGet 패키지 관리자를 사용하세요.

PDF 병합을 위한 iTextSharp와 IronPDF의 차이점은 무엇인가요?

iTextSharp는 각 PDF 문서에서 콘텐츠를 수동으로 추가해야 하는 반면, IronPDF는 PDF를 병합하는 직접적인 방법을 통해 보다 간단한 솔루션을 제공하여 개발 시간과 복잡성을 줄여줍니다.

개발자가 iTextSharp에서 iText 7 또는 IronPDF로 전환해야 하는 이유는 무엇인가요?

ITextSharp는 수명이 다한 반면, iText 7은 향상된 기능을 제공하므로 개발자는 전환해야 합니다. 그러나 IronPDF는 훨씬 더 현대적인 기능과 사용 편의성을 제공하므로 PDF 조작을 위한 탁월한 선택입니다.

IronPDF는 PDF 파일 병합 그 이상을 처리할 수 있나요?

예, IronPDF는 처음부터 PDF 생성, HTML을 PDF로 변환, 콘텐츠 수정, 양식 처리, 암호화 적용 등 다양한 PDF 조작을 지원합니다.

IronPDF가 C#에서 PDF 조작을 위한 신뢰할 수 있는 선택인 이유는 무엇인가요?

IronPDF는 활발하게 개발되고 최신 기능을 제공하며 PDF 조작 작업을 간소화하는 사용자 친화적인 인터페이스를 제공하므로 개발자에게 안정적이고 효율적인 선택이 될 수 있습니다.

IronPDF는 이전 라이브러리와 비교하여 PDF 병합 프로세스를 어떻게 개선하나요?

IronPDF는 PDF 파일을 직접 결합하는 방법을 제공하여 병합 프로세스를 개선하고, C# 프로젝트와의 통합을 간소화하며, 전체 개발 시간을 단축합니다.

개발자가 C#용 PDF 라이브러리를 선택할 때 염두에 두어야 할 고려 사항은 무엇인가요?

개발자는 C# 프로젝트용 PDF 라이브러리를 선택할 때 사용 편의성, 기능 세트, 라이선스 옵션, 호환성 및 적극적인 개발 지원과 같은 요소를 고려해야 합니다. IronPDF는 이러한 영역에서 탁월하므로 선호되는 선택입니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.