如何通过Crontab实现amCharts的PDF自动导出?(Node.js环境)
Got it, let's tackle this problem step by step. Since amCharts' default export is client-side, we need to simulate a browser environment in Node.js to render the chart and automate the PDF export—here's a solid approach:
1. Use a Headless Browser (Puppeteer)
amCharts relies on browser APIs to render charts, so we'll use Puppeteer (a headless Chrome/Chromium tool) to simulate a browser session in Node.js. This lets us render the chart server-side and trigger the export.
First, install the required packages:
npm install puppeteer amcharts3
2. Write the Export Script
Create a Node.js script (e.g., auto-export-chart.js) that handles rendering the chart and exporting it to PDF. Here's a complete example:
const puppeteer = require('puppeteer'); const fs = require('fs'); const path = require('path'); async function generateChartPDF() { // Launch a headless Chrome instance const browser = await puppeteer.launch({ headless: 'new', // Uncomment below if you need to use your system's Chrome instead of Puppeteer's bundled one // executablePath: '/usr/bin/google-chrome' }); const page = await browser.newPage(); // Set viewport dimensions to match your chart's ideal size await page.setViewport({ width: 1200, height: 800 }); // Inject amCharts and your chart configuration into a temporary HTML page await page.setContent(` <html> <head> <script src="https://cdn.amcharts.com/lib/3/amcharts.js"></script> <script src="https://cdn.amcharts.com/lib/3/serial.js"></script> <script src="https://cdn.amcharts.com/lib/3/plugins/export/export.min.js"></script> <link rel="stylesheet" href="https://cdn.amcharts.com/lib/3/plugins/export/export.css" /> <style> body, html { margin: 0; padding: 0; height: 100%; } #chartdiv { width: 100%; height: 100%; } </style> </head> <body> <div id="chartdiv"></div> <script> // Your custom amCharts configuration const chart = AmCharts.makeChart("chartdiv", { "type": "serial", "theme": "light", "dataProvider": [ {"month": "Jan", "sales": 1000}, {"month": "Feb", "sales": 1200}, {"month": "Mar", "sales": 1500} // Add your actual data here—you could also fetch it via API if needed ], "categoryField": "month", "graphs": [{ "valueField": "sales", "type": "column", "fillAlphas": 0.8 }], "export": { "enabled": true, // Enable amCharts' export functionality "libs": { "pdfmake": "https://cdn.amcharts.com/lib/3/plugins/export/libs/pdfmake/pdfmake.min.js", "vfs_fonts": "https://cdn.amcharts.com/lib/3/plugins/export/libs/pdfmake/vfs_fonts.js" } } }); // Wait for the chart to finish rendering, then trigger PDF export chart.addListener("init", () => { chart.export.toPDF({ // Customize export options (e.g., page size, orientation) "pageSize": "A4", "orientation": "landscape" }, (pdfBase64) => { // Send the base64-encoded PDF back to our Node.js script window.sendPDF(pdfBase64); }); }); </script> </body> </html> `); // Set up a handler to receive the PDF data from the browser const pdfBase64 = await new Promise((resolve) => { page.exposeFunction('sendPDF', resolve); }); // Save the PDF to a file (add timestamps if you want unique filenames) const outputPath = path.join(__dirname, `chart-export-${new Date().toISOString().slice(0,10)}.pdf`); fs.writeFileSync(outputPath, pdfBase64, 'base64'); // Clean up: close the browser await browser.close(); console.log(`PDF saved to ${outputPath}`); } // Run the export function, catch any errors generateChartPDF().catch((err) => { console.error('Export failed:', err); process.exit(1); });
3. Test the Script
Run the script manually to make sure it works:
node auto-export-chart.js
Check if the PDF file is generated and contains your chart correctly. If the chart isn't fully rendered, add a small delay after page.setContent (e.g., await page.waitForTimeout(2000);) to give it time to load.
4. Automate with Crontab
To run this script on a schedule (like daily/weekly), use Crontab:
- Open the Crontab editor:
crontab -e
- Add a line to schedule the script. For example, to run it every day at 3 AM:
0 3 * * * cd /path/to/your/project && /usr/bin/node auto-export-chart.js >> /var/log/chart-export.log 2>&1
0 3 * * *: Cron syntax for "3:00 AM every day"/usr/bin/node: Path to your Node.js executable (find it withwhich node)>> /var/log/chart-export.log 2>&1: Logs output/errors to a file for debugging
5. Troubleshooting Tips
- Chart not rendering: Ensure all amCharts scripts (including the export plugin) are loaded correctly in the HTML.
- Puppeteer issues: If Puppeteer fails to launch, check if your system has the required dependencies (e.g., libnss3, libatk1.0-0—Puppeteer will warn you if missing).
- Dynamic data: If your chart uses external data, fetch it in the Node.js script first, then inject it into the HTML template as a string.
内容的提问来源于stack exchange,提问作者CaptnHirni

