// Generates samples/sample.pdf: Thai + English text, an image, and form fields. import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'; import fontkit from '@pdf-lib/fontkit'; import { readFileSync, writeFileSync } from 'node:fs'; import zlib from 'node:zlib'; function png(w, h) { // simple gradient PNG const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) { raw[y * (w * 3 + 1)] = 0; for (let x = 0; x < w; x++) { const o = y * (w * 3 + 1) + 1 + x * 3; raw[o] = (x * 255) / w; raw[o + 1] = (y * 255) / h; raw[o + 2] = 180; } } const chunk = (t, d) => { const b = Buffer.alloc(8 + d.length + 4); b.writeUInt32BE(d.length); b.write(t, 4); d.copy(b, 8); b.writeUInt32BE(zlib.crc32 ? zlib.crc32(Buffer.concat([Buffer.from(t), d])) >>> 0 : 0, 8 + d.length); return b; }; const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2; return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); } const d = await PDFDocument.create(); d.registerFontkit(fontkit); const th = await d.embedFont(readFileSync('public/fonts/Sarabun-Regular.ttf')); const hb = await d.embedFont(StandardFonts.HelveticaBold); const p = d.addPage([595, 842]); p.drawText('Quarterly Report 2026', { x: 60, y: 770, size: 24, font: hb, color: rgb(0.1, 0.2, 0.5) }); p.drawText('รายงานประจำไตรมาส บริษัท ตัวอย่าง จำกัด', { x: 60, y: 735, size: 16, font: th }); p.drawText('Revenue grew 12% compared to last quarter.', { x: 60, y: 700, size: 12, font: th }); p.drawText('ยอดขายเพิ่มขึ้นร้อยละ 12 เมื่อเทียบกับไตรมาสก่อน', { x: 60, y: 682, size: 12, font: th }); const img = await d.embedPng(png(200, 120)); p.drawImage(img, { x: 60, y: 520, width: 200, height: 120 }); const rows = [['Item', 'Q1', 'Q2'], ['Sales', '1,200', '1,344'], ['Cost', '800', '850']]; rows.forEach((r, i) => r.forEach((c, j) => p.drawText(c, { x: 300 + j * 80, y: 620 - i * 20, size: 11, font: th }))); const form = d.getForm(); p.drawText('ชื่อผู้อนุมัติ:', { x: 60, y: 452, size: 12, font: th }); form.createTextField('approver').addToPage(p, { x: 150, y: 445, width: 200, height: 22 }); p.drawText('Agree:', { x: 60, y: 420, size: 12, font: th }); form.createCheckBox('agree').addToPage(p, { x: 150, y: 415, width: 14, height: 14 }); const p2 = d.addPage([595, 842]); p2.drawText('Page two - เลขบัตรประชาชน 1-2345-67890-12-3', { x: 60, y: 770, size: 14, font: th }); writeFileSync('samples/sample.pdf', await d.save()); console.log('ok');