@danchitnis/svg-to-pdf
v1.0.0
Published
convert svg to pdf
Readme
@danchitnis/svg-to-pdf
A lightweight, flexible, and platform-agnostic library to convert SVG to PDF using pdf-lib.
Features
- Platform Agnostic: Works in both Node.js and the Browser.
- Flexible Layout: specific paper sizes (A4, Letter, etc.), custom dimensions, or content-scaling.
- SVG Support:
- Basic Shapes:
rect,circle,ellipse,line,polyline,polygon. - Paths: Comprehensive
dattribute parsing. - Transforms:
translate,scale,rotate,matrixsupport. - Groups (
<g>) and hierarchy. - Styles: Basic styling via attributes.
- Text: Basic text rendering (standard fonts).
- ViewBox: Full
viewBoxsupport with aspect ratio handling.
- Basic Shapes:
Installation
npm install @danchitnis/svg-to-pdfUsage
This library operates on a simplified, platform-neutral JSON structure (SimpleSvgElement) instead of directly on DOM nodes. This design allows it to run in complete isolation from browser APIs (perfect for Node.js) or within a browser environment.
You need to convert your SVG (whether a string or a DOM element) into this simple structure before passing it to the converter.
Node.js Example
In Node.js, you can use jsdom to parse the SVG string.
Install dependencies:
npm install jsdom npm install --save-dev @types/jsdomCreate a converter script:
import { convertSvgToPdfFromSimpleStructure, SimpleSvgElement } from "@danchitnis/svg-to-pdf"; import { JSDOM } from "jsdom"; import * as fs from "fs/promises"; // 1. Define a helper to convert JSDOM/DOM elements to SimpleSvgElement function adaptDomToSimpleSvgStructure(element: Element): SimpleSvgElement { const attributes: { [key: string]: string } = {}; for (const attr of Array.from(element.attributes)) { attributes[attr.name] = attr.value; } const children: SimpleSvgElement[] = []; for (const childNode of Array.from(element.children)) { children.push(adaptDomToSimpleSvgStructure(childNode as Element)); } return { tagName: element.tagName, attributes, children, textContent: element.textContent, getAttribute: (name) => element.getAttribute(name), }; } async function main() { // 2. Read and Parse SVG const svgContent = await fs.readFile("input.svg", "utf-8"); const dom = new JSDOM(svgContent, { contentType: "image/svg+xml" }); const svgElement = dom.window.document.documentElement; if (!svgElement || svgElement.tagName.toLowerCase() !== "svg") { throw new Error("Invalid SVG"); } // 3. Adapt to Simple Structure const simpleSvg = adaptDomToSimpleSvgStructure(svgElement); // 4. Convert to PDF const pdfBytes = await convertSvgToPdfFromSimpleStructure(simpleSvg, { paperSize: "A4", // or 'Letter', or { width: 210, height: 297 } backgroundColor: "white", }); // 5. Save PDF await fs.writeFile("output.pdf", pdfBytes); console.log("PDF created!"); } main();
Browser Example
In the browser, you can directly interact with the DOM elements.
import { convertSvgToPdfFromSimpleStructure, SimpleSvgElement } from "@danchitnis/svg-to-pdf";
// Same helper function as above
function adaptDomToSimpleSvgStructure(element: Element): SimpleSvgElement {
// ... (see Node.js example) ...
}
async function exportSvgToPdf() {
const svgElement = document.querySelector("#my-svg-chart");
const simpleSvg = adaptDomToSimpleSvgStructure(svgElement);
const pdfBytes = await convertSvgToPdfFromSimpleStructure(simpleSvg, {
multiplier: 2, // Scale up content 2x
backgroundColor: "#ffffff"
});
// Download the PDF file (example utility)
const blob = new Blob([pdfBytes], { type: "application/pdf" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "chart.pdf";
link.click();
}API
convertSvgToPdfFromSimpleStructure(svgElement, options)
Parameters:
svgElement:SimpleSvgElement- The root SVG element in specific JSON format.options:SvgToPdfOptions- Configuration for the output PDF.
Returns: Promise<Uint8Array> - The generated PDF as a byte array.
SvgToPdfOptions
| Option | Type | Description |
| search | type | description |
|---|---|---|
| width | number | Override output width (in points). |
| height | number | Override output height (in points). |
| scale | number | Apply a global scale factor to the content. |
| multiplier | number | Simple scaling: Output Size = SVG Size * Multiplier. |
| paperSize | string | { w, h } | Fit content to standard paper (e.g., 'A4', 'Letter') or custom dimensions (mm). |
| backgroundColor | string | Background color name or hex code (e.g., 'white', '#f0f0f0'). |
Supported Paper Sizes
- A3, A4, A5
- Letter, Legal, Tabloid
License
ISC
