본문 바로가기
nest.js

[nest.js] pdf-lib 를 이용하여 기존 PDF 파일에서 특정 페이지들만 새 PDF 파일로 저장 테스트 진행

by Hwoarang757 2025. 6. 23.

1. 패키지를 설치 하였습니다.

$ npm install pdf-lib

또는

$ yarn add pdf-lib

 

 

2. Service 부분에 테스트 코드를 작성 진행 하였습니다.

import { Injectable, Logger, NotFoundException } from '@nestjs/common';
//
import { PDFDocument } from 'pdf-lib'
import * as fs from 'fs/promises';

@Injectable()
export class TestService {

	private readonly logger = new Logger(TestService.name);

    async pdfSplitTest() : Promise<boolean> {
      
      try {
        // 1. 기존 PDF 파일 로드 
        const prevPdfBytes = await fs.readFile("F:/TEST_ORIGINAL.pdf");
        const pdfDoc = await PDFDocument.load(prevPdfBytes);

        //2. 새 PDF 문서 생성
        const rangePdfDoc = await PDFDocument.create();

        const startPage = 16;
        const endPage = 32;

        const pages = Array.from({length : endPage - startPage  + 1}
                                ,(_ , index) => startPage + index);

        
        //3. 지정된 페이지 범위 복사 및 새 문서에 추가
        const pageIndices = pages.map(num => num -1);
        const copiedPages = await rangePdfDoc.copyPages(pdfDoc , pageIndices);
        copiedPages.forEach(page => rangePdfDoc.addPage(page));
        
        //4. 새 PDF 저장 , 객체 압축 활성화 진행
        const pdfBytes = await rangePdfDoc.save({ useObjectStreams : true });
        await fs.writeFile("F:/TEST_RANGE.pdf" , pdfBytes);
        
      } catch(exception) {
        this.logger.error(exception);
        return false;
      }

      return true;
    }

}