Created
April 4, 2020 18:40
-
-
Save ghanizadev/c9d1a54acb05e08c37793f0bfabf4440 to your computer and use it in GitHub Desktop.
Save PDF files from Flipsnack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http') | |
const fs = require('fs') | |
const path = require('path'); | |
const pdf = require('images-to-pdf'); | |
const read = async (i) => new Promise((resolve, reject) => { | |
options = { | |
host: process.env.HOST, | |
port: 80 | |
} | |
let path = process.env.ARG.split('_'); | |
path[1] = path[1].substring(1, path[1].length); | |
path[0] += `_${i}`; | |
path = path.join(''); | |
http.get({...options, path}, function(res){ | |
var imagedata = '' | |
res.setEncoding('binary') | |
res.on('data', function(chunk){ | |
imagedata += chunk | |
}) | |
res.on('end', async function(){ | |
await fs.writeFile(`./.tmp/${i}.jpeg`, imagedata, 'binary', function(err){ | |
if (err) throw err | |
console.log('Page %s saved.', i); | |
resolve(`./.tmp/${i}.jpeg`); | |
}) | |
}) | |
}) | |
}); | |
const save = async (indexes) => { | |
console.log('Saving to PDF...'); | |
await pdf(indexes, 'file.pdf'); | |
console.log('File saved!'); | |
} | |
const run = async () => { | |
var dir = './.tmp'; | |
if (!fs.existsSync(dir)){ | |
fs.mkdirSync(dir); | |
} | |
const indexes = []; | |
for(let j = 1; j <= process.env.PAGES; j++){ | |
let path = await read(j); | |
indexes.push(path); | |
} | |
console.log("Finished downloading"); | |
await save(indexes); | |
if (fs.existsSync('./.tmp')) { | |
fs.readdirSync('./.tmp').forEach((file, index) => { | |
const curPath = path.join('./.tmp', file); | |
if (fs.lstatSync(curPath).isDirectory()) { // recurse | |
deleteFolderRecursive(curPath); | |
} else { // delete file | |
fs.unlinkSync(curPath); | |
} | |
}); | |
fs.rmdirSync('./.tmp'); | |
} | |
} | |
run().catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hey how do I use this?