fix: editor
This commit is contained in:
@@ -1,9 +1,20 @@
|
||||
import puppeteer from 'puppeteer';
|
||||
import { resolve, basename } from 'path';
|
||||
import { resolve, basename, dirname } from 'path';
|
||||
import { existsSync, mkdirSync } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { createServer } from 'http';
|
||||
import { readFile } from 'fs/promises';
|
||||
import { extname } from 'path';
|
||||
|
||||
const OUTPUT_DIR = resolve(fileURLToPath(import.meta.url), '../../../output/pdf');
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const PROJECT_ROOT = resolve(__dirname, '../..');
|
||||
const OUTPUT_DIR = resolve(PROJECT_ROOT, 'output/pdf');
|
||||
|
||||
const MIME_TYPES = {
|
||||
'.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
|
||||
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
||||
'.webp': 'image/webp', '.svg': 'image/svg+xml', '.json': 'application/json',
|
||||
};
|
||||
|
||||
async function generatePdf(htmlPath) {
|
||||
const absolutePath = resolve(htmlPath);
|
||||
@@ -14,13 +25,33 @@ async function generatePdf(htmlPath) {
|
||||
|
||||
mkdirSync(OUTPUT_DIR, { recursive: true });
|
||||
|
||||
const pdfName = basename(absolutePath, '.html') + '.pdf';
|
||||
// Strip .output and .template from PDF filename
|
||||
let pdfName = basename(absolutePath, '.html');
|
||||
pdfName = pdfName.replace(/\.(output|template)$/, '') + '.pdf';
|
||||
const pdfPath = resolve(OUTPUT_DIR, pdfName);
|
||||
|
||||
const browser = await puppeteer.launch({ headless: true });
|
||||
// Start temp HTTP server to resolve /assets/ paths correctly
|
||||
const server = createServer(async (req, res) => {
|
||||
const filePath = resolve(PROJECT_ROOT, decodeURIComponent(req.url).replace(/^\//, ''));
|
||||
try {
|
||||
const data = await readFile(filePath);
|
||||
const ext = extname(filePath);
|
||||
res.writeHead(200, { 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream' });
|
||||
res.end(data);
|
||||
} catch {
|
||||
res.writeHead(404);
|
||||
res.end('Not found');
|
||||
}
|
||||
});
|
||||
|
||||
await new Promise(r => server.listen(0, '127.0.0.1', r));
|
||||
const port = server.address().port;
|
||||
const relPath = absolutePath.replace(PROJECT_ROOT + '/', '');
|
||||
|
||||
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
|
||||
const page = await browser.newPage();
|
||||
|
||||
await page.goto(`file://${absolutePath}`, { waitUntil: 'networkidle0' });
|
||||
await page.goto(`http://127.0.0.1:${port}/${relPath}`, { waitUntil: 'networkidle0', timeout: 30000 });
|
||||
|
||||
await page.pdf({
|
||||
path: pdfPath,
|
||||
@@ -31,6 +62,7 @@ async function generatePdf(htmlPath) {
|
||||
});
|
||||
|
||||
await browser.close();
|
||||
server.close();
|
||||
console.log(`PDF generated: ${pdfPath}`);
|
||||
return pdfPath;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user