Nodejs SVG image Download scheme

Source: Internet
Author: User
Tags git clone

Sometimes the user needs to save or download the displayed SVG diagram, but SVG itself cannot be saved as "right button-picture save as" like a picture, there are a variety of options, which are used to convert SVG into a picture and then download it.


To implement this scenario, using PHANTOMJS to provide third-party support on the basis of node. JS (if not https://nodejs.org/download installation), PHANTOMJS is a support Dom,canvas, Web standards such as SVG provide local support for WebKit, please click http://phantomjs.org/, below to fedora-based (Red Hat 4.4.7-4) As an example, first configure the environment, and then see the code example.


Environment configuration:
1. Execute the following command to install the PHANTOMJS compilation tool


sudo yum-y install gcc gcc-c++ make flex bison gperf ruby \
Openssl-devel freetype-devel fontconfig-devel libicu-devel sqlite-devel \
Libpng-devel Libjpeg-devel
2. Execute the following command to download the PHANTOMJS source code and compile it


git clone git://github.com/ariya/phantomjs.git
CD PHANTOMJS
Git Checkout 2.0
./build.sh
This process is slow and takes thirty or forty minutes depending on the performance of the operating system. The executable file generated after compilation is/root/phantomjs/bin/and executed after entering this directory./phantom can be run.


3. Set path to execute the following command


Cd/etc
Vim profile
After opening the profile file, press the INSERT key, move the cursor to the end of the file, enter the line, add the following code


Export path= "/root/phantomjs/bin: $PATH"
4. Third-party library references


Create Package.json


{
"Name": "Test",
"Version": "1.1.1",
"description": "Convert SVG to image in server side by Phantomjs and Nodejs",
"Main": "Phantom.js",
"Dependencies": {
"Express": "Latest",
"Phantom": "Latest"
},
"Devdependencies": {},
"Scripts": {
"Start": "Node Phantom.js"
},
"keywords": [
""
],
"Author": "",
"License": "No"
}


The Package.json file defines the various modules required for this project, as well as the configuration information (such as name, version, license, and so on) of the project, where the dependent libraries are defined in the Dependencies node, and the NMP install is downloaded automatically. For details, please go to http://javascript.ruanyifeng.com/nodejs/packagejson.html#toc0


You need to introduce the express and phantom libraries, which are explained below:


Express Library is used to turn on HTTP service, please enter http://expressjs.com/zh/4x/api.html for details.


The Phantom Library is a bridge linking phantomjs and node, because PHANTOMJS is not nodejs module in itself, making phantomjs unusable with NPM, With this bridge, you can use both NPM and the Phantomjs method. For details, please go to Https://github.com/sgentle/phantomjs-node.


This is the end of the environment configuration, if all goes well see the following code example:


code example:
1. File structure


Create a folder, such as Phantomjstest, with a index.html, a phantom.js, and a Package.json file.


Index.html:


<! DOCTYPE html>
<title>Shell</title>
<body>
<div id= "Viewport" style= "Display:inline-block;" >
</div>
</body>
Phantom.js


var phantom = require (' phantom ');
var fs = require (' FS ');
var express = require (' Express ');
var app = Express ();


App.get ('/', function (req, res) {
SVG html
var svgstring = "<svg width= ' height= '" ><g><rect x= ' 0 ' y= ' 0 ' width= ' [height= '] ' fill= ' black ' /></g></svg> ";
Creating an Phantom instance
Phantom.create (function (ph) {
Create a Page instance
Ph.createpage (function (page) {
Load page
Page.open ("index.html", function (status) {
Add SVG to the page, set the clip's rectangle
Page.evaluate (function (svgstring) {
var selector = "#Viewport";
Document.queryselector (selector). InnerHTML = svgstring;
return Document.queryselector (selector). Getboundingclientrect ();
},
function (Result) {
Set Clip Box
Page.set ("ClipRect", result);
Generate PNG pictures
Page.render (' A.png ', {
Format: ' PNG ',
Quality: ' 100 '
}, function () {
Download image to Client
Res.download (' A.png ', "test.png");
});
},


svgstring);
});
});
});
});


var server = App.listen (3040, function () {
var host = Server.address (). Address;
var port = server.address (). Port;
Console.log (' Example app listening at http://%s%s ', host, Port);
});
The example above is an SVG HTML string


<svg width= ' height= ' ><g><rect x= ' 0 ' y= ' 0 ' width= ' [height= '] fill= ' ></svg>
Insert into the index.html page, which is a 100-wide, black-filled rectangle, and then use PHANTOMJS to generate a a.png picture, and then download it, where the name of the picture can be


Res.download (&LT;SOURCEFILEPATH&GT;, <downloadfilename>);
Custom.


Run:
After everything is ready, take a look at the effect below. Execute command:


NPM Install
Node Phantom.js
The console appears with the following interface:


In the browser, enter the address http://host:3040 (the host is the Linux IP), you can download a picture.


Open Test.png, show

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Nodejs SVG image Download scheme

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.