npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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 d attribute parsing.
    • Transforms: translate, scale, rotate, matrix support.
    • Groups (<g>) and hierarchy.
    • Styles: Basic styling via attributes.
    • Text: Basic text rendering (standard fonts).
    • ViewBox: Full viewBox support with aspect ratio handling.

Installation

npm install @danchitnis/svg-to-pdf

Usage

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.

  1. Install dependencies:

    npm install jsdom
    npm install --save-dev @types/jsdom
  2. Create 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