Skip to content

Instantly share code, notes, and snippets.

@HardikDG
Last active August 26, 2018 05:06
Show Gist options
  • Save HardikDG/1e1cbfdea14c67073deaeba606807ad7 to your computer and use it in GitHub Desktop.
Save HardikDG/1e1cbfdea14c67073deaeba606807ad7 to your computer and use it in GitHub Desktop.
SVG to PDF using librsvg
var Rsvg = require('librsvg').Rsvg;
var fs = require('fs');
var path = require('path');
var currentfileNames = [];
function readFiles(dirname, onError) {
fs.readdir(dirname, function(err, filenames) {
if (err) {
onError(err);
return;
}
filenames.forEach(function(filename) {
// Stream SVG file into render instance.
console.log(filename);
if (filename != '.DS_Store') {
var svg = new Rsvg();
currentfileNames.push(__dirname + '/' + dirname + '/' + filename);
fs.createReadStream(__dirname + '/' + dirname + '/' + filename).pipe(svg);
// When finishing reading SVG, render and save as PDF image.
svg.on('finish', function() {
// console.log('SVG width: ' + svg.width);
// console.log('SVG height: ' + svg.height);
newPath = path.basename(currentfileNames.shift(), '.svg');
console.log(newPath);
fs.writeFile(__dirname + '/' + dirname + '/' + newPath + '.pdf', svg.render({
format: 'pdf',
width: svg.width,
height: svg.height
}).data, (error) => { if (error) {
console.log("error in write file" + error)
}});
});
}
});
});
}
readFiles('assets');
var Rsvg = require('librsvg').Rsvg;
var fs = require('fs');
var path = require('path');
var fileNames = [];
var assetDirName = "assets"
function readFiles(onError) {
fs.readdir(assetDirName, function(err, filenames) {
if (err) {
onError(err);
return;
}
fileNames = filenames;
createPDF();
});
}
function createPDF() {
if(fileNames.length == 0) {
console.log("Return" , fileNames.length);
return;
}
filename = fileNames[0];
console.log(filename)
if (filename != '.DS_Store') {
var svg = new Rsvg();
currentfileName = __dirname + '/' + assetDirName + '/' + filename;
fs.createReadStream(__dirname + '/' + assetDirName + '/' + filename).pipe(svg);
// When finishing reading SVG, render and save as PDF file.
svg.on('finish', function() {
// console.log('SVG width: ' + svg.width);
// console.log('SVG height: ' + svg.height);
newPath = path.basename(currentfileName, '.svg');
console.log('Finish: ',newPath);
fs.writeFile(__dirname + '/' + assetDirName + '/' + newPath + '.pdf', svg.render({
format: 'pdf',
width: svg.width,
height: svg.height
}).data, (error) => {
fileNames.shift();
createPDF();
if (error) {
console.log("error in write file" + error)
}});
});
} else {
fileNames.shift();
createPDF();
}
}
readFiles();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment