ConvertPdf.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const sax = require('./sax');
  4. const utils = require('../utils');
  5. const ConvertHtml = require('./ConvertHtml');
  6. class ConvertPdf extends ConvertHtml {
  7. check(data, opts) {
  8. const {inputFiles} = opts;
  9. return this.config.useExternalBookConverter &&
  10. inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'pdf';
  11. }
  12. async run(notUsed, opts) {
  13. if (!this.check(notUsed, opts))
  14. return false;
  15. await this.checkExternalConverterPresent();
  16. const {inputFiles, callback} = opts;
  17. const outFile = `${inputFiles.filesDir}/${utils.randomHexString(10)}.xml`;
  18. //конвертируем в xml
  19. let perc = 0;
  20. await this.execConverter(this.pdfToHtmlPath, ['-c', '-s', '-xml', inputFiles.sourceFile, outFile], () => {
  21. perc = (perc < 80 ? perc + 10 : 40);
  22. callback(perc);
  23. });
  24. callback(80);
  25. const data = await fs.readFile(outFile);
  26. callback(90);
  27. //парсим xml
  28. let lines = [];
  29. let images = [];
  30. let loading = [];
  31. let inText = false;
  32. let bold = false;
  33. let italic = false;
  34. let title = '';
  35. let prevTop = 0;
  36. let i = -1;
  37. const loadImage = async(image) => {
  38. const src = path.parse(image.src);
  39. let type = 'unknown';
  40. switch (src.ext) {
  41. case '.jpg': type = 'image/jpeg'; break;
  42. case '.png': type = 'image/png'; break;
  43. }
  44. if (type != 'unknown') {
  45. image.data = (await fs.readFile(image.src)).toString('base64');
  46. image.type = type;
  47. image.name = src.base;
  48. }
  49. }
  50. const putImage = (curTop) => {
  51. if (!isNaN(curTop) && images.length) {
  52. while (images.length && images[0].top < curTop) {
  53. i++;
  54. lines[i] = images[0];
  55. images.shift();
  56. }
  57. }
  58. }
  59. const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  60. if (!cutCounter && inText) {
  61. let tOpen = (bold ? '<b>' : '');
  62. tOpen += (italic ? '<i>' : '');
  63. let tClose = (italic ? '</i>' : '');
  64. tClose += (bold ? '</b>' : '');
  65. lines[i].text += `${tOpen}${text}${tClose} `;
  66. if (i < 2)
  67. title += text + ' ';
  68. }
  69. };
  70. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  71. if (!cutCounter) {
  72. if (inText) {
  73. switch (tag) {
  74. case 'i':
  75. italic = true;
  76. break;
  77. case 'b':
  78. bold = true;
  79. break;
  80. }
  81. }
  82. if (tag == 'text' && !inText) {
  83. let attrs = sax.getAttrsSync(tail);
  84. const line = {
  85. text: '',
  86. top: parseInt((attrs.top && attrs.top.value ? attrs.top.value : null), 10),
  87. left: parseInt((attrs.left && attrs.left.value ? attrs.left.value : null), 10),
  88. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10),
  89. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10),
  90. };
  91. if (line.width != 0 || line.height != 0) {
  92. inText = true;
  93. if (isNaN(line.top) || isNaN(prevTop) || (Math.abs(prevTop - line.top) > 3)) {
  94. putImage(line.top);
  95. i++;
  96. lines[i] = line;
  97. }
  98. prevTop = line.top;
  99. }
  100. }
  101. if (tag == 'image') {
  102. const attrs = sax.getAttrsSync(tail);
  103. const src = (attrs.src && attrs.src.value ? attrs.src.value : '');
  104. if (src) {
  105. const image = {
  106. isImage: true,
  107. src,
  108. data: '',
  109. type: '',
  110. top: parseInt((attrs.top && attrs.top.value ? attrs.top.value : null), 10) || 0,
  111. };
  112. loading.push(loadImage(image));
  113. images.push(image);
  114. images.sort((a, b) => a.top - b.top)
  115. }
  116. }
  117. if (tag == 'page') {
  118. putImage(100000);
  119. }
  120. }
  121. };
  122. const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  123. if (inText) {
  124. switch (tag) {
  125. case 'i':
  126. italic = false;
  127. break;
  128. case 'b':
  129. bold = false;
  130. break;
  131. }
  132. }
  133. if (tag == 'text')
  134. inText = false;
  135. };
  136. let buf = this.decode(data).toString();
  137. sax.parseSync(buf, {
  138. onStartNode, onEndNode, onTextNode
  139. });
  140. putImage(100000);
  141. await Promise.all(loading);
  142. //найдем параграфы и отступы
  143. const indents = [];
  144. for (const line of lines) {
  145. if (line.isImage)
  146. continue;
  147. if (!isNaN(line.left)) {
  148. indents[line.left] = 1;
  149. }
  150. }
  151. let j = 0;
  152. for (let i = 0; i < indents.length; i++) {
  153. if (indents[i]) {
  154. j++;
  155. indents[i] = j;
  156. }
  157. }
  158. indents[0] = 0;
  159. //формируем текст
  160. let text = `<title>${title}</title>`;
  161. let concat = '';
  162. let sp = '';
  163. for (const line of lines) {
  164. if (line.isImage) {
  165. text += `<fb2-image type="${line.type}" name="${line.name}">${line.data}</fb2-image>`;
  166. continue;
  167. }
  168. if (concat == '') {
  169. const left = line.left || 0;
  170. sp = ' '.repeat(indents[left]);
  171. }
  172. let t = line.text.trim();
  173. if (t.substr(-1) == '-') {
  174. t = t.substr(0, t.length - 1);
  175. concat += t;
  176. } else {
  177. text += sp + concat + t + "\n";
  178. concat = '';
  179. }
  180. }
  181. if (concat)
  182. text += sp + concat + "\n";
  183. return await super.run(Buffer.from(text), {skipCheck: true, isText: true, cutTitle: true});
  184. }
  185. }
  186. module.exports = ConvertPdf;