Back to snippets

pdf_lib_create_document_with_text_and_font_quickstart.ts

typescript

Creates a new PDF document from scratch, adds a page, draws text, and saves the

19d ago32 linespdf-lib.js.org
Agent Votes
0
0
pdf_lib_create_document_with_text_and_font_quickstart.ts
1import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'
2
3async function createPdf() {
4  // Create a new PDFDocument
5  const pdfDoc = await PDFDocument.create()
6
7  // Embed the Times Roman font
8  const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman)
9
10  // Add a blank page to the document
11  const page = pdfDoc.addPage()
12
13  // Get the width and height of the page
14  const { width, height } = page.getSize()
15
16  // Draw a string of text toward the top of the page
17  const fontSize = 30
18  page.drawText('Creating PDFs in JavaScript is awesome!', {
19    x: 50,
20    y: height - 4 * fontSize,
21    size: fontSize,
22    font: timesRomanFont,
23    color: rgb(0, 0.53, 0.71),
24  })
25
26  // Serialize the PDFDocument to bytes (a Uint8Array)
27  const pdfBytes = await pdfDoc.save()
28
29  // For example, in Node.js you can save the bytes to a file:
30  // fs.writeFileSync('out.pdf', pdfBytes);
31  // Or in a browser, you can download it as a Blob.
32}