Add default options to the pdf plugin

This commit is contained in:
TheThomaas 2025-05-04 22:32:35 +02:00
parent 9fd9dbc14a
commit e3db7301f3

View file

@ -3,27 +3,34 @@ import { nanoid } from 'nanoid'
import fs from 'fs'; import fs from 'fs';
let config = {} let config = {}
export default function (eleventyConfig, pluginOptions) { export default function (eleventyConfig, pluginOptions = {}) {
config = pluginOptions; config = Object.assign({
// Plugin defaults
tempDir: "dist", // Directory where the temporary files are created
debug: false, // Keep the generated temporary html file for debugging
format: "A4", // Default pdf format
margin: { // PDF file margins
top: "1cm",
right: "1.25cm",
bottom: "1cm",
left: "1.25cm",
}
}, pluginOptions);
eleventyConfig.addTransform("toPDF", transformPDF); eleventyConfig.addTransform("toPDF", transformPDF);
}; };
const transformPDF = async function(content) { const transformPDF = async function(content) {
if (this.outputPath && this.outputPath.toLowerCase().endsWith('.pdf')) { if (this.outputPath && this.outputPath.toLowerCase().endsWith('.pdf')) {
let htmlFile = `./${config.tempDir || "dist"}/${nanoid()}.html`; let tempFileName = config.debug ? this.page.fileSlug : nanoid();
let pdfFile = `./${config.tempDir || "dist"}/${nanoid()}.pdf`; let htmlFile = `./${config.tempDir}/${tempFileName}.html`;
let pdfFile = `./${config.tempDir}/${tempFileName}.pdf`;
fs.writeFileSync(htmlFile, content); fs.writeFileSync(htmlFile, content);
const htmlPDF = new PuppeteerHTMLPDF(); const htmlPDF = new PuppeteerHTMLPDF();
const options = { const options = {
format: config.format || "A4", format: config.format,
margin: config.margin || { margin: config.margin,
top: "1cm",
right: "1.25cm",
bottom: "1cm",
left: "1.25cm",
},
path: pdfFile, // you can pass path to save the file path: pdfFile, // you can pass path to save the file
}; };
htmlPDF.setOptions(options); htmlPDF.setOptions(options);
@ -32,7 +39,9 @@ const transformPDF = async function(content) {
await htmlPDF.create(pdfContent); await htmlPDF.create(pdfContent);
let contents = fs.readFileSync(pdfFile, 'binary'); let contents = fs.readFileSync(pdfFile, 'binary');
if (!config.debug) {
fs.unlinkSync(htmlFile); fs.unlinkSync(pdfFile); fs.unlinkSync(htmlFile); fs.unlinkSync(pdfFile);
}
return Buffer.from(contents,'binary'); return Buffer.from(contents,'binary');
} else return content; } else return content;
}; };