Node.js で PDF ページを画像に変換する方法

DDD
リリース: 2024-09-18 19:47:36
オリジナル
472 人が閲覧しました

How to Convert PDF Pages to Images in Node.js

この記事では、Node.js を使用して PDF ページを画像に変換する方法について説明します。これは、サムネイルを生成したり、PDF ファイルからビジュアル コンテンツを抽出したりする場合に役立ちます。 pdfjs-dist ライブラリを使用して PDF ページをロードしてレンダリングし、canvas を使用して画像バッファを作成します。

前提条件
始める前に、必要なパッケージをインストールする必要があります:

npm install pdfjs-dist Canvas

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');
ログイン後にコピー

コードの説明

  1. PDF をロードする: pdfjs-dist を使用して、バッファーから PDF ファイルをロードします。
const loadingTask = pdfjs.getDocument({ data: pdfBuffer });
const pdfDocument = await loadingTask.promise;
ログイン後にコピー
  1. 各ページのレンダリング: PDF 内の各ページについて、getPage と pdfjs-dist のレンダリング メソッドを使用してキャンバス上にレンダリングします。
const page = await pdfDocument.getPage(pageNumber);
const renderContext = {
  canvasContext: context,
  viewport: viewport,
};
await page.render(renderContext).promise;
ログイン後にコピー
  1. 画像をローカルに保存: ページがキャンバスにレンダリングされたら、Node.js の fs モジュールを使用して画像バッファーを JPEG 形式で保存します。
fs.writeFileSync(imagePath, imageBuffer);
ログイン後にコピー

結論:
このアプローチは PDF を画像に変換する場合に効率的に機能し、PDF コンテンツを処理または視覚化できるようになります。高品質の画像の場合、キャンバスを 2 倍に拡大縮小します。これは、ニーズに基づいて簡単に調整できます。

これがお役に立てば幸いです!要件に応じてコードを自由に調整してください。

以上がNode.js で PDF ページを画像に変換する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!