-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-pdf.js
More file actions
65 lines (46 loc) · 1.66 KB
/
generate-pdf.js
File metadata and controls
65 lines (46 loc) · 1.66 KB
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
const puppeteer = require("puppeteer");
const fs = require("fs");
const path = require("path");
const { PDFDocument } = require("pdf-lib");
const rootDir = process.cwd();
const outputDir = path.join(rootDir, "assets", "pdf");
const outputPath = path.join(outputDir, "guideline.pdf");
const coverPath = path.join(outputDir, "cover_page.pdf");
const tempPdfPath = path.join(outputDir, "temp_guideline.pdf");
const url = `file://${path.join(rootDir, "_site", "print.html")}`;
(async () => {
fs.mkdirSync(outputDir, { recursive: true });
const browser = await puppeteer.launch({
headless: "new",
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
const page = await browser.newPage();
await page.goto(url, { waitUntil: "networkidle0" });
await page.pdf({
path: tempPdfPath,
width: 1123,
height: 794,
printBackground: true,
margin: {
top: "2cm",
bottom: "2cm",
left: "2cm",
right: "2cm"
},
});
await browser.close();
// On fusionne cover_page.pdf et le PDF généré
const coverBytes = fs.readFileSync(coverPath);
const mainBytes = fs.readFileSync(tempPdfPath);
const coverPdf = await PDFDocument.load(coverBytes);
const mainPdf = await PDFDocument.load(mainBytes);
const mergedPdf = await PDFDocument.create();
const [coverPage] = await mergedPdf.copyPages(coverPdf, [0]);
mergedPdf.addPage(coverPage);
const mainPages = await mergedPdf.copyPages(mainPdf, mainPdf.getPageIndices());
mainPages.forEach(page => mergedPdf.addPage(page));
const mergedBytes = await mergedPdf.save();
fs.writeFileSync(outputPath, mergedBytes);
fs.unlinkSync(tempPdfPath);
console.log("PDF généré :", outputPath);
})();