ttt
const express = require('express');
const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs');
const app = express();
const port = 3000;
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Route to convert URL to PDF
app.post('/convert', async (req, res) => {
const { url } = req.body;
try {
// Validate URL
const urlPattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/i;
if (!urlPattern.test(url)) {
return res.status(400).json({ error: 'Ungültige URL' });
}
// Launch Puppeteer
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
// Navigate to URL and wait for content to load
await page.goto(url, { waitUntil: 'networkidle2' });
// Get full page dimensions
const { width, height } = await page.evaluate(() => {
return {
width: document.documentElement.scrollWidth,
height: document.documentElement.scrollHeight
};
});
// Set viewport to full page size
await page.setViewport({ width, height });
// Generate PDF
const pdfPath = path.join(__dirname, 'public', `output-${Date.now()}.pdf`);
await page.pdf({
path: pdfPath,
width: `${width}px`,
height: `${height}px`,
printBackground: true,
format: null, // Use custom dimensions
margin: { top: 0, right: 0, bottom: 0, left: 0 },
displayHeaderFooter: false,
preferCSSPageSize: true
});
await browser.close();
// Generate public URL for download
const pdfUrl = `/output-${path.basename(pdfPath)}`;
// Clean up files after 1 hour
setTimeout(() => {
fs.unlink(pdfPath, (err) => {
if (err) console.error('Fehler beim Löschen der PDF:', err);
});
}, 3600000);
res.json({ pdfUrl });
} catch (error) {
console.error('Fehler:', error);
res.status(500).json({ error: 'Fehler beim Erstellen der PDF' });
}
});
// Start server
app.listen(port, () => {
console.log(`Server läuft auf http://localhost:${port}`);
});
Kommentare
Kommentar veröffentlichen