const fs = require('fs') const express = require('express') const multer = require('multer') const childProcess = require('child_process') const bodyParser = require('body-parser') const PDF2HTMLEX_PATH = 'C:/Users/alan.colon/Downloads/pdf2htmlEX-win32-0.14.6-upx-with-poppler-data/pdf2htmlEX.exe' const phantom = require('phantom') const uuid = require('uuid') const upload = multer({ dest: 'temp/' }) const app = express() app.use(bodyParser.urlencoded({extended: false, limit: '100mb'})) app.use(express.static('./public')) app.post('/edit', upload.single('document'), (req, res) => { const pdfFile = req.file.path const htmlFile = `${req.file.path}.html` childProcess.exec(`"${PDF2HTMLEX_PATH}" --hdpi 200 --vdpi 200 --font-format ttf --no-drm 1 "${pdfFile}" "${htmlFile}"`, (err, stdout, stderr) => { if (err) { res.status(500).send(`
${err}\n\n${stdout}\n\n${stderr}
`) } else { fs.readFile('public/edit.html', (err, editHtml) => { fs.readFile(`${req.file.path}.html`, 'utf8', (err, data) => { if (err) { res.status(500).send(`
${err}\n\n${stdout}\n\n${stderr}
`) } else { res.status(200).send(data.replace('', `${editHtml}`)) } fs.unlink(pdfFile) fs.unlink(htmlFile) }) }) } }) }) app.post('/save', (req, res) => { console.log(req.body.html) const tmpUuid = uuid() const htmlPath = `temp/${tmpUuid}.html` const pdfPath = `temp/${tmpUuid}.pdf` const pageWidth = /\.w0{width:([\d\.]*)pt/.exec(req.body.html)[1] const pageHeight = /\.h0{height:([\d\.]*)pt/.exec(req.body.html)[1] fs.writeFile(htmlPath, req.body.html, 'utf8', async (err) => { const instance = await phantom.create() const page = await instance.createPage() page.property('paperSize', { width: pageWidth, height: pageHeight, margin: '0px' }) page.open(htmlPath) page.on('onLoadFinished', function(status) { if (status === 'success') { page.render(pdfPath, {format: 'pdf'}) setTimeout(() => { res.download(pdfPath, 'todo-preserve-filename.pdf', (err) => { if (err) { console.error(err) res.status(500).send(err) } fs.unlink(htmlPath) //fs.unlink(pdfPath) }) }, 5000) } else { res.status(500).send('Failed: ' + status) } }) }) }) app.listen('3003') console.log('http://localhost:3003')