-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (57 loc) · 1.79 KB
/
index.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const userName = document.getElementById("name");
const submitBtn = document.getElementById("submitBtn");
const { PDFDocument, rgb, degrees } = PDFLib;
const capitalize = (str, lower = false) =>
(lower ? str.toLowerCase() : str).replace(/(?:^|\s|["'([{])+\S/g, (match) =>
match.toUpperCase()
);
submitBtn.addEventListener("click", () => {
const val = capitalize(userName.value);
//check if the text is empty or not
if (val.trim() !== "" && userName.checkValidity()) {
// console.log(val);
generatePDF(val);
} else {
userName.reportValidity();
}
});
const generatePDF = async (name) => {
const existingPdfBytes = await fetch("./cert.pdf").then((res) =>
res.arrayBuffer()
);
// Load a PDFDocument from the existing PDF bytes
const pdfDoc = await PDFDocument.load(existingPdfBytes);
pdfDoc.registerFontkit(fontkit);
//get font
const fontBytes = await fetch("./Tinos-BoldItalic.ttf").then((res) =>
res.arrayBuffer()
);
// Embed our custom font in the document
const Tinos = await pdfDoc.embedFont(fontBytes);
// Get the first page of the document
const pages = pdfDoc.getPages();
const firstPage = pages[0];
// Draw a string of text diagonally across the first page
firstPage.drawText(name, {
x: 420,
y: 280,
size: 22,
font: Tinos,
color: rgb(0.0, 0.0, 0.0),
});
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save();
console.log("Done creating");
// this was for creating uri and showing in iframe
// const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
// document.getElementById("pdf").src = pdfDataUri;
var file = new File(
[pdfBytes],
name+"_Certificate.pdf",
{
type: "application/pdf;charset=utf-8",
}
);
saveAs(file);
};
// init();