Example #1
0
	}, function (data) {
		if (!data.errors) {
			var r1 = /width="/;
			var r2 = /ex"/;
			var m1 = data.svg.search(r1) + 7;
			var m2 = m1 + data.svg.slice(m1).search(r2);
			var width = parseInt(data.svg.slice(m1,m2));  

			var r1 = /height="/;
			var r2 = /ex"/;
			var m3 = data.svg.search(r1) + 8;
			var m4 = m3 + data.svg.slice(m3).search(r2);
			var height = parseInt(data.svg.slice(m3,m4));

			var factor = 100/width;
			width = (width*factor).toString()

			factor = (300/4)/height;
			height = (height*factor).toString()

			var r = /width=".*ex" height=".*ex"/;
			data.svg = data.svg.replace(r, 'width="' + width + '" height="' + height + '"')

			var buf = new Buffer(data.svg);
		 	callback(svg2png(buf, { width: 450, height: 100 }));
	  	}
	});
Example #2
0
 stratigraphyServices.drawStratigraphy(stratig, width, function (svgresult) {
     // we replace standard href by deprecated xlink:href in the svg output by recent svg.js (2.6.3)
     // as it is not yet supported by latest svg2png/phantomjs (2.1.1) and all embedded images
     // are removed otherwise
     svgresult = svgresult.replace(/href/g, 'xlink:href');
     if(format == 'png') {
         const svg2png = require("svg2png");
         svg2png(svgresult, { width: width }).then(function(buffer) {
             res.writeHead(200, {'Content-Type': 'image/png'});
             res.write(buffer);
             res.end()}).catch(function(e) { console.error(e)});
     }
     else if(format == 'pngi') {
         var Inkscape = require('inkscape')
         inkscape = new Inkscape(['-e']);
         res.writeHead(200, {'Content-Type': 'image/png'});
         inkscape.end(svgresult);
         inkscape.pipe(res);
     }
     else if(format == 'pdf'){
         var Inkscape = require('inkscape')
         inkscape = new Inkscape(['--export-pdf']);
         res.writeHead(200, {'Content-Type': 'application/pdf'});
         inkscape.end(svgresult);
         inkscape.pipe(res);
     }
     else { // defaulting to svg format
         res.writeHead(200, {'Content-Type': 'image/svg+xml'});
         res.write(svgresult);
         res.end();
     }
 });
                nearest: (sourceset, properties, offset, callback) => {
                    print('Image:nearest', `Find nearest icon to ${ properties.width }x${ properties.height } with offset ${ offset }`);

                    const offsetSize = offset * 2,
                        width = properties.width - offsetSize,
                        height = properties.height - offsetSize,
                        sideSize = Math.max(width, height),
                        svgSource = _.find(sourceset, (source) => source.size.type == 'svg');

                    let nearestIcon = sourceset[0],
                        nearestSideSize = Math.max(nearestIcon.size.width, nearestIcon.size.height);

                    if (svgSource) {
                            print('Image:nearest', `SVG source will be saved as ${ width }x${ height }`);
                            svg2png(svgSource.file, { height, width })
                                .then((resizedBuffer) => callback(null, {
                                    size: sizeOf(resizedBuffer),
                                    file: resizedBuffer
                                }))
                                .catch(callback);
                    } else {
                        _.each(sourceset, (icon) => {
                            let max = Math.max(icon.size.width, icon.size.height);

                            if ((nearestSideSize > max || nearestSideSize < sideSize) && max >= sideSize) {
                                nearestIcon = icon;
                                nearestSideSize = max;
                            }
                        });

                        callback(null, nearestIcon);
                    }
                },
Example #4
0
  specification.sizes.forEach((size) => {
    let dest = `${specification.fileName}${specification.append[specification.sizes.indexOf(size)]}.png`;
    dest = path.join(specification.outputPath + dest);

    svg2png(buffer, { width: size, height: size }).then((output) => {
      fs.writeFile(dest, output, (err) => {
        if (err) throw err;
      });
    });
  });
Example #5
0
 const mathImgs = await Promise.map(mathSvgs, async svg => {
   const img = path.join(this.workDir, NOTE_MATH_PATH, `${Evermark.genHash(svg.data)}.png`)
   await svg2png(Buffer.from(svg.data), { width: svg.width * 2, height: svg.height * 2 }).then(
     buffer => fileUtils.writeFile(img, buffer)
   )
   return {
     src: `${img.slice(path.join(this.workDir, NOTE_PATH).length + 1)}`,
     width: svg.width,
     height: svg.height
   }
 })
Example #6
0
 fs.writeFile(svgFile, req.rawBody, function(err) {
     if (err) {
         return next(err);
     }
     svg2png(svgFile, pngFile, function(err) {
         if (err) {
             return next(err);
         }
         res.send(imgUUID);
     });
 });
Example #7
0
 return through.obj((file, encoding, callback) => {
   svg2png(file.contents, options)
     .then((buffer) => {
       callback(
         null,
         new Vinyl({
           path: file.path,
           contents: buffer
         })
       )
     })
     .catch(callback)
 })
Example #8
0
app.post('/export', function (req, res) {
    var filename = makeID(8),
      dest = __dirname + '/charts/' + filename + '.' + req.body.format;

    svg2png(req.body.content, dest, 2, function (err) {
      if (err) {
        res.status(500).send(err);
        console.error(err);
        return;
      }
      console.log("Export success");
      res.status(201).send('charts/' + filename + '.' + req.body.format);
    });
});
Example #9
0
			html : content, done : function(errors, window) {
				box = window.document.querySelector('#box');
			    chart.renderSvgToPng(data, svgname);
			    // convert to png
			    svg2png(svgname, filename, function (err) {
			        if(err) {
			            console.log(svgname + ' to ' + filename + ' failed.', err);
			            response.send({"msg": "fail"});
			        } else {
			            console.log(svgname + ' to ' + filename + ' successfully.');
			            response.send({"msg": "ok", "filename": filename});
			        }
	    		});
		    }
Example #10
0
        fs.exists("svg/" + item.name + ".svg", function (exists) {
            if (exists) {
                // COPY FILE TO DIST
                fs.createReadStream("svg/" + item.name + ".svg").pipe(fs.createWriteStream("../dist/svg/" + item.name + ".svg"));

                // CREATE PNG
                svg2png("svg/" + item.name + ".svg", "../dist/png/" + item.name + ".png", 1, function (err) {
                   if (err){
                       console.error("ERROR: creating png file: " + item.name)
                   }
                });
            } else {
                console.error("ERROR: SVG file does not exist: " + item.name)
            }
        })
Example #11
0
  request.on('end', function () {
  	console.time('svg2png process time');
		var success = true;
		var filename = "convert/" + (new Date()).getTime();
		var infile = filename + ".svg";
		// Evidently, the extension determines target format
		var outfile = filename + ".jpg";
		fs.writeFileSync(infile, body);
 		svg2png(infile, outfile, 2, function (err) {
			// JPGs for everyone!
    		success = false;
    		if (err) console.log(err);
    		else {
					response.writeHead(200, {"Content-Type": "text/plain"});
					response.end(outfile);
		  		console.timeEnd('svg2png process time');    			
    			}
			});
  });
Example #12
0
			renderBoxImg = function(data, units, svgFile, pngFile) {

		        // produce svg file
		        var svgGraph = d3.select(box)
		                         .attr('xmlns', 'http://www.w3.org/2000/svg');

		        // render d3 line chart
		        render(data, units);

		        var svgXML = (new xmldom.XMLSerializer()).serializeToString(svgGraph[0][0]);
		        fs.writeFile(svgFile, svgXML);

		        // convert to svg to png
		        svg2png(svgFile, pngFile, function (err) {
		            if(err) {
		                console.log(svgFile + ' to ' + pngFile + ' failed.', err);
		                response.send({"msg": "fail"});
		            } else {
		                console.log(svgFile + ' to ' + pngFile + ' successfully.');
		                response.send({"msg": "ok", "filename": pngFile});
		            }
		        });
		    }; // renderBoxImg end
Example #13
0
      var renderMapImg = function(data, svgFile, pngFile) {
        var render = function() {
          var svg = d3.select(map);

          var myMap = map().width(323).height(323);
          d3.select(svg)
            .datum() // pass data here
            .call(myMap);

          // svg.selectAll("circle")
          //     .data([32, 57, 112, 293])
          //   .enter().append("circle")
          //     .attr("cy", 60)
          //     .attr("cx", function(d, i) { return i * 100 + 30; })
          //     .attr("r", function(d) { return Math.sqrt(d); });
        }

        // produce svg file
        var svgGraph = d3.select(map)
          .attr('xmlns', 'http://www.w3.org/2000/svg');

        // render d3 chart
        render();

        var svgXML = (new xmldom.XMLSerializer()).serializeToString(svgGraph[0][0]);
        fs.writeFile(svgFile, svgXML);

        // convert svg to png
        svg2png(svgFile, pngFile, function (err) {
          if(err) {
            console.log(svgFile + ' to ' + pngFile + ' failed.', err);
          } else {
            console.log(svgFile + ' to ' + pngFile + ' successfully.');
          }
        });
      };
Example #14
0
    grunt.registerMultiTask('svg_sprites', 'Takes SVGs and creates a scalable SVG sprite with PNG fallback', function () {
        // Merge task-specific and/or target-specific options with these defaults.
        var data = this.data,
            src = data.src,
            dest = data.dest || './',
            tasks = [],
            srcFiles,
            combined,
            css,
            previewPage,
            previewPath,
            previewContent,
            svgSpritePath,
            svgSpriteDest,
            svgContent,
            cssPath,
            cssContent,
            svgPath,
            pngPath,
            options = this.options({
                classNameSuffix: '',
                svg: {
                    sprite: 'sprites/svg-sprite.svg'
                },
                className: '.%f',
                svgId:     '%f',
                cssFile:   'css/sprites.css',
                svgPath:   '../%f',
                pngPath:   '../%f',
                preview: {
                    sprite: 'preview-svg-sprite.html',
                    defs: 'preview-svg.html'
                },
                refSize: 26,
                padding: 0,
                defs: false,
                hideSvg: true,
                generatePreview: true,
                generateCSS: true
            });

        // Load in all images from the src
        srcFiles = grunt.file.expand(src);
        if (!srcFiles.length) {
            grunt.log.writeln('No matched files');
            return;
        }

        srcFiles.forEach(function (file) {
            var contents = grunt.file.read(file),
                fileInfo = {
                    path: file
                };

            svgutil.addSvgFile(contents, fileInfo, tasks, function () {
                return null;
            });
        });


        combined = svgutil.buildSVGSprite(options.classNameSuffix, tasks, options);
        css      = cssRender.render(combined.spriteData, options);

        if (options.generatePreview) {
            previewPage = preview.render(css.elements, combined.content, options);
            previewPath = options.defs ? options.preview.defs : options.preview.sprite;
            previewContent = new Buffer(previewPage.svgSprite.content);

            grunt.file.write(path.join(dest, previewPath), previewContent);
        }

        svgSpritePath = options.defs ? options.svg.defs : options.svg.sprite;
        svgSpriteDest = path.join(dest, svgSpritePath);
        svgContent = new Buffer(combined.content);

        grunt.file.write(svgSpriteDest, svgContent);

        if (options.generateCSS) {
            cssPath = options.cssFile;
            cssContent = new Buffer(css.content);

            grunt.file.write(path.join(dest, cssPath), cssContent);
        }

        svgPath = path.resolve(svgSpriteDest);
        pngPath = path.resolve(utils.swapFileName(svgSpriteDest));

        svg2png(svgPath, pngPath, function (err) {
            if (err) {
                grunt.fail.fatal('Could not create the PNG format');
            }
        });

    });
Example #15
0
     .then(function (buffer) {
     return svg2png(buffer, _this.options);
 })
Example #16
0
var svg2png = require('svg2png');

svg2png('twentytwo.svg', 'twentytwo.iconset/icon_16x16.png', 1/16, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_16x16@2x.png', 1/8, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_32x32.png', 1/8, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_32x32@2x.png', 1/4, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_128x128.png', 1/2, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_128x128@2x.png', 1, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_256x256.png', 1, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_256x256@2x.png', 2, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_512x512.png', 2, function(e) {});
svg2png('twentytwo.svg', 'twentytwo.iconset/icon_512x512@2x.png', 4, function(e) {});

svg2png('background.svg', 'background.png', 1, function(e) {});
Example #17
0
var svg2png = require('svg2png');

var jdenticon = require("jdenticon"),
    SvgContext = require("./SvgContext.js"),
    fs = require("fs"),
    size = 1000,
    hash = "cd53f27dd778822b3c9f1074de0dd731", // md5 hash
    ctx = new SvgContext(size, size);

jdenticon.drawIcon(ctx, hash, size);
fs.writeFileSync(__dirname + "/testicon.svg", ctx.toSvg());

svg2png(__dirname + "/testicon.svg", __dirname + "/dest.png", function (err) {
  console.log(err);
});
 .then((src) => svg2png(src, { width: targetFile.width, height: targetFile.height }))
Example #19
0
var svg2png = require('svg2png');
var ncp = require('ncp');
var path = require('path');

svg2png(path.resolve('src/images/toggle.svg'), path.resolve('src/images/toggle.png'), 1.0, function (err) {
	ncp('src/images/toggle.png', 'dist/images/toggle.png');
});
Example #20
0
function generateImage(response, chart, series, values, querySettings) {
		 
	// Default graph setting cloning
	var settings = graphSettings();	 
	 
	mergeQuerySettingsAndDefaultSettings(querySettings, settings);
		
	// Assign serie values
	settings.series = series;
	
	// Assign X Axis labels
	if (!settings.xAxis)
		settings.xAxis = new Object();
		
	settings.xAxis.values = values;

	switch(chart.toUpperCase()) {
		case "LINE":
			chart = jGraf.lineChart(settings);
			break;
		case "PIE":
			chart = jGraf.pieChart(settings);
			break;
		case "POLAR":
			chart = jGraf.polarChart(settings);
			break;
		case "BAR":
		default:
			chart = jGraf.barChart(settings);
			break;
	}

	var svg = chart.toString();

	if (querySettings.format && querySettings.format.toLowerCase() == 'svg') {
		response.setHeader("Content-Type", "image/svg+xml");
	    response.write(svg, "binary");
	    response.end();
	    return;
	}
	
	var fileId = guid();
	var SVG = "tmp/" + fileId + ".svg";
	var PNG = "tmp/" + fileId + ".png";
	
	fs.writeFileSync(SVG, svg); 
	console.log("File SVG generated");	
	
	svg2png(SVG, PNG, function (err) {
	    if(err) {
	        console.log(err);
	        
	        deleteFile(SVG);
	        
	        response.setHeader("Content-Type", "text/html");
	        response.end("There was an error.");
	    } else {
	        console.log("The PNG file was saved");
	        
	        var content = fs.readFileSync(PNG);
	        deleteFile(SVG);
	        deleteFile(PNG);
	         
	        response.setHeader("Content-Type", "image/png");
	        response.write(content, "binary");
	        response.end();
	    }
	});
};
Example #21
0
        data['resources']['compared_tasks'].push(
          compare_data['resources']['tasks'][cKey]
        );
      }
    }
  }
}
gant.init(data.range, config);
gant.update(data.resources);

const format = program.format || 'html';
const stdout = program.stdout;

const out = gant.out(format);
if (stdout) {
  console.log(out);
} else {
  let output_file = program.output;
  if (output_file == undefined) {
    let filename = path.basename(filepath);
    output_file = filename.replace(path.extname(filepath), '.' + format);
  }
  if (format == 'png') {
    svg2png(out)
      .then(buffer => fs.writeFileSync(output_file, buffer))
      .catch(e => console.error(e));
  } else {
    fs.writeFileSync(output_file, out);
  }
}
Example #22
0
async function generate_svg(svg_text, T)
{
	let data = await svg2png(new Buffer(svg_text));
	let media_id = await uploadMedia(data.toString('base64'), T);
	return media_id;
}
Example #23
0
function render_png(data, callback, error) {
  svg2png(new Buffer(data), {
    width: /width="([\d.]+)ex"/.exec(data)[1] * 9,
    height: /height="([\d.]+)ex"/.exec(data)[1] * 9,
  }).then(callback).catch(error);
}
Example #24
0
var svg2png = require("svg2png");
svg2png("logo.svg", "logo.png", function (err) {
    if(err) console.log(err);
});
Example #25
0
 .then(buffer => svg2png(buffer, {
   width: parseInt(file.markup.match(rwidth)[1]),
   height: parseInt(file.markup.match(rheight)[1])
 }))
Example #26
0
 .then(input => svg2png(input, size))