IT/프로그램 | 앱

C# iTextSharp PDF 파일 합치기 Merge

DKSOFT 2022. 6. 28.
프로젝트를 만들고 Nuget 으로 iTextSharp 을 설치 해주세요

아래코드는
PDF File1 : File1.pdf 파일과 PDF File2 : File2.pdf 파일을 합쳐서 newFile.pdf 로 출력하는 프로그램 입니다.

 

/*
아래코드를 자신의 프로젝트에 맞게 변형해서 넣어 주세요.
*/

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

static void Main(string[] args)
{
    //Pdf 합치는 함수
    MergePDF(@"D:/File1.pdf", @"D:/File2.pdf" , @"D:/newFile.pdf");
}
        
private static void MergePDF(string File1, string File2 , string outputFile)
{
    string[] fileArray = new string[3];
    fileArray[0] = File1;
    fileArray[1] = File2;

    PdfReader reader = null;
    iTextSharp.text.Document sourceDocument = null;
    PdfCopy pdfCopyProvider = null;
    PdfImportedPage importedPage;
    string outputPdfPath = outputFile;

    sourceDocument = new iTextSharp.text.Document();
    pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

    //output file Open  
    sourceDocument.Open();


    //files list wise Loop  
    for (int f = 0; f < fileArray.Length - 1; f++)
    {
        int pages = TotalPageCount(fileArray[f]);

        reader = new PdfReader(fileArray[f]);
        //Add pages in new file  
        for (int i = 1; i <= pages; i++)
        {
            importedPage = pdfCopyProvider.GetImportedPage(reader, i);
            pdfCopyProvider.AddPage(importedPage);
        }

        reader.Close();
    }
    //save the output file  
    sourceDocument.Close();
}

private static int TotalPageCount(string file)
{
    using (StreamReader sr = new StreamReader(System.IO.File.OpenRead(file)))
    {
        Regex regex = new Regex(@"/Type\s*/Page[^s]");
        MatchCollection matches = regex.Matches(sr.ReadToEnd());

        return matches.Count;
    }
}

해당 코드를 빌드 후 D:\ 를 확인하면 newFile.pdf 파일 생성된것을 확인 할 수 있습니다.

응용해서 많이 이용 하시고 즐거운 코딩 생활 되세요~

 

iTextSharp 프로젝트 URL 참조

https://itextpdf.com 

 

The Leading PDF Library for Developers | iText

We have an active community of partners, customers, and contributors, that help us every day to improve our products, documentation and support. We see them as part of our iText family, and hope you will join our family too.

itextpdf.com

 

댓글

💲 추천 글