ConvertPdf.js 7.1 KB

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