pdf-libを使用してNode.jsでPDFを処理する

pdf-lib npmモジュールは、Node.jsを使用してPDFを作成および編集するための優れたツールです。PuppeteerHTMLからPDFを生成できる優れたツールですが、残念ながら、私の経験ではCSSでの印刷レイアウトに対するブラウザーのサポートあまりよくありません。pdf-libモジュールを使用すると、PDFを非常に細かく制御できます。PDFのマージ、ページ番号の追加、透かし、PDFの分割、およびILovePDF APIを使用してPDFファイル処理するために使用できるその他の関数に使用できます

はじめに

pdf-libを使用して簡単なPDFドキュメントを作成しましょう。このPDF文書は1ページのみで、ページの中央にMastering JSのアイコンが表示されます。

const { PDFDocument } = require('pdf-lib');
const fs = require('fs');

run().catch(err => console.log(err));

async function run() {
  // Create a new document and add a new page
  const doc = await PDFDocument.create();
  const page = doc.addPage();

  // Load the image and store it as a Node.js buffer in memory
  let img = fs.readFileSync('./logo.png');
  img = await doc.embedPng(img);

  // Draw the image on the center of the page
  const { width, height } = img.scale(1);
  page.drawImage(img, {
    x: page.getWidth() / 2 - width / 2,
    y: page.getHeight() / 2 - height / 2
  });

  // Write the PDF to a file
  fs.writeFileSync('./test.pdf', await doc.save());
}

上記のスクリプトを実行すると、次のPDFが生成されます。pdf-libの使用は非常に単純であり、いくつかの落とし穴があります。注意PDFDocument#embedPng()してPDFDocument#save()戻るPromise必要があるため、使用する必要がありますawait

シンプルなPDF

PDFを結合

pdf-libのキラー機能は、新しいPDFを作成するだけでなく、既存のPDFを変更できることです。たとえば、2つのPDFがあるとします。1つは電子書籍の表紙を含み、もう1つは電子書籍のコンテンツを含みます。2つのPDFをマージする方法は?前回の電子書籍(Mastering Async / Await)でILovePDF API 使用しましたが、pdf-libを使用すると、Node.jsでこのタスクを簡単に実行できます。

2つのがありPDFファイルは、次のとおりです。cover.pdfpage-30-31.pdfPDF-libのPDFマージ2を使用して、次のスクリプト、test.pdfファイル。

const { PDFDocument } = require('pdf-lib');
const fs = require('fs');

run().catch(err => console.log(err));

async function run() {
  // Load cover and content pdfs
  const cover = await PDFDocument.load(fs.readFileSync('./cover.pdf'));
  const content = await PDFDocument.load(fs.readFileSync('./page-30-31.pdf'));

  // Create a new document
  const doc = await PDFDocument.create();

  // Add the cover to the new doc
  const [coverPage] = await doc.copyPages(cover, [0]);
  doc.addPage(coverPage);

  // Add individual content pages
  const contentPages = await doc.copyPages(content, content.getPageIndices());
  for (const page of contentPages) {
    doc.addPage(page);
  }

  // Write the PDF to a file
  fs.writeFileSync('./test.pdf', await doc.save());
}

マージ後の効果を下の図に示します。

PDFを結合

ページ番号を追加

Puppeteerを使用してHTMLからPDFを生成する際の最大の問題の1つは、ページ番号を追加する手間ですページ番号を追加するのは簡単に思えますが、CSS印刷レイアウトではこの機能を正しく実装できません。あなたは見ることができ、私はオフセットハードコードピクセルでループのために書いたものをページには、正しく表示することができます。

例えば、マスタリング非同期/待って、フロント4のPDFをページしませんでした:./content.pdf次のスクリプトは、PDFの各ページにページを追加します。

const { PDFDocument, StandardFonts, rgb } = require('pdf-lib');
const fs = require('fs');

run().catch(err => console.log(err));

async function run() {
  const content = await PDFDocument.load(fs.readFileSync('./content.pdf'));

  // Add a font to the doc
  const helveticaFont = await content.embedFont(StandardFonts.Helvetica);

  // Draw a number at the bottom of each page.
  // Note that the bottom of the page is `y = 0`, not the top
  const pages = await content.getPages();
  for (const [i, page] of Object.entries(pages)) {
    page.drawText(`${+i + 1}`, {
      x: page.getWidth() / 2,
      y: 10,
      size: 15,
      font: helveticaFont,
      color: rgb(0, 0, 0)
    });
  }

  // Write the PDF to a file
  fs.writeFileSync('./test.pdf', await content.save());
}

ページ番号を追加した後の効果を下の図に示します。
ページ番号を追加

続行するには

Node.jsエコシステムには、考えられるほとんどすべての問題を解決できる優れたライブラリが数多くあります。PDF-libのモジュールあなたがPDFを処理することができます、シャープは、画像とほぼすべてを処理することができますPKG別の実行可能ファイルにノードプロジェクトバンドルなど。問題を解決するためのオンラインAPIを探す前に、最初にnpmを検索しようとすると、より良い解決策を見つけることができます。

原文:pdf-libを使用してNode.jsでPDFを操作する

おすすめ

転載: www.cnblogs.com/tianliupingzong/p/12703007.html