PDF にフォームを埋め込む

Uncategorized
240 words

PDFフォームとは?

PDFフォームは、PDFファイルの中に入力可能なフィールドが組み込まれているものです。

ユーザーがPDFフォームに情報を入力し印刷することが可能。

ブラウザーでも開いて入力することができるが、日本語入力ができない。

PDFフォームに日本語を入力したい場合は、Adobe Acrobat を使う。

環境

PDF-LIB を使う。

1
npm install pdf-lib

ソース

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { PDFDocument } from 'pdf-lib';

// PDFフォームを操作する非同期関数
async function pdfForm() {
// PDFを取得し、バイト配列として読み込む
const url = 'https://www.env.go.jp/content/900473371.pdf'
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())

// PDF内のページを取得
const pdfDoc = await PDFDocument.load(existingPdfBytes)
const pages = pdfDoc.getPages()
const firstPage = pages[0]

// テキストフィールドを作成し、ページに追加
const superheroField = form.createTextField('favorite.superhero')
superheroField.setText('One Punch Man')
superheroField.addToPage(firstPage, { x: 55, y: 640 })

// 変更を加えたPDFを保存
const pdfBytes = await pdfDoc.save()
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'updated-document.pdf';
a.click();
}