ConvertPdf.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const fs = require('fs-extra');
  2. const sax = require('./sax');
  3. const utils = require('../utils');
  4. const ConvertHtml = require('./ConvertHtml');
  5. class ConvertPdf extends ConvertHtml {
  6. check(data, opts) {
  7. const {inputFiles} = opts;
  8. return this.config.useExternalBookConverter &&
  9. inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'pdf';
  10. }
  11. async run(notUsed, opts) {
  12. if (!this.check(notUsed, opts))
  13. return false;
  14. await this.checkExternalConverterPresent();
  15. const {inputFiles, callback} = opts;
  16. const outFile = `${inputFiles.fileListDir}/${utils.randomHexString(10)}.xml`;
  17. //конвертируем в xml
  18. await this.execConverter(this.pdfToHtmlPath, ['-c', '-s', '-xml', inputFiles.sourceFile, outFile]);
  19. callback(50);
  20. const data = await fs.readFile(outFile);
  21. callback(60);
  22. //парсим xml
  23. let lines = [];
  24. let inText = false;
  25. let title = '';
  26. let i = -1;
  27. const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  28. if (!cutCounter && inText) {
  29. lines[i].text += text + ' ';
  30. if (i < 2)
  31. title += text + ' ';
  32. }
  33. };
  34. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  35. if (!cutCounter) {
  36. if (tag == 'text' && !inText) {
  37. inText = true;
  38. i++;
  39. let attrs = sax.getAttrsSync(tail);
  40. lines[i] = {
  41. text: '',
  42. top: (attrs.top && attrs.top.value ? attrs.top.value : null),
  43. left: (attrs.left && attrs.left.value ? attrs.left.value : null),
  44. };
  45. }
  46. }
  47. };
  48. const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  49. if (tag == 'text')
  50. inText = false;
  51. };
  52. let buf = this.decode(data).toString();
  53. sax.parseSync(buf, {
  54. onStartNode, onEndNode, onTextNode
  55. });
  56. //найдем параграфы и отступы
  57. console.log(lines.length);
  58. //формируем текст
  59. let text = ''
  60. text = title + "\n" + text;
  61. return await super.run(Buffer.from(text), {skipCheck: true, isText: true});
  62. }
  63. }
  64. module.exports = ConvertPdf;