Node.js 사용하여 여러 PDF 파일을 하나의 PDF로 병합하는 방법
IronPDF는 Node.js에서 몇 줄의 코드로 여러 PDF 파일을 하나의 문서로 병합할 수 있도록 해줍니다. PdfDocument.fromFile()로 각 파일을 불러오고, 배열을 PdfDocument.merge()에 전달한 다음, toFile()로 결과를 저장하십시오.
빠른 시작: PDF 파일 병합
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/quickstart-merge.js
// Install: npm install ironpdf
const IronPdf = require('ironpdf');
async function quickMerge() {
const docs = await Promise.all([
IronPdf.PdfDocument.fromFile('doc1.pdf'),
IronPdf.PdfDocument.fromFile('doc2.pdf'),
IronPdf.PdfDocument.fromFile('doc3.pdf'),
]);
const merged = await IronPdf.PdfDocument.merge(docs);
await merged.toFile('merged-output.pdf');
}
quickMerge();//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/quickstart-merge.js
// Install: npm install ironpdf
const IronPdf = require('ironpdf');
async function quickMerge() {
const docs = await Promise.all([
IronPdf.PdfDocument.fromFile('doc1.pdf'),
IronPdf.PdfDocument.fromFile('doc2.pdf'),
IronPdf.PdfDocument.fromFile('doc3.pdf'),
]);
const merged = await IronPdf.PdfDocument.merge(docs);
await merged.toFile('merged-output.pdf');
}
quickMerge();최소 워크플로우(5단계)
- IronPDF 설치:
npm install ironpdf - 라이브러리 가져오기:
const IronPdf = require('ironpdf') PdfDocument.fromFile()로 각 PDF 파일 로드PdfDocument.merge()로 로드된 문서 병합toFile()로 결과 저장
IronPDF는 시스템 수준의 PDF 도구 없이 HTML to PDF 변환, 문서 조립 및 PDF 수정 작업을 처리하는 Node.js용 PDF 조작 라이브러리입니다. 문서를 병합할 때 각 소스 파일의 폰트, 이미지, 내장 양식 및 페이지 기하학을 보존합니다.
배포 전에 IronPDF 라이선스 키를 설정하여 체험판 워터마크를 제거하고 전체 출력을 활성화하세요. 운영체제에 맞는 렌더링 엔진 설정은 IronPdfEngine 구성 가이드를 따릅니다.
Node.js에서 여러 PDF 파일을 병합하는 방법은 무엇입니까?
PdfDocument.merge()은 PdfDocument 객체 배열을 받아, 소스 문서가 배열에 나타나는 순서대로 모든 페이지를 포함하는 새 문서를 반환합니다. 작업은 비파괴적입니다. 원본 파일 객체는 수정되지 않습니다.
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-pdfs.js
const IronPdf = require('ironpdf');
async function mergePdfs(outputFilePath, inputFiles) {
// Load all source documents in parallel
const pdfDocs = await Promise.all(
inputFiles.map(file => IronPdf.PdfDocument.fromFile(file))
);
// Combine into one document, preserving page order
const mergedPdf = await IronPdf.PdfDocument.merge(pdfDocs);
// Write the result to disk
await mergedPdf.toFile(outputFilePath);
console.log(`Merged PDF saved to ${outputFilePath}`);
}
(async () => {
const inputFiles = ['report-jan.pdf', 'report-feb.pdf', 'report-mar.pdf'];
await mergePdfs('quarterly-report.pdf', inputFiles);
})();//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-pdfs.js
const IronPdf = require('ironpdf');
async function mergePdfs(outputFilePath, inputFiles) {
// Load all source documents in parallel
const pdfDocs = await Promise.all(
inputFiles.map(file => IronPdf.PdfDocument.fromFile(file))
);
// Combine into one document, preserving page order
const mergedPdf = await IronPdf.PdfDocument.merge(pdfDocs);
// Write the result to disk
await mergedPdf.toFile(outputFilePath);
console.log(`Merged PDF saved to ${outputFilePath}`);
}
(async () => {
const inputFiles = ['report-jan.pdf', 'report-feb.pdf', 'report-mar.pdf'];
await mergePdfs('quarterly-report.pdf', inputFiles);
})();Promise.all()은 소스 파일을 한 번에 하나씩이 아니라 병렬로 로드하며, 이는 대용량 컬렉션을 처리할 때 중요합니다. merge() 호출은 문서를 배열 순서대로 연결하므로, 출력에 표시되기를 원하는 순서대로 파일을 배열에 배치하십시오.
fromFile() 메서드는 스크립트 파일 자체를 기준으로 한 상대 경로를 해결하지 않습니다.코드의 각 부분은 어떤 역할을 하나요?
PdfDocument.fromFile(): 디스크에서 PDF를 읽어와PdfDocument객체를 반환합니다. 전체 메서드 시그니처는 IronPDF for Node.js API 레퍼런스를 참조하세요.Promise.all(): 모든 파일 로드 작업을 동시에 처리하여, 여러 문서를 병합할 때의 총 로드 시간을 단축합니다. 이 패턴은 멀티 스레드 및 동시 PDF 생성 시나리오에도 적합합니다.PdfDocument.merge(): 로드된 문서 배열을 단일PdfDocument로 연결하며, 각 소스의 모든 서식, 이미지 및 내장된 콘텐츠를 그대로 유지합니다.toFile(): 병합된 문서를 지정된 경로에 저장합니다. 필요할 경우 출력 파일 크기를 줄이기 위해 이를 PDF 압축과 결합하세요.
각 PDF에서 특정 페이지 병합하는 방법은 무엇입니까?
모든 소스 문서의 모든 페이지를 전달하는 것이 항상 목표는 아닙니다. 각 입력 파일에서 특정 페이지 범위를 병합하려면, 문서를 merge()로 전달하기 전에 원하는 페이지를 추출하십시오.
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-specific-pages.js
const IronPdf = require('ironpdf');
// Each entry specifies a file and the range of pages to include (zero-indexed)
const pageRanges = [
{ file: 'contract.pdf', startPage: 0, endPage: 2 },
{ file: 'appendix.pdf', startPage: 0, endPage: 0 },
{ file: 'signature.pdf', startPage: 0, endPage: 0 },
];
async function mergeSpecificPages(outputFile, ranges) {
const pdfsToMerge = [];
for (const range of ranges) {
const pdf = await IronPdf.PdfDocument.fromFile(range.file);
// extractPages returns a new PdfDocument with only the specified page range
const pages = pdf.extractPages(range.startPage, range.endPage);
pdfsToMerge.push(pages);
}
const merged = await IronPdf.PdfDocument.merge(pdfsToMerge);
await merged.toFile(outputFile);
}
mergeSpecificPages('assembled-contract.pdf', pageRanges);//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-specific-pages.js
const IronPdf = require('ironpdf');
// Each entry specifies a file and the range of pages to include (zero-indexed)
const pageRanges = [
{ file: 'contract.pdf', startPage: 0, endPage: 2 },
{ file: 'appendix.pdf', startPage: 0, endPage: 0 },
{ file: 'signature.pdf', startPage: 0, endPage: 0 },
];
async function mergeSpecificPages(outputFile, ranges) {
const pdfsToMerge = [];
for (const range of ranges) {
const pdf = await IronPdf.PdfDocument.fromFile(range.file);
// extractPages returns a new PdfDocument with only the specified page range
const pages = pdf.extractPages(range.startPage, range.endPage);
pdfsToMerge.push(pages);
}
const merged = await IronPdf.PdfDocument.merge(pdfsToMerge);
await merged.toFile(outputFile);
}
mergeSpecificPages('assembled-contract.pdf', pageRanges);extractPages(startPage, endPage)는 0을 기준으로 하는 페이지 인덱스를 허용합니다. 0, 0을 전달하면 첫 페이지만 추출되며, 0, 2을 전달하면 처음 세 페이지가 추출됩니다. 이 루프는 ranges에 나타나는 순서대로 페이지 범위 문서 배열을 생성한 다음, merge()에서 이를 연결하여 최종 출력을 만듭니다.
이 패턴은 서명 페이지, 부록 및 별도 파일에 저장된 표지 등을 포함하여 계약을 조립할 때 유용합니다. 디스크에 파일을 중복 저장하지 않고 각 소스에서 중요 한 페이지만 수집할 수 있습니다.
병합된 PDF에 헤더와 푸터를 추가하는 방법은 무엇입니까?
병합 후, 결과 문서의 addHtmlHeader() 및 addHtmlFooter()을 호출하여 모든 페이지에 일관된 머리글과 바닥글을 적용하십시오. 이 메서드는 HTML 문자열과 옵션 객체를 허용합니다.
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-with-headers-footers.js
const IronPdf = require('ironpdf');
async function mergeWithHeadersFooters(inputFiles, outputFile) {
const docs = await Promise.all(
inputFiles.map(f => IronPdf.PdfDocument.fromFile(f))
);
const mergedPdf = await IronPdf.PdfDocument.merge(docs);
// Apply a styled header to every page
await mergedPdf.addHtmlHeader('<h3 style="color:#333;">Quarterly Report</h3>', {
height: 25,
drawDividerLine: true,
});
// Apply a page-numbering footer
await mergedPdf.addHtmlFooter('<p style="font-size:10px;">Page {page} of {total-pages}</p>', {
height: 20,
drawDividerLine: true,
});
await mergedPdf.toFile(outputFile);
}
mergeWithHeadersFooters(['q1.pdf', 'q2.pdf', 'q3.pdf'], 'annual-report.pdf');//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-with-headers-footers.js
const IronPdf = require('ironpdf');
async function mergeWithHeadersFooters(inputFiles, outputFile) {
const docs = await Promise.all(
inputFiles.map(f => IronPdf.PdfDocument.fromFile(f))
);
const mergedPdf = await IronPdf.PdfDocument.merge(docs);
// Apply a styled header to every page
await mergedPdf.addHtmlHeader('<h3 style="color:#333;">Quarterly Report</h3>', {
height: 25,
drawDividerLine: true,
});
// Apply a page-numbering footer
await mergedPdf.addHtmlFooter('<p style="font-size:10px;">Page {page} of {total-pages}</p>', {
height: 20,
drawDividerLine: true,
});
await mergedPdf.toFile(outputFile);
}
mergeWithHeadersFooters(['q1.pdf', 'q2.pdf', 'q3.pdf'], 'annual-report.pdf');{page} 및 {total-pages} 자리 표시자는 병합된 문서의 페이지 수를 기준으로 렌더링 시점에 해결됩니다. drawDividerLine: true을 사용하여 헤더나 푸터를 페이지 콘텐츠와 시각적으로 구분하십시오.
병합 후 헤더와 푸터를 적용하면 합친 문서의 모든 페이지에 동일한 처리가 이루어져, 소스 파일에 관계없이 동일한 처리가 이루어집니다. 전체 헤더와 푸터 구성 옵션은 HTML 헤더와 푸터 예제를 참조하세요.
병합된 PDF를 비밀번호로 보호하는 방법은 무엇입니까?
병합 후 보안 옵션 객체를 사용하여 saveAs()을 호출하여 암호 보호 및 권한 제한을 적용하십시오. 이는 결합된 문서에 대한 무단 액세스를 방지합니다.
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-with-security.js
const IronPdf = require('ironpdf');
async function mergeWithSecurity(inputFiles, outputFile) {
const docs = await Promise.all(
inputFiles.map(f => IronPdf.PdfDocument.fromFile(f))
);
const mergedPdf = await IronPdf.PdfDocument.merge(docs);
// Restrict the merged document to print-only access
await mergedPdf.saveAs(outputFile, {
userPassword: 'viewerpass',
ownerPassword: 'adminpass',
allowUserAnnotations: false,
allowUserCopyPasteContent: false,
allowUserFormData: false,
allowUserPrinting: true,
});
}
mergeWithSecurity(['invoice-1.pdf', 'invoice-2.pdf'], 'secured-invoices.pdf');//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-with-security.js
const IronPdf = require('ironpdf');
async function mergeWithSecurity(inputFiles, outputFile) {
const docs = await Promise.all(
inputFiles.map(f => IronPdf.PdfDocument.fromFile(f))
);
const mergedPdf = await IronPdf.PdfDocument.merge(docs);
// Restrict the merged document to print-only access
await mergedPdf.saveAs(outputFile, {
userPassword: 'viewerpass',
ownerPassword: 'adminpass',
allowUserAnnotations: false,
allowUserCopyPasteContent: false,
allowUserFormData: false,
allowUserPrinting: true,
});
}
mergeWithSecurity(['invoice-1.pdf', 'invoice-2.pdf'], 'secured-invoices.pdf');문서를 열려면 userPassword이 필요합니다; ownerPassword는 권한 설정 자체를 제어합니다. 다른 권한 플래그를 비활성화한 상태에서 allowUserPrinting: true을 설정하면 수신자가 문서를 PRINT할 수는 있지만 편집, 복사 및 주석 달기는 할 수 없게 됩니다. 사용 가능한 권한 플래그의 전체 목록은 IronPDF Node.js API 레퍼런스를 참조하세요.
fromFile()를 사용하여 불러올 때 각 문서의 암호 해독 암호를 제공하십시오. 비밀번호를 제공하지 않고 암호화된 문서를 병합하려고 하면 오류가 발생합니다.PDF 병합과 디지털 서명 추가하는 방법은 무엇입니까?
PDF를 병합한 후 즉시 결과에 서명을 하면, 모든 소스 콘텐츠를 포함하는 단일 서명된 문서를 생성합니다. 결합된 출력에 디지털 인증서를 첨부하려면 merge() 뒤에 applySignature()를 적용하십시오.
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-with-signature.js
const IronPdf = require('ironpdf');
async function mergeAndSign(inputFiles, outputFile, pfxPath, pfxPassword) {
const docs = await Promise.all(
inputFiles.map(f => IronPdf.PdfDocument.fromFile(f))
);
const mergedPdf = await IronPdf.PdfDocument.merge(docs);
// Attach a digital signature using a PFX certificate
await mergedPdf.applySignature(pfxPath, pfxPassword);
await mergedPdf.toFile(outputFile);
}
mergeAndSign(
['section-a.pdf', 'section-b.pdf'],
'signed-report.pdf',
'certificate.pfx',
'certpass'
);//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-merge-pdf/merge-with-signature.js
const IronPdf = require('ironpdf');
async function mergeAndSign(inputFiles, outputFile, pfxPath, pfxPassword) {
const docs = await Promise.all(
inputFiles.map(f => IronPdf.PdfDocument.fromFile(f))
);
const mergedPdf = await IronPdf.PdfDocument.merge(docs);
// Attach a digital signature using a PFX certificate
await mergedPdf.applySignature(pfxPath, pfxPassword);
await mergedPdf.toFile(outputFile);
}
mergeAndSign(
['section-a.pdf', 'section-b.pdf'],
'signed-report.pdf',
'certificate.pfx',
'certpass'
);applySignature() 메서드는 인증서를 PDF 메타데이터에 삽입하여 독자가 문서의 무결성을 확인할 수 있도록 합니다. 이 워크플로는 여러 섹션이 결합된 후 배포 전에 공동 서명되는 계약 조립 파이프라인에서 일반적입니다. 인증서 기반 서명의 전체 순서를 보려면, 디지털 서명 예제를 참조하세요.
일반적인 PDF 병합 오류를 해결하는 방법은 무엇입니까?
대부분의 병합 중 오류는 네 가지 범주로 분류됩니다: 누락된 파일, 메모리 고갈, 손상된 입력 및 권한 문제. 아래 표에서는 가장 빈번한 원인과 각각에 대해 어떻게 해결할 수 있는지를 나열합니다.
| 오류 | 가능성 있는 원인 | 해결책 |
|---|---|---|
| 파일을 찾을 수 없음 | 잘못된 경로 또는 작업 디렉터리 불일치 | 절대 경로를 사용하거나 프로세스 작업 디렉터리를 확인하세요. |
| JavaScript 힙 메모리 부족 | 동시에 많은 대형 PDF 로드 | Node.js 메모리 증가: node --max-old-space-size=4096 script.js |
| 잘못되거나 손상된 PDF | 소스 파일이 손상되었거나 유효한 PDF가 아님 | 처리 전에 PDF 리더로 소스 파일을 유효성 검사하세요. |
| 권한이 거부되었습니다 | 입력에 대한 읽기 권한이 없거나 출력 디렉터리에 대한 쓰기 권한이 없음 | 운영 체제에서 파일 및 디렉터리 권한을 확인하세요. |
| 암호화된 소스 PDF | 입력 PDF를 열기 위해 비밀번호가 필요합니다 | fromFile()의 두 번째 인수로 비밀번호를 전달하세요. |
환경에 특정한 설정 문제에 대해, IronPDF 변경 로그에 문서화된 알려진 문제 및 수정을 확인하세요. 위의 표를 확인한 후에도 문제가 지속되면, merge 호출을 try-catch 블록으로 감싸서 라이브러리에서 발생하는 전체 오류 메시지를 표시하십시오.
fromFile()를 호출하기 전에 입력 배열에 포함된 모든 파일 경로가 존재하는지 항상 확인하십시오. 단 하나의 파일이 누락되어도 전체 Promise.all() 호출이 거부되어 병합이 취소됩니다.Node.js 자체에는 사전 경로 유효성 검사를 위한 유용한 도구가 제공됩니다. Node.js의 fs.promises.access 메서드를 사용하면 파일을 IronPDF로 전달하기 전에 파일이 읽을 수 있는지 확인할 수 있습니다. 커뮤니티 개발자가 유사한 병합 오류 시나리오를 어떻게 처리하는지에 대한 질문이 있다면, Node.js에서 PDF 병합에 대한 Stack Overflow 스레드가 추가적인 문맥을 제공합니다.
Node.js에서 PDF 병합을 위한 다음 단계는 무엇입니까?
위의 예제는 가장 일반적인 병합 시나리오를 다룹니다: 기본 파일 결합, 페이지 범위 선택, 헤더 및 푸터 삽입, 비밀번호 보호 및 디지털 서명. IronPDF는 또한 병합된 페이지 전반에 걸쳐 PDF 폼 관리를 지원하며, 새로운 콘텐츠를 병합 문서에 스탬프 찍기 및 최종 출력에서 미리 보기 생성을 위해 래스터화된 이미지 생성도 지원합니다.
무료 30일 체험을 시작하세요 워터마크 없이 병합을 테스트하거나, 라이선싱 옵션 보기 사용 준비가 되었다면 이전 단계를 참조하세요.
IronPDF로 무엇을 할 수 있는지 준비되셨습니까? 전체 API 워크스루 및 추가 가이드의 IronPDF for Node.js 문서를 방문하세요.
자주 묻는 질문
Node.js에서 여러 PDF 파일을 하나로 병합하려면 어떻게 해야 하나요?
PdfDocument.fromFile()을 사용하여 각 파일을 불러오고, 결과를 배열에 수집하고, 배열을 PdfDocument.merge()에 전달한 후 toFile()로 출력을 저장하세요. 세 개 이상의 문서를 병합할 때는 Promise.all()을 사용하여 파일을 병렬로 불러옵니다.
IronPDF는 PDF를 병합할 때 서식을 보존합니까?
네. IronPDF는 각 소스 문서의 글꼴, 이미지, 임베디드 양식, 페이지 기하학을 보존합니다. 병합된 출력은 입력 배열에 나타나는 소스 파일 순서대로 각 페이지의 원래 레이아웃을 유지합니다.
각 PDF에서 특정 페이지만 병합하려면 어떻게 하나요?
extractPages(startPage, endPage)를 각 로드된 문서에 호출한 후 PdfDocument.merge()에 전달하십시오. 페이지 인덱스는 0부터 시작하므로 첫 번째 페이지는 인덱스 0입니다. 반환된 문서는 지정된 범위만 포함하고 있습니다.
병합된 PDF에 머리글과 바닥글을 추가할 수 있나요?
네. 병합 후, 결과 문서에서 addHtmlHeader()와 addHtmlFooter()를 호출하세요. 두 메서드 모두 HTML 문자열과 옵션 객체를 인수로 받습니다. 자동 페이지 번호 매기기를 위해 {page} 및 {total-pages} 플레이스홀더를 사용하세요.
Node.js에서 병합된 PDF에 비밀번호를 설정하려면 어떻게 해야 하나요?
saveAs()를 호출할 때 userPassword, ownerPassword 및 allowUserPrinting과 같은 권한 플래그를 지정하는 보안 옵션 객체를 사용합니다. 문서를 열려면 userPassword가 필요하고, ownerPassword는 권한 설정을 제어합니다.
파일을 찾을 수 없다는 오류로 병합에 실패하면 어떻게 해야 합니까?
모든 입력 파일 경로가 Node.js 프로세스 작업 디렉토리에 상대적이거나 절대 경로로 전환되었는지 확인하십시오. 각 파일을 읽기 가능 여부를 확인하려면 fs.promises.access()를 사용하고 PdfDocument.fromFile()을 호출하기 전에 확인하십시오.
소스 PDF 중 하나가 암호화된 경우 어떻게 되나요?
암호화된 PDF를 로드하려 할 때 암호를 제공하지 않으면 오류가 발생하며 전체 Promise.all() 호출이 거부됩니다. 병합하기 전에 fromFile()의 두 번째 인수로 문서 비밀번호를 제공합니다.
IronPDF로 PDF를 병합하려면 라이선스 키가 필요합니까?
IronPDF는 개발 중 라이선스 키 없이 작동하지만 출력 문서에 체험용 워터마크가 포함됩니다. 워터마크를 제거하고 전체 기능을 활성화하려면 실 배포 전에 유효한 라이선스 키를 구성하십시오.





