Giter Club home page Giter Club logo

svg-to-img's Introduction

svg-to-img

A node.js library to convert SVGs to images built with Puppeteer.

Coveralls github CircleCI build node version npm version npm monthly downloads

Getting Started

Installation

To use svg-to-img in your project, run:

npm install svg-to-img -S

Note: When you install svg-to-img, it downloads a recent version of Chromium (~170Mb Mac, ~282Mb Linux, ~280Mb Win) that is guaranteed to work with the library.

Debian

If you're planning on running svg-to-img on Debian, you will need to manually install the following dependencies:

#!/bin/bash

apt-get update
apt-get install -yq gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 \
  libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 \
  libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 \
  libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 \
  ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget

Usage

Caution: svg-to-img uses async/await which is only supported in Node v7.6.0 or greater.

Example - converting a svg to png:

const svgToImg = require("svg-to-img");

(async () => {
  const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toPng();
  
  console.log(image);
})();

Example - converting a svg to jpeg and saving the image as example.jpeg:

const svgToImg = require("svg-to-img");

(async () => {
  await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toJpeg({
    path: "./example.jpeg"
  });
})();

Example - resizing a svg proportionally and converting it to webp:

const svgToImg = require("svg-to-img");

(async () => {
  const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toWebp({
    width: 300
  });
  
  console.log(image);
})();

Example - converting a svg to base64-encoded png:

const svgToImg = require("svg-to-img");

(async () => {
  const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toPng({
    encoding: "base64"
  });
  
  console.log(image);
})();

API Documentation

svgToImg.from(svg)

  • svg <Buffer|string> SVG markup to be converted.
  • returns: <[Svg]> a new Svg object.

The method returns a svg instance based on the given argument.

svg.to([options])

  • options <[Object]> Options object which might have the following properties:
    • path <[string]> The file path to save the image to. The image type will be inferred from file extension. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the image won't be saved to the disk.
    • type <[string]> Specify image type, can be either png, jpeg or webp. Defaults to png.
    • quality <[number]> The quality of the image, between 0-1. Defaults to 1. Not applicable to png images.
    • width <[number]> width of the output image. Defaults to the natural width of the SVG.
    • height <[number]> height of the output image. Defaults to the natural height of the SVG.
    • clip <[Object]> An object which specifies clipping region of the output image. Should have the following fields:
      • x <[number]> x-coordinate of top-left corner of clip area
      • y <[number]> y-coordinate of top-left corner of clip area
      • width <[number]> width of clipping area
      • height <[number]> height of clipping area
    • background <[string]> background color applied to the output image, must be a valid CSS color value.
    • encoding <[string]> Specify encoding, can be either base64, utf8, binary or hex. Returns a Buffer if this option is omitted.
  • returns: <[Promise]<Buffer|String>> Promise which resolves to the output image.

svg.toPng([options])

  • options <[Object]> Optional options object that can have the same properties as the to method except for the type property.
  • returns: <[Promise]<Buffer|String>> Promise which resolves to the png image.

This method is simply a shorthand for the to method.

svg.toJpeg([options])

  • options <[Object]> Optional options object that can have the same properties as the to method except for the type property.
  • returns: <[Promise]<Buffer|String>> Promise which resolves to the jpeg image.

This method is simply a shorthand for the to method.

svg.toWebp([options])

  • options <[Object]> Optional options object that can have the same properties as the to method except for the type property.
  • returns: <[Promise]<Buffer|String>> Promise which resolves to the webp image.

This method is simply a shorthand for the to method.

Built with

  • node.js - Cross-platform JavaScript run-time environment for executing JavaScript code server-side.
  • Puppeteer - Headless Chrome Node API.
  • TypeScript - Typed superset of JavaScript that compiles to plain JavaScript.
  • Jest - Delightful JavaScript Testing.

Contributing

When contributing to this project, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.

Update the README.md with details of changes to the library.

Execute npm run test and update the tests if needed.

Authors

License

This project is licensed under the MIT License - see the LICENSE file for details.

svg-to-img's People

Contributors

dependabot[bot] avatar etienne-martin avatar weaintplastic 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

Watchers

 avatar  avatar  avatar

svg-to-img's Issues

Failed to launch chrome on AWS elastic-beanstalk.

#6 related
Error:
image (8)

I looked around for this issue and I think resolution for this is to install the system dependencies mentioned in the docs. It would be great if the documentation also includes the dependencies list for Amazon Linux 2 (elastic-beanstalk.)

Thank you :)

Malformed image

Hi I am trying to save this SVG image, which has embedded image and I am getting a Malformed Image.

Screen Shot 2020-10-26 at 1 44 46 pm

My code is simple const imageSvgToImg = await svgToImg.from(startSVG+ renderedMessage).toPng()

The SVG which is in a text string inside renderedMessage is attached here

buzzypng_Joe_Bloggs 1.svg.zip

Any help appreciated

300 dpi svg to png conversion

I have a svg file that I want converted to a 300 dpi png file of a certain size. How would I do that with svg-to-img I can't quite wrap my head around it...

Cannot read properties of undefined (reading 'setOfflineMode')

I am converting about 50 files in a loop, and about once every couple of hundred I get an error:

/home/righthaze/.../node_modules/svg-to-img/dist/index.js:58
    await page.setOfflineMode(true);
               ^

TypeError: Cannot read properties of undefined (reading 'setOfflineMode')
    at convertSvg (/home/.../node_modules/svg-to-img/dist/index.js:58:16)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async /home/.../index.js:37:9

My code:

const svgToImg = require("svg-to-img")

for (let sample = 0; sample < 50000; sample++) {
  const samplePath = path.join(samplesPath, sample.toString())
  fs.mkdirSync(samplePath, { recursive: true })
  const { path: svgPath } = await mega.getCaptcha()
  const step = 1.0 / 50

  for (let i = 1.0; i > step; i = i - step) {
    let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="298" height="100" viewBox="0,0,298,100">`
    svg += `<path fill="none" stroke="black" d="${ calcCaptchaPath(i, svgPath) }"></path>`
    svg += `</svg>`
    await svgToImg.from(svg).toJpeg({
      path: path.join(samplePath, i.toString() + ".jpg")
    });
  }
  1. Node: v16.14.0
  2. OS: Ubuntu 20.04
  3. svg-to-img: 2.0.9

Cannot read property 'setOfflineMode' of undefined

Im getting this error from time to time when converting my svg to jpeg files in my node.js project.

Whole error:
(node:38761) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'setOfflineMode' of undefined
at convertSvg (/Users/Caleb/Desktop/Hawk/node_modules/svg-to-img/dist/index.js:58:16)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Client. (/Users/Caleb/Desktop/Hawk/index.js:452:5)
(node:38761) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:38761) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Error: Protocol error (Runtime.evaluate): Target closed.

Sometimes when I try to convert multiple (50+) svg files simultaneously, I get the following error:

Error: Protocol error (Runtime.evaluate): Target closed.
    at /home/sawent/Documents/Utveckling/repos/ncc-calculation/node_modules/puppeteer/lib/Connection.js:196:56
    at new Promise (<anonymous>)
    at CDPSession.send (/home/sawent/Documents/Utveckling/repos/ncc-calculation/node_modules/puppeteer/lib/Connection.js:195:12)
    at ExecutionContext.evaluateHandle (/home/sawent/Documents/Utveckling/repos/ncc-calculation/node_modules/puppeteer/lib/ExecutionContext.js:61:77)
    at ExecutionContext.evaluate (/home/sawent/Documents/Utveckling/repos/ncc-calculation/node_modules/puppeteer/lib/ExecutionContext.js:46:31)
    at Frame.evaluate (/home/sawent/Documents/Utveckling/repos/ncc-calculation/node_modules/puppeteer/lib/FrameManager.js:299:20)
    at processTicksAndRejections (internal/process/task_queues.js:94:5) {
  message: 'Protocol error (Runtime.evaluate): Target closed.'
}

It seems that increasing the timeout time in scheduleBroswerForDestruction() resolved the issue for me.

UnhandledPromiseRejectionWarning: Error: Evaluation failed

Running a clean install, using your logo.svg and your code:

const svgToImg = require("svg-to-img");
(async () => {
  const image = await svgToImg.from("logo.svg").toPng();
  console.log(image);
})();

Result in:

(node:2990) UnhandledPromiseRejectionWarning: Error: Evaluation failed: Error: Malformed SVG
    at Image.onError (__puppeteer_evaluation_script__:57:20)
    at ExecutionContext.evaluateHandle (/Users/xxx/test/node_modules/puppeteer/lib/ExecutionContext.js:90:15)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
  -- ASYNC --
    at ExecutionContext.<anonymous> (/Users/xxx/test/node_modules/puppeteer/lib/helper.js:144:27)
    at ExecutionContext.evaluate (/Users/xxx/test/node_modules/puppeteer/lib/ExecutionContext.js:58:31)
    at ExecutionContext.<anonymous> (/Users/xxx/test/node_modules/puppeteer/lib/helper.js:145:23)
    at Frame.evaluate (/Users/xxx/test/node_modules/puppeteer/lib/FrameManager.js:447:20)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
  -- ASYNC --
    at Frame.<anonymous> (/Users/xxx/test/node_modules/puppeteer/lib/helper.js:144:27)
    at Page.evaluate (/Users/xxx/test/node_modules/puppeteer/lib/Page.js:777:43)
    at Page.<anonymous> (/Users/xxx/test/node_modules/puppeteer/lib/helper.js:145:23)
    at convertSvg (/Users/xxx/test/node_modules/svg-to-img/dist/index.js:66:31)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)

Using SVG string

is it possible to use an svg string or an svg as a data url into a base64 png? im using nodejs

Cannot read property 'setOfflineMode' of undefined

When trying to convert several SVGs I ran into this:

TypeError: Cannot read property 'setOfflineMode' of undefined
    at convertSvg (/home/bauke/mi-skin/node_modules/svg-to-img/dist/index.js:32:16)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

My code:

svgPaths.forEach((file) => {
  fs.readFile(file, { encoding: 'utf-8' }, async (error, data) => {
    if (error) console.log(error)
    await svgToImg.from(data).to({
      type: 'png',
      path: path.join(dist, path.basename(file, '.svg') + '.png')
    }).catch((reason) => { console.log(reason) })
  })
})

I'm not sure if it's me doing something wrong or the package as I've tried doing just single files and those worked fine.

You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection

 Error: Failed to launch chrome! spawn /app/node_modules/puppeteer/.local-chromium/linux-555668/chrome-linux/chrome ENOENT
 TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md
     at onClose (/app/node_modules/puppeteer/lib/Launcher.js:255:14)
     at ChildProcess.helper.addEventListener.error (/app/node_modules/puppeteer/lib/Launcher.js:246:64)
     at emitOne (events.js:116:13)
     at ChildProcess.emit (events.js:211:7)
     at Process.ChildProcess._handle.onexit (internal/child_process.js:196:12)
     at onErrorNT (internal/child_process.js:372:16)
     at _combinedTickCallback (internal/process/next_tick.js:138:11)
     at process._tickDomainCallback (internal/process/next_tick.js:218:9)```

Typing file missing in /dist directory

Awesome library! Unfortunately, my tsc build currently fails with the following error:

node_modules/svg-to-img/dist/index.d.ts(2,45): error TS2307: Cannot find module './typings/types'.

The types.d.ts is simply missing in the NPM distribution. Any chance to get this fixed?

ReferenceError: window is not defined

Hi, when running on Debian I came across this error, tried look at Puppeteer's issues and found nothing relevant so trying my hand here first.

ReferenceError: window is not defined
     at scheduleBrowserForDestruction (/home/bauke/tildey/node_modules/svg-to-img/dist/index.js:44:5)
     at convertSvg (/home/bauke/tildey/node_modules/svg-to-img/dist/index.js:75:5)
     at <anonymous>
     at process._tickDomainCallback (internal/process/next_tick.js:229:7)

I noticed there's one reference to window here.

example code doesn't work

When I tried implementing the example code given, all I receive in return is a blank white image, which leads me to suspect either the svg image isn't being fully loaded in properly (program possibly continues as soon as legitimate results are received but doesn't wait for entire image), or the source link is broken (but I saw in a codepen screenshot that it worked fine in an svg html tag).

Also, I've tried other svg url links, and it returns an error statement saying it's a malformed svg image, so I'm not sure what to make of that as well.

(I have the correct version of Node (v8.something) as well so that's not the issue)

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.