Node.js에서 PDF 페이지를 이미지로 변환하는 방법
이 기사에서는 Node.js를 사용하여 PDF 페이지를 이미지로 변환하는 방법을 다룹니다. 이는 축소판을 생성하거나 PDF 파일에서 시각적 콘텐츠를 추출하는 데 유용할 수 있습니다. pdfjs-dist 라이브러리를 사용하여 PDF 페이지를 로드 및 렌더링하고 캔버스를 사용하여 이미지 버퍼를 생성합니다.
전제조건
시작하기 전에 필수 패키지를 설치해야 합니다:
npm 설치 pdfjs-dist 캔버스
PDF 페이지를 이미지로 변환하고 로컬에 저장하기 위한 코드:
const fs = require('fs'); const path = require('path'); const pdfjs = require('pdfjs-dist/legacy/build/pdf.js'); const Canvas = require('canvas'); /** * Converts a PDF to images by rendering each page and saving them to a local directory. * * @param {Buffer} pdfBuffer - The PDF file as a buffer. * @param {string} outputDir - The directory where images will be saved. * @returns {Promise<void>} Resolves when all images are saved. */ async function convertPdfToImages(pdfBuffer, outputDir) { try { // Ensure the output directory exists if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }); } // Load the original PDF using pdf.js const loadingTask = pdfjs.getDocument({ data: pdfBuffer }); const pdfDocument = await loadingTask.promise; // Loop through each page of the PDF for (let i = 1; i <= pdfDocument.numPages; i++) { const page = await pdfDocument.getPage(i); // Render the page as an image and save it const imageBuffer = await renderPageToImage(page); // Save the image to the output directory const imagePath = path.join(outputDir, `page_${i}.jpg`); fs.writeFileSync(imagePath, imageBuffer); console.log(`Saved: ${imagePath}`); } } catch (error) { console.error('Error converting PDF to images:', error); } } /** * Renders a single PDF page to an image buffer. * * @param {PDFPageProxy} page - The PDF.js page object. * @returns {Promise<Buffer>} The image as a buffer (JPEG format). */ async function renderPageToImage(page) { // Scale the page to 2x for a higher quality image output const viewport = page.getViewport({ scale: 2.0 }); const canvas = Canvas.createCanvas(viewport.width, viewport.height); const context = canvas.getContext('2d'); const renderContext = { canvasContext: context, viewport: viewport, }; // Render the PDF page to the canvas await page.render(renderContext).promise; // Convert the canvas content to a JPEG image buffer and return it return canvas.toBuffer('image/jpeg'); } // Example usage: // const pdfBuffer = fs.readFileSync('sample.pdf'); // convertPdfToImages(pdfBuffer, './output_images');
로그인 후 복사
코드 설명
- PDF 로드: 우리는 pdfjs-dist를 사용하여 버퍼에서 PDF 파일을 로드합니다.
const loadingTask = pdfjs.getDocument({ data: pdfBuffer }); const pdfDocument = await loadingTask.promise;
로그인 후 복사
- 각 페이지 렌더링: PDF의 각 페이지에 대해 pdfjs-dist의 getPage 및 render 메소드를 사용하여 캔버스에 렌더링합니다.
const page = await pdfDocument.getPage(pageNumber); const renderContext = { canvasContext: context, viewport: viewport, }; await page.render(renderContext).promise;
로그인 후 복사
- 로컬에 이미지 저장: 페이지가 캔버스에 렌더링되면 Node.js의 fs 모듈을 사용하여 이미지 버퍼를 JPEG 형식으로 저장합니다.
fs.writeFileSync(imagePath, imageBuffer);
로그인 후 복사
결론:
이 접근 방식은 PDF를 이미지로 변환하는 데 효율적으로 작동하므로 PDF 콘텐츠를 처리하거나 시각화할 수 있습니다. 고품질 이미지를 위해 캔버스 크기를 2배로 조정합니다. 이는 필요에 따라 쉽게 조정할 수 있습니다.
도움이 되었으면 좋겠습니다! 요구 사항에 따라 코드를 자유롭게 조정하세요.
위 내용은 Node.js에서 PDF 페이지를 이미지로 변환하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
2 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
Repo : 팀원을 부활시키는 방법
4 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD
R.E.P.O. 파일 저장 위치 : 어디에 있고 그것을 보호하는 방법은 무엇입니까?
3 몇 주 전
By DDD

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제
Gmail 이메일의 로그인 입구는 어디에 있나요?
7315
9


자바 튜토리얼
1625
14


Cakephp 튜토리얼
1348
46


라라벨 튜토리얼
1260
25


PHP 튜토리얼
1207
29

