I'd like to run an SVG-PDF-converter, which processes all files in a folder and creates the PDF output files with the corresponding file names:
var fs = require('fs'),
PDFDocument = require('pdfkit'),
SVGtoPDF = require('svg-to-pdfkit'),
glob = require("glob"),
inputFiles = glob.sync('./input/**/*.svg');
for (let i = 0; i < inputFiles.length; i++) {
var doc = new PDFDocument(),
stream = fs.createWriteStream('./output/' + inputFiles[i] + '.pdf'),
svg = fs.readFileSync(inputFiles[i], 'utf-8');
SVGtoPDF(doc, svg, 0, 0);
doc.pipe(stream);
doc.end();
};
Obviously it doesn't work that way... How can I use variable file names in createWriteStream
?
Short answer: Use backquote like this
fs.createWriteStream(`./somefolder/${fileName}.pdf`)
var fileName = String(inputFiles[i]),
outputString = fileName.replace("input", "output"),
outputStringComplete = outputString.replace("svg", "pdf"),
stream = fs.createWriteStream(outputStringComplete);
You can do something like this to actually fetch the filename using regex. You will get the filenames then you can use this filename to create new file.
const fileDetails = glob.sync('yourpathtodir');
const regex = new RegExp(/[^\\\/]+(?=\.[\w]+$)|[^\\\/]+$/);
const fileNames = [];
fileDetails.forEach(el => fileNames.push(regex.exec(el)[0]));
console.log(fileNames);
for (let i = 0; i < fileNames.length; i++) {
var doc = new PDFDocument(),
stream = fs.createWriteStream(`./output/${fileNames[i]}.pdf`),
svg = fs.readFileSync(`${fileNames[i]}.svg`, 'utf-8'); // you might need to provide full name for file
SVGtoPDF(doc, svg, 0, 0);
doc.pipe(stream);
doc.end();
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.