crif-pdfexample.web.val.run
Readme

Generate a pdf with pdf-lib

πŸ‘‰ Visit the web site generated by this Val

pdf-lib is an incredible pure-JavaScript module that generates PDFs! In this example, it's generating a simple page that embeds the PDF, and exposes another route (with Hono) that serves the PDF.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
export const pdfExample = (async (req) => {
const { Hono } = await import("npm:hono");
const app = new Hono();
app.get("/", async (c) => {
return new Response(
`<html><body><h1>This PDF is generated with Val Town:</h1>
<iframe src='/pdf' width="100%" height="500"></iframe></body>
</html>`,
{
headers: {
"Content-Type": "text/html; charset=utf-8",
},
},
);
});
app.get("/pdf", async (c) => {
const { PDFDocument, StandardFonts, rgb } = await import("npm:pdf-lib");
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create();
// Embed the Times Roman font
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
// 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("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();
return new Response(pdfBytes, {
headers: {
"Content-Type": "application/pdf",
},
});
});
return app.fetch(req);
});
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
April 23, 2024