프로젝트를 만들고 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 참조
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
'IT' 카테고리의 다른 글
리눅스 용량 확인 명령어들 (0) | 2022.07.21 |
---|---|
윈도우 Task 명령어 (tasklist , taskkill , wmic) (0) | 2022.07.06 |
ClickOnce 기간 길고 넉넉하게 개인키 인증서 생성 발급하기 (0) | 2022.06.27 |
Windows 10 RS4 이상 , 최고의 성능 전원 관리 옵션 활성화 (0) | 2022.06.26 |
ubuntu mysql cron mysqldump 백업 자동화 스크립트 (0) | 2020.03.24 |
댓글