Code Monkey home page Code Monkey logo

svg2png-wasm's Introduction

svg2png-wasm

Demo site

SVG to PNG converter JS library made with WASM + resvg.

See resvg for SVG support status.

💻 Usage

Installation

Node.js / Browser

npm install svg2png-wasm
# yarn add svg2png-wasm
# pnpm add svg2png-wasm

Or, using a script tag in the browser and load from unpkg.

<script src="https://unpkg.com/[email protected]"></script>

<!-- Or, latest -->
<script src="https://unpkg.com/svg2png-wasm"></script>

Deno

// from esm.sh
export * from 'https://esm.sh/[email protected]';
// from skypack.dev
export * from 'https://cdn.skypack.dev/[email protected]?dts';

Examples

Node.js

import { svg2png, initialize } from 'svg2png-wasm';
// const { svg2png, initialize } = require('svg2png-wasm');
import { readFileSync, writeFileSync } from 'fs';

await initialize(
  readFileSync('./node_modules/svg2png-wasm/svg2png_wasm_bg.wasm'),
);

/** @type {Uint8Array} */
const png = await svg2png(
  '<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> ... </svg>',
  {
    scale: 2, // optional
    width: 400, // optional
    height: 400, // optional
    backgroundColor: 'white', // optional
    fonts: [
      // optional
      readFileSync('./Roboto.ttf'), // require, If you use text in svg
    ],
    defaultFontFamily: {
      // optional
      sansSerif: 'Roboto',
    },
  },
);
writeFileSync('./output.png', png);

Browser

import { createSvg2png, initialize } from 'svg2png-wasm';

// put wasm to your assets directory
await initialize(fetch('/assets/svg2png_wasm_bg.wasm'));
const svgs = [
  '<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> ... </svg>',
  '<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> ... </svg>',
  '<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> ... </svg>',
  // and more ...
];
const font = await fetch('./Roboto.ttf').then((res) => res.arrayBuffer());
const svg2png = createSvg2png({
  fonts: [new Uint8Array(font)], // require, If you use text in svg
});
/** @type {Uint8Array[]} */
const pngs = await Promise.all(svgs.map((svg) => svg2png(svg, { scale: 2 })));
svg2png.dispose(); // You should dispose svg2png, if you will not use it in the future

Or, using a script tag in the browser and load from unpkg.

<script src="https://unpkg.com/svg2png-wasm"></script>
<script>
  await svg2pngWasm.initialize(fetch('https://unpkg.com/svg2png-wasm/svg2png_wasm_bg.wasm'))
  const font = await fetch('./Roboto.ttf').then((res) => res.arrayBuffer());
  /** @type {Uint8Array} */
  const png = await svg2pngWasm.svg2png(
    '<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> ... </svg>',
  );
  document.getElementById('output').src = URL.createObjectURL(
    new Blob([png], { type: 'image/png' }),
  );
</script>

API

The library has two main APIs (svg2png and createSvg2png).

Basically, you can use svg2png, but if you want to process a lot of data continuously, consider using createSvg2png. It can reduce the overhead of font loading. Converters generated by createSvg2png should be disposed of after use by calling the dispose method.

export type InitInput =
  | RequestInfo
  | URL
  | Response
  | BufferSource
  | WebAssembly.Module;
export type DefaultFontFamily = {
  serifFamily?: string;
  sansSerifFamily?: string;
  cursiveFamily?: string;
  fantasyFamily?: string;
  monospaceFamily?: string;
};
export type ConverterOptions = {
  fonts?: Uint8Array[];
  defaultFontFamily?: DefaultFontFamily;
};
export type ConvertOptions = {
  scale?: number;
  width?: number;
  height?: number;
  backgroundColor?: string;
};
export type Svg2png = ((
  svg: string,
  options?: ConvertOptions,
) => Promise<Uint8Array>) & {
  dispose: () => void;
};
/**
 * Initialize WASM module
 * @param mod WebAssembly Module or WASM url
 */
export const initialize: (mod: Promise<InitInput> | InitInput) => Promise<void>;
/**
 * @param opts Converter options (e.g. font settings)
 * @returns svg2png converter
 */
export const createSvg2png: (opts?: ConverterOptions | undefined) => Svg2png;
export const svg2png: (
  svg: string,
  opts?: (ConverterOptions & ConvertOptions) | undefined,
) => Promise<Uint8Array>;

📄 LICENSE

MIT

This library uses resvg, which is licensed unser MPL-2.0. The source code for resvg can be found here.

🙋‍♂️ Contributing

WELCOME!

svg2png-wasm's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar mfzl avatar opengg avatar renovate[bot] avatar ssssota avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

svg2png-wasm's Issues

resvg v0.20.0

リリースされてたので、更新・追従する

CI/CDの修正

手元だと動くけどGitHub Actionsだと失敗するテストになってる。

ついでに、リリースフローの見直し(semantic-release?)、Jest->Vitestなど

readme カイゼン

  • demo pageへの誘導
  • サンプルコードのリファクタリング
  • createSvg2png と svg2png の説明

Does it support images in svg?

I tried to convert a svg that contains image tag, but the images are gone in resulting png, regardless of if they are referenced by href url or base64 string.

Embedded Fonts Not Rendering

I'm using the package in a CloudFlare worker and running into issues with rendering embedded fonts.

Example SVG:
6040c18b5322b032e7a392c41bbb75a8

Note that the font is embedded using a data uri.

Output:
6040c18b5322b032e7a392c41bbb75a8

ライセンスの検討

現在は resvg および usvg のライセンスからMPL-2.0をこのライブラリのライセンスに適用していたが、

MPL 2.0 FAQ

によれば、MPL部分を入手する方法を明記すれば他のライセンスでもよいとしていることがわかった。
(実際、自身で書いたソースコードにMPLを適用していないので名ばかりのMPLライセンスになっている)

WASM内に入手方法を書くことは困難であるため(バンドルされた)JSコードおよびREADMEに記述する。

肝心なこのライブラリのライセンスについてはMIT/Apache 2.0/BSDあたりから検討する。

デモページ

GitHub Pagesで動くサンプルを公開したい(建前)
自分がお手軽にSVG->PNGできるようにしたい(本音)

Text rendering does not seem to work in the online demonstration

I tried the online version with the following svgs that have text:

  <svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <text x="20" y="40">Example SVG text 1</text>
</svg>
<svg width="1200" height="1200" viewBox="0 0 1200 628" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><linearGradient id="backgroundGradient" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="black"></stop><stop offset="100%" stop-color="#3a2fa6"></stop></linearGradient><rect width="100%" height="100%" fill="url(#backgroundGradient)"></rect><text text-anchor="start" font-family="Roboto" font-size="140" fill="#d239f6"><tspan x="80" y="200">Future Frontend</tspan></text><text text-anchor="start" font-family="Roboto" font-size="80" fill="#d239f6"><tspan x="80" y="340">Demo</tspan></text><text text-anchor="start" font-family="ui-sans-serif, system-ui" font-size="40" font-weight="200" fill="white"><tspan x="80" y="440">The future of frontend reimagined</tspan></text><text text-anchor="start" font-family="ui-sans-serif, system-ui" font-size="40" font-weight="200" fill="white"><tspan x="80" y="520">5.6-9.6.2023</tspan></text><text text-anchor="start" font-family="ui-sans-serif, system-ui" font-size="40" font-weight="200" fill="white"><tspan x="380" y="520">Pörssitalo, Helsinki, Finland</tspan></text></svg>

For some reason, both fail to render the text portions. Note that the gradient shows up just fine in the latter example.

I was also able to reproduce the same behavior locally with a Cloudflare worker and I can share the code if that helps.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.