Developers often need to break down large PDF files into smaller, more manageable sections. With the GroupDocs.Merger Cloud SDK for Node.JS, splitting a PDF into multiple parts becomes straightforward, as the cloud service handles the heavy lifting while you concentrate on your application logic. This guide provides a full working example, shows how to perform the same task via cURL, and explains the configuration options that let you fine‑tune the split operation.
Split PDF Into Multiple PDF in Node.JS - Complete Code Example
This example demonstrates how to split a PDF into multiple PDF files using GroupDocs.Merger Cloud SDK for Node.JS.
const fs = require('fs');
const path = require('path');
const GroupDocsMergerCloud = require('@groupdocs/merger-cloud');
// ---------- Set up API credentials ----------
const client = new GroupDocsMergerCloud.ApiClient();
client.appSid = 'YOUR_APP_SID';
client.appKey = 'YOUR_APP_KEY';
// ---------- Initialize API instances ----------
const mergerApi = new GroupDocsMergerCloud.MergerApi(client);
const storageApi = new GroupDocsMergerCloud.StorageApi(client);
// ---------- Helper to upload a local file to cloud storage ----------
async function uploadFile(localPath, cloudPath) {
const fileData = fs.readFileSync(localPath);
const uploadRequest = new GroupDocsMergerCloud.UploadFileRequest({
path: cloudPath,
file: fileData
});
await storageApi.uploadFile(uploadRequest);
}
// ---------- Helper to download a cloud file to local storage ----------
async function downloadFile(cloudPath, localPath) {
const downloadRequest = new GroupDocsMergerCloud.DownloadFileRequest({ path: cloudPath });
const response = await storageApi.downloadFile(downloadRequest);
fs.writeFileSync(localPath, response);
}
// ---------- Main execution ----------
(async () => {
try {
// 1. Upload source PDF to cloud storage
const localInputPdf = path.resolve(__dirname, 'input.pdf'); // local source PDF
const cloudInputPdf = 'input/input.pdf'; // cloud path
await uploadFile(localInputPdf, cloudInputPdf);
console.log('Uploaded PDF to cloud storage.');
// 2. Configure split options (example: split into two parts: pages 1‑2 and 3‑5)
const splitOptions = new GroupDocsMergerCloud.SplitOptions({
pages: ['1-2', '3-5'] // page ranges to split
});
// 3. Build split request
const splitRequest = new GroupDocsMergerCloud.SplitDocumentRequest({
fileInfo: new GroupDocsMergerCloud.FileInfo({ filePath: cloudInputPdf }),
options: splitOptions
});
// 4. Execute split operation
const splitResult = await mergerApi.splitDocument(splitRequest);
console.log(`Split operation completed. ${splitResult.length} parts generated.`);
// 5. Download each split part and save locally
for (let i = 0; i < splitResult.length; i++) {
const partInfo = splitResult[i];
const localOutputPath = path.resolve(__dirname, `output_part_${i + 1}.pdf`);
await downloadFile(partInfo.path, localOutputPath);
console.log(`Saved split part ${i + 1} to ${localOutputPath}`);
}
// 6. (Optional) Clean up cloud storage – delete uploaded source file
const deleteRequest = new GroupDocsMergerCloud.DeleteFileRequest({ path: cloudInputPdf });
await storageApi.deleteFile(deleteRequest);
console.log('Cleaned up source file from cloud storage.');
} catch (error) {
console.error('Error during PDF split process:', error);
}
})();
참고: 이 코드 예제는 핵심 기능을 보여줍니다. 프로젝트에 사용하기 전에 파일 경로와 구성 값을 실제 환경에 맞게 업데이트하고, 모든 필수 종속성이 올바르게 설치되었는지 확인하며, 개발 환경에서 충분히 테스트하십시오. 문제가 발생하면 공식 문서를 참조하거나 지원 팀에 문의하십시오.
cURL을 사용한 REST API로 PDF 분할
순수 REST 방식을 선호한다면, 동일한 분할 작업을 cURL 명령으로 수행할 수 있습니다. 아래 단계에서는 액세스 토큰을 얻고, 원본 PDF를 업로드하고, 분할을 실행한 뒤 각 부분을 다운로드하는 방법을 보여줍니다.
# 1. Get an access token (replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET)
curl -X POST "https://api.groupdocs.cloud/v2.0/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
# 2. Upload the source PDF (replace YOUR_ACCESS_TOKEN and adjust paths)
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/input.pdf" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/pdf" \
--data-binary @./input.pdf
# 3. Execute the split operation (pages 1-2 and 3-5)
curl -X POST "https://api.groupdocs.cloud/v2.0/merger/split" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"fileInfo": { "filePath": "input.pdf" },
"options": { "pages": ["1-2","3-5"] }
}'
# 4. Download each generated part (example for part 1)
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/output_part_1.pdf" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o ./output_part_1.pdf
엔드포인트 및 매개변수의 전체 목록은 공식 API 문서를 참조하십시오.
Node.JS에서 PDF를 여러 PDF로 분할하는 방법 작동 원리
흐름을 이해하면 코드를 보다 복잡한 시나리오에 맞게 조정하는 데 도움이 됩니다.
- API 클라이언트 초기화 -
new GroupDocsMergerCloud.ApiClient()는 App SID와 App Key를 보유하는 클라이언트를 생성합니다.
const client = new GroupDocsMergerCloud.ApiClient();
client.appSid = 'YOUR_APP_SID';
client.appKey = 'YOUR_APP_KEY';
- 소스 파일 업로드 - 헬퍼
uploadFile은 로컬 PDF를 읽고storageApi.uploadFile을 사용하여 클라우드 스토리지에 전송합니다.
await uploadFile(localInputPdf, cloudInputPdf);
- 분할 옵션 구성 -
new GroupDocsMergerCloud.SplitOptions({ pages: ['1-2', '3-5'] })은 서비스에 추출할 페이지 범위를 알려줍니다.
const splitOptions = new GroupDocsMergerCloud.SplitOptions({
pages: ['1-2', '3-5']
});
- 분할 요청 전송 -
mergerApi.splitDocument(splitRequest)는 요청을 전송하고 생성된 각 부분에 대한 정보를 포함하는 배열을 반환합니다.
const splitResult = await mergerApi.splitDocument(splitRequest);
- 결과 다운로드 - 루프는
splitResult를 반복하면서 각 파트에 대해downloadFile을 호출하고 로컬에 저장합니다.
for (let i = 0; i < splitResult.length; i++) {
const partInfo = splitResult[i];
await downloadFile(partInfo.path, localOutputPath);
}
각 클래스와 메서드에 대한 자세한 내용은 API 참조를 참조하십시오.
필수 조건 및 설정
시작하기 전에 다음 항목이 있는지 확인하십시오:
- Node.js 14 이상 설치됨.
- 유효한 App SID와 App Key가 있는 GroupDocs Cloud 계정.
- API 호출을 위한 인터넷 액세스.
npm을 통해 SDK를 설치하고 최신 패키지를 다운로드하십시오:
npm install groupdocs-merger-cloud
바이너리를 직접 다운로드 페이지에서 가져올 수도 있습니다.
분할 옵션 미세 조정
SplitOptions 객체는 조정할 수 있는 여러 속성을 제공합니다:
- pages - 페이지 범위 배열 (예:
['1-2','3-5']). 이것은 예제에서 사용되는 핵심 설정입니다. - outputPath - 분할 파일이 클라우드 스토리지에 저장될 선택적 폴더입니다.
- preserveMetadata -
true로 설정하면 원본 문서 메타데이터가 각 파트에 복사됩니다. 자세한 옵션은 API reference를 참조하세요.
이러한 값을 조정하면 각 결과 PDF의 크기, 이름 및 메타데이터를 제어할 수 있습니다.
결론
Node.JS에서 PDF를 여러 PDF로 분할하는 작업은 GroupDocs.Merger Cloud SDK for Node.JS를 사용하면 간단해집니다. SDK는 파일 업로드, 페이지 범위 선택 및 결과 검색을 처리하여 출력물을 워크플로에 통합하는 데 집중할 수 있게 해줍니다. App SID와 App Key를 안전하게 보관하고, 프로덕션 배포 시 상용 라이선스 사용을 고려하십시오. 가격 정보는 제품 페이지에서 확인할 수 있으며, 임시 라이선스 페이지에서 임시 라이선스를 얻을 수 있습니다. 이 가이드의 코드, cURL 예제 및 구성 팁을 통해 Node.JS 애플리케이션에서 강력한 PDF 분할을 구현할 준비가 되었습니다.
FAQs
Node.JS에서 사용자 정의 페이지 범위를 사용하여 PDF를 여러 PDF로 분할하려면 어떻게 해야 하나요?
SplitOptions의pages속성을 사용하여 필요한 범위를 정의하십시오. 예:['1-3','4-6']. SDK는 각 범위마다 별도의 PDF를 생성합니다.PDF를 클라우드 스토리지에 영구적으로 저장하지 않고 분할할 수 있나요?
예. 원본 파일을 업로드하고 분할을 완료한 후, 예제에 표시된 대로storageApi.deleteFile을 사용하여 원본 파일을 삭제할 수 있습니다.프로덕션에서 split 기능을 사용하려면 유료 라이선스가 필요합니까?
프로덕션 사용에는 상업용 라이선스가 필요합니다. 가격 정보를 확인하려면 제품 페이지를 방문하고 평가를 위해 임시 라이선스 페이지에서 임시 라이선스를 얻으세요.
