| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- /**
- * Génère des PDF à partir des fichiers .md du dossier planning-artifacts (parent).
- * Les blocs ```mermaid sont convertis en SVG puis insérés comme images pour apparaître dans le PDF.
- * Usage : node generate-pdfs.js (depuis pdfGenerator)
- * Prérequis : npm install (dans ce dossier)
- */
- const fs = require('fs');
- const path = require('path');
- const dir = __dirname;
- const sourceDir = path.join(dir, '..');
- const pdfDir = path.join(dir, 'pdf');
- const cssPath = path.join(dir, 'pdf-style.css');
- /** Extrait les blocs ```mermaid ... ``` et les remplace par des images SVG (générées via Puppeteer). */
- async function preprocessMermaidToSvg(mdContent, sourceDirPath, baseName) {
- const regex = /```mermaid\n([\s\S]*?)```/g;
- const blocks = [];
- let match;
- while ((match = regex.exec(mdContent)) !== null) {
- blocks.push({ full: match[0], code: match[1].trim(), index: match.index });
- }
- if (blocks.length === 0) return mdContent;
- let puppeteer;
- try {
- puppeteer = require('puppeteer');
- } catch (e) {
- console.warn(' (Puppeteer non disponible pour Mermaid : les blocs restent en code)');
- return mdContent;
- }
- const browser = await puppeteer.launch({ headless: 'new' });
- try {
- const replacements = [];
- for (let i = 0; i < blocks.length; i++) {
- const { code } = blocks[i];
- const page = await browser.newPage();
- const safeCode = code.replace(/<\/script>/gi, '</scr\' + \'ipt>');
- await page.setContent(
- `<!DOCTYPE html><html><body><script type="text/mermaid">${safeCode}</script>
- <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
- <script>mermaid.initialize({startOnLoad:true});</script></body></html>`,
- { waitUntil: 'networkidle0', timeout: 15000 }
- );
- await page.waitForSelector('svg', { timeout: 10000 }).catch(() => null);
- await new Promise((r) => setTimeout(r, 300));
- const svg = await page.evaluate(() => {
- const el = document.querySelector('body svg');
- return el ? el.outerHTML : '';
- });
- await page.close();
- if (svg) {
- const svgFile = path.join(sourceDirPath, `${baseName}-mermaid-${i + 1}.svg`);
- fs.writeFileSync(svgFile, svg, 'utf8');
- replacements.push({ full: blocks[i].full, img: `\n})\n` });
- }
- }
- await browser.close();
- let out = mdContent;
- for (const r of replacements.reverse()) out = out.replace(r.full, r.img);
- return out;
- } catch (err) {
- await browser.close().catch(() => {});
- console.warn(' (Mermaid preprocess erreur:', err.message, ')');
- return mdContent;
- }
- }
- async function main() {
- let mdToPdf;
- try {
- ({ mdToPdf } = require('md-to-pdf'));
- } catch (e) {
- console.error('Erreur : installez les dépendances avec : npm install');
- process.exit(1);
- }
- if (!fs.existsSync(sourceDir)) {
- console.error('Dossier source introuvable :', sourceDir);
- process.exit(1);
- }
- const files = fs.readdirSync(sourceDir).filter(
- (f) => f.endsWith('.md') && !/^README(-.*)?\.md$/i.test(f)
- );
- if (!fs.existsSync(pdfDir)) {
- fs.mkdirSync(pdfDir, { recursive: true });
- }
- const hasNonAscii = (s) => /[^\x00-\x7F]/.test(s);
- const baseConfig = {
- pdf_options: {
- format: 'A4',
- margin: '20mm',
- printBackground: true,
- },
- stylesheet: fs.existsSync(cssPath) ? cssPath : undefined,
- body_class: 'markdown-body',
- basedir: sourceDir,
- };
- console.log('Conversion des fichiers Markdown -> PDF...\n');
- console.log(' Source :', sourceDir);
- console.log(' Sortie :', pdfDir, '\n');
- for (const file of files) {
- const mdPath = path.join(sourceDir, file);
- const base = path.basename(file, '.md');
- const pdfPath = path.join(pdfDir, base + '.pdf');
- let content = fs.readFileSync(mdPath, 'utf8');
- const hadMermaid = /```mermaid/.test(content);
- if (hadMermaid) {
- content = await preprocessMermaidToSvg(content, sourceDir, base);
- }
- const input = hasNonAscii(file) || hadMermaid ? { content } : { path: mdPath };
- try {
- await mdToPdf(input, { ...baseConfig, basedir: sourceDir, dest: pdfPath });
- console.log(' OK :', file, '-> pdf/' + base + '.pdf');
- } catch (err) {
- console.error(' ERREUR pour', file, ':', err.message);
- }
- }
- console.log('\nTerminé. PDF dans : pdfGenerator/pdf/');
- console.log('Puis lancez : npm run merge pour générer le PDF complet.');
- }
- main();
|