Skip to content

Instantly share code, notes, and snippets.

@temberature
Created May 12, 2022 17:14
Show Gist options
  • Save temberature/f161c369f3a08dca45db52bba75cc68c to your computer and use it in GitHub Desktop.
Save temberature/f161c369f3a08dca45db52bba75cc68c to your computer and use it in GitHub Desktop.
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
import fs from "fs";
import fontkit from "@pdf-lib/fontkit";
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create();
// var font = fontkit.openSync('fonts/msyh.ttf');
const fontData = fs.readFileSync("fonts/msyh.ttf");
pdfDoc.registerFontkit(fontkit);
// Embed the Times Roman font
const timesRomanFont = await pdfDoc.embedFont(fontData);
// Add a blank page to the document
const page = pdfDoc.addPage();
// Get the width and height of the page
const { width, height } = page.getSize();
// Draw a string of text toward the top of the page
const fontSize = 30;
page.drawText("用JS创建PDF真棒!Creating PDFs in JavaScript is awesome!", {
x: 50,
y: height - 4 * fontSize,
size: fontSize,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save();
fs.writeFileSync("test.pdf", pdfBytes);
// For example, `pdfBytes` can be:
// • Written to a file in Node
// • Downloaded from the browser
// • Rendered in an <iframe>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment