pdf-lib npmモジュールは、Node.jsを使用してPDFを作成および編集するための優れたツールです。PuppeteerはHTMLから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-libのキラー機能は、新しいPDFを作成するだけでなく、既存のPDFを変更できることです。たとえば、2つのPDFがあるとします。1つは電子書籍の表紙を含み、もう1つは電子書籍のコンテンツを含みます。2つのPDFをマージする方法は?前回の電子書籍(Mastering Async / Await)でILovePDF API を使用しましたが、pdf-libを使用すると、Node.jsでこのタスクを簡単に実行できます。
2つのがありPDFファイルは、次のとおりです。cover.pdf
とpage-30-31.pdf
。PDF-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());
}
マージ後の効果を下の図に示します。
ページ番号を追加
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を検索しようとすると、より良い解決策を見つけることができます。