1. はじめに
JavaScript で PDF を扱うためのライブラリを探していたところ、PDF-LIB というライブラリを見つけました。
試しに作成と編集を作ってみたので、その内容を共有します。
2. 作成と編集のサンプル
pdf.html と pdf.js を作成します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Generator</title>
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
</head>
<body>
<button id="generatePdfButton">PDFを生成</button><br>
<br>
<input type="file" id="uploadPdfInput" accept="application/pdf"><br>
<input type="text" id="newFileNameInput" placeholder="新しいファイル名"><br>
<button id="editPdfButton">PDFを編集</button>
<script type="module">
import { createPdf, modifyPdf } from './pdf.js';
document.getElementById('generatePdfButton').addEventListener('click', () => {
createPdf().catch(err => console.error(err));
});
document.getElementById('editPdfButton').addEventListener('click', async () => {
const fileInput = document.getElementById('uploadPdfInput');
if (fileInput.files.length === 0) {
alert('PDFファイルを選択してください。');
return;
}
const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();
const newFileName = newFileNameInput.value || 'edited.pdf';
modifyPdf(arrayBuffer, newFileName).catch(err => console.error(err));
});
</script>
</body>
</html>
PDFを作成で、createPdf() を呼び出します。作成ボタンをクリックするだけです。
PDFを編集で、modifyPdf() を呼び出します。
編集は、ファイルを選択して、新しいファイル名を入力して、ボタンをクリックします。
const { degrees, PDFDocument, StandardFonts, rgb } = PDFLib;
// PDFを作成
export async function createPdf() {
const pdfDoc = await PDFDocument.create();
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
const fontSize = 30;
page.drawText('Creating PDFs in JavaScript is awesome!', {
x: 50,
y: height - 4 * fontSize,
size: fontSize,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
const pdfBytes = await pdfDoc.save();
download(pdfBytes, 'output.pdf', 'application/pdf');
}
// PDFを編集
export async function modifyPdf(arrayBuffer, newFileName) {
const pdfDoc = await PDFDocument.load(arrayBuffer);
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
const pages = pdfDoc.getPages()
const firstPage = pages[0]
const { width, height } = firstPage.getSize()
firstPage.drawText('This text was added with JavaScript!', {
x: 5,
y: height / 2 + 300,
size: 50,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(-45),
})
const pdfBytes = await pdfDoc.save()
download(pdfBytes, newFileName, 'application/pdf');
}
// ダウンロード
function download(data, filename, type) {
const blob = new Blob([data], { type });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
drawText() は決め打ちになっているので引数で指定すれば自由に変更できます。
StandardFonts を使っているので、PDFFont を使えば変更可能ですかね?(試してない)。
3. まとめ
テンプレートのPDFファイルを用意して drawText() で指定箇所にテキストを追加する方法が取れるので埋め込むデータさえあれば、簡単にPDFを作成できそうな気がします。
今回の記事も、Github Copilot が8割くらい書いてくれました。
A. 参考サイト
PDF-LIB
オープンソースの JavaScript PDF エディター ライブラリ
JavaScriptでPDF出力を実装する方法
コメント