69 lines
2 KiB
JavaScript
69 lines
2 KiB
JavaScript
const fs = require("fs");
|
|
const path = require("path");
|
|
const puppeteer = require("puppeteer");
|
|
|
|
async function svgToPdf(inputPath, outputPath) {
|
|
const svgContent = fs.readFileSync(inputPath, "utf-8");
|
|
|
|
// Extract width/height or fallback to viewBox
|
|
let width = 1000;
|
|
let height = 1000;
|
|
|
|
const widthMatch = svgContent.match(/<svg[^>]*\bwidth="([\d.]+)(px)?"/i);
|
|
const heightMatch = svgContent.match(/<svg[^>]*\bheight="([\d.]+)(px)?"/i);
|
|
const viewBoxMatch = svgContent.match(/viewBox="([\d.\s]+)"/i);
|
|
|
|
if (widthMatch && heightMatch) {
|
|
width = parseFloat(widthMatch[1]);
|
|
height = parseFloat(heightMatch[1]);
|
|
} else if (viewBoxMatch) {
|
|
const parts = viewBoxMatch[1].split(/\s+/);
|
|
width = parseFloat(parts[2]);
|
|
height = parseFloat(parts[3]);
|
|
}
|
|
|
|
// Create HTML wrapper
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<style>
|
|
html, body { margin: 0; padding: 0; }
|
|
object, svg { display: block; width: 100%; height: 100%; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<object type="image/svg+xml" data="data:image/svg+xml;base64,${Buffer.from(svgContent).toString('base64')}"></object>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
const browser = await puppeteer.launch();
|
|
const page = await browser.newPage();
|
|
|
|
await page.setContent(html, { waitUntil: "networkidle0" });
|
|
|
|
await page.pdf({
|
|
path: outputPath,
|
|
width: `${width}px`,
|
|
height: `${height}px`,
|
|
printBackground: true,
|
|
pageRanges: "1"
|
|
});
|
|
|
|
await browser.close();
|
|
console.log(`✅ PDF saved: ${outputPath}`);
|
|
}
|
|
|
|
// Command-line arguments
|
|
const args = process.argv.slice(2);
|
|
if (args.length === 0) {
|
|
console.log("Usage: node svg_to_pdf.js input.svg [output.pdf]");
|
|
process.exit(1);
|
|
}
|
|
|
|
const inputPath = path.resolve(args[0]);
|
|
const outputPath = args[1] ? path.resolve(args[1]) : inputPath.replace(/\.svg$/i, ".pdf");
|
|
|
|
svgToPdf(inputPath, outputPath);
|