server.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const fs = require('fs')
  2. const express = require('express')
  3. const multer = require('multer')
  4. const childProcess = require('child_process')
  5. const bodyParser = require('body-parser')
  6. const PDF2HTMLEX_PATH = 'C:/Users/alan.colon/Downloads/pdf2htmlEX-win32-0.14.6-upx-with-poppler-data/pdf2htmlEX.exe'
  7. const phantom = require('phantom')
  8. const uuid = require('uuid')
  9. const upload = multer({
  10. dest: 'temp/'
  11. })
  12. const app = express()
  13. app.use(bodyParser.urlencoded({extended: false, limit: '100mb'}))
  14. app.use(express.static('./public'))
  15. app.post('/edit', upload.single('document'), (req, res) => {
  16. const pdfFile = req.file.path
  17. const htmlFile = `${req.file.path}.html`
  18. childProcess.exec(`"${PDF2HTMLEX_PATH}" --hdpi 200 --vdpi 200 --font-format ttf --no-drm 1 "${pdfFile}" "${htmlFile}"`, (err, stdout, stderr) => {
  19. if (err) {
  20. res.status(500).send(`<pre>${err}\n\n${stdout}\n\n${stderr}</pre>`)
  21. } else {
  22. fs.readFile('public/edit.html', (err, editHtml) => {
  23. fs.readFile(`${req.file.path}.html`, 'utf8', (err, data) => {
  24. if (err) {
  25. res.status(500).send(`<pre>${err}\n\n${stdout}\n\n${stderr}</pre>`)
  26. } else {
  27. res.status(200).send(data.replace('</body>', `${editHtml}</body>`))
  28. }
  29. fs.unlink(pdfFile)
  30. fs.unlink(htmlFile)
  31. })
  32. })
  33. }
  34. })
  35. })
  36. app.post('/save', (req, res) => {
  37. console.log(req.body.html)
  38. const tmpUuid = uuid()
  39. const htmlPath = `temp/${tmpUuid}.html`
  40. const pdfPath = `temp/${tmpUuid}.pdf`
  41. const pageWidth = /\.w0{width:([\d\.]*)pt/.exec(req.body.html)[1]
  42. const pageHeight = /\.h0{height:([\d\.]*)pt/.exec(req.body.html)[1]
  43. fs.writeFile(htmlPath, req.body.html, 'utf8', async (err) => {
  44. const instance = await phantom.create()
  45. const page = await instance.createPage()
  46. page.property('paperSize', {
  47. width: pageWidth,
  48. height: pageHeight,
  49. margin: '0px'
  50. })
  51. page.open(htmlPath)
  52. page.on('onLoadFinished', function(status) {
  53. if (status === 'success') {
  54. page.render(pdfPath, {format: 'pdf'})
  55. setTimeout(() => {
  56. res.download(pdfPath, 'todo-preserve-filename.pdf', (err) => {
  57. if (err) {
  58. console.error(err)
  59. res.status(500).send(err)
  60. }
  61. fs.unlink(htmlPath)
  62. //fs.unlink(pdfPath)
  63. })
  64. }, 5000)
  65. } else {
  66. res.status(500).send('Failed: ' + status)
  67. }
  68. })
  69. })
  70. })
  71. app.listen('3003')
  72. console.log('http://localhost:3003')