ConvertPdf.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //const _ = require('lodash');
  2. const fs = require('fs-extra');
  3. const path = require('path');
  4. const sax = require('../../sax');
  5. const utils = require('../../utils');
  6. const ConvertHtml = require('./ConvertHtml');
  7. const xmlParser = require('../../xmlParser');
  8. class ConvertPdf extends ConvertHtml {
  9. check(data, opts) {
  10. const {inputFiles} = opts;
  11. return this.config.useExternalBookConverter &&
  12. inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'pdf';
  13. }
  14. async run(notUsed, opts) {
  15. if (!this.check(notUsed, opts))
  16. return false;
  17. await this.checkExternalConverterPresent();
  18. const {inputFiles, callback, abort, uploadFileName} = opts;
  19. const inpFile = inputFiles.sourceFile;
  20. const outBasename = `${inputFiles.filesDir}/${utils.randomHexString(10)}`;
  21. const outFile = `${outBasename}.xml`;
  22. const metaFile = `${outBasename}_metadata.xml`;
  23. const pdfaltoPath = `${this.config.dataDir}/pdfalto/pdfalto`;
  24. if (!await fs.pathExists(pdfaltoPath))
  25. throw new Error('Внешний конвертер pdfalto не найден');
  26. //конвертируем в xml
  27. let perc = 0;
  28. await this.execConverter(pdfaltoPath, [inpFile, outFile], () => {
  29. perc = (perc < 80 ? perc + 10 : 40);
  30. callback(perc);
  31. }, abort);
  32. callback(80);
  33. const data = await fs.readFile(outFile);
  34. callback(90);
  35. await utils.sleep(100);
  36. //парсим xml
  37. let lines = [];
  38. let pagelines = [];
  39. let line = {text: ''};
  40. let fonts = {};
  41. let images = [];
  42. let loading = [];
  43. let title = '';
  44. let author = '';
  45. let prevTop = 0;
  46. let i = -1;
  47. const loadImage = async(image) => {
  48. const src = path.parse(image.src);
  49. let type = 'unknown';
  50. switch (src.ext) {
  51. case '.jpg': type = 'image/jpeg'; break;
  52. case '.png': type = 'image/png'; break;
  53. }
  54. if (type != 'unknown') {
  55. image.data = (await fs.readFile(image.src)).toString('base64');
  56. image.type = type;
  57. image.name = src.base;
  58. }
  59. };
  60. const putImage = (curTop) => {
  61. if (!isNaN(curTop) && images.length) {
  62. while (images.length && images[0].top < curTop) {
  63. i++;
  64. lines[i] = images[0];
  65. images.shift();
  66. }
  67. }
  68. };
  69. const putPageLines = () => {
  70. pagelines.sort((a, b) => (a.top - b.top)*10000 + (a.left - b.left))
  71. //объединяем в одну строку равные по высоте
  72. const pl = [];
  73. let pt = -100;
  74. let j = -1;
  75. pagelines.forEach(line => {
  76. if (Math.abs(pt - line.top) > 3) {
  77. j++;
  78. pl[j] = line;
  79. } else {
  80. pl[j].text += line.text;
  81. }
  82. pt = line.top;
  83. });
  84. //заполняем lines
  85. pl.forEach(line => {
  86. putImage(line.top);
  87. i++;
  88. lines[i] = line;
  89. });
  90. pagelines = [];
  91. };
  92. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  93. if (tag == 'textstyle') {
  94. const attrs = sax.getAttrsSync(tail);
  95. const fontId = (attrs.id && attrs.id.value ? attrs.id.value : '');
  96. const fontStyle = (attrs.fontstyle && attrs.fontstyle.value ? attrs.fontstyle.value : '');
  97. if (fontId && fontStyle) {
  98. const styles = fontStyle.split(' ');
  99. const styleTags = {bold: 'b', italics: 'i', superscript: 'sup', subscript: 'sub'};
  100. const f = fonts[fontId] = {tOpen: '', tClose: ''};
  101. styles.forEach(style => {
  102. const s = styleTags[style];
  103. if (s) {
  104. f.tOpen += `<${s}>`;
  105. f.tClose = `</${s}>${f.tClose}`;
  106. }
  107. });
  108. }
  109. }
  110. if (tag == 'page') {
  111. putPageLines();
  112. putImage(100000);
  113. }
  114. if (tag == 'textline') {
  115. const attrs = sax.getAttrsSync(tail);
  116. line = {
  117. text: '',
  118. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10),
  119. left: parseInt((attrs.hpos && attrs.hpos.value ? attrs.hpos.value : null), 10),
  120. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10),
  121. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10),
  122. };
  123. if (line.width != 0 || line.height != 0) {
  124. if (Math.abs(prevTop - line.top) > 3) {
  125. putImage(line.top);
  126. pagelines.push(line);
  127. }
  128. prevTop = line.top;
  129. }
  130. }
  131. if (tag == 'string') {
  132. const attrs = sax.getAttrsSync(tail);
  133. if (attrs.content && attrs.content.value) {
  134. let tOpen = '';
  135. let tClose = '';
  136. const fontId = (attrs.stylerefs && attrs.stylerefs.value ? attrs.stylerefs.value : '');
  137. if (fontId && fonts[fontId]) {
  138. tOpen = fonts[fontId].tOpen;
  139. tClose = fonts[fontId].tClose;
  140. }
  141. line.text += `${tOpen}${attrs.content.value}${tClose} `;
  142. }
  143. }
  144. if (tag == 'illustration') {
  145. const attrs = sax.getAttrsSync(tail);
  146. if (attrs.type && attrs.type.value == 'image') {
  147. let src = (attrs.fileid && attrs.fileid.value ? attrs.fileid.value : '');
  148. if (src) {
  149. const image = {
  150. isImage: true,
  151. src,
  152. data: '',
  153. type: '',
  154. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10) || 0,
  155. left: parseInt((attrs.hpos && attrs.hpos.value ? attrs.hpos.value : null), 10) || 0,
  156. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10) || 0,
  157. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10) || 0,
  158. };
  159. const exists = images.filter(img => (img.top == image.top && img.left == image.left && img.width == image.width && img.height == image.height));
  160. if (!exists.length) {
  161. loading.push(loadImage(image));
  162. images.push(image);
  163. images.sort((a, b) => (a.top - b.top)*10000 + (a.left - b.left));
  164. }
  165. }
  166. }
  167. }
  168. };
  169. let buf = this.decode(data).toString();
  170. sax.parseSync(buf, {
  171. onStartNode
  172. });
  173. putPageLines();
  174. putImage(100000);
  175. await Promise.all(loading);
  176. await utils.sleep(100);
  177. //найдем параграфы и отступы
  178. const indents = [];
  179. for (const line of lines) {
  180. if (line.isImage)
  181. continue;
  182. if (!isNaN(line.left)) {
  183. indents[line.left] = 1;
  184. }
  185. }
  186. let j = 0;
  187. for (let i = 0; i < indents.length; i++) {
  188. if (indents[i]) {
  189. j++;
  190. indents[i] = j;
  191. }
  192. }
  193. indents[0] = 0;
  194. //title
  195. if (fs.pathExists(metaFile)) {
  196. const metaXmlString = (await fs.readFile(metaFile)).toString();
  197. let metaXmlParsed = xmlParser.parseXml(metaXmlString);
  198. metaXmlParsed = xmlParser.simplifyXmlParsed(metaXmlParsed);
  199. if (metaXmlParsed.metadata) {
  200. title = (metaXmlParsed.metadata.title ? metaXmlParsed.metadata.title._t : null);
  201. author = (metaXmlParsed.metadata.author ? metaXmlParsed.metadata.author._t : null);
  202. }
  203. }
  204. if (!title && uploadFileName)
  205. title = uploadFileName;
  206. //формируем текст
  207. const limitSize = 2*this.config.maxUploadFileSize;
  208. let text = '';
  209. text += `<fb2-title>${title}</fb2-title>`;
  210. text += `<fb2-author>${author}</fb2-author>`;
  211. let concat = '';
  212. let sp = '';
  213. for (const line of lines) {
  214. if (text.length > limitSize) {
  215. throw new Error(`Файл для конвертирования слишком большой|FORLOG| text.length: ${text.length} > ${limitSize}`);
  216. }
  217. if (line.isImage) {
  218. text += `<fb2-image type="${line.type}" name="${line.name}">${line.data}</fb2-image>`;
  219. continue;
  220. }
  221. if (concat == '') {
  222. const left = line.left || 0;
  223. sp = ' '.repeat(indents[left]);
  224. }
  225. let t = line.text.trim();
  226. if (t.substr(-1) == '-') {
  227. t = t.substr(0, t.length - 1);
  228. concat += t;
  229. } else {
  230. text += sp + concat + t + "\n";
  231. concat = '';
  232. }
  233. }
  234. if (concat)
  235. text += sp + concat + "\n";
  236. await utils.sleep(100);
  237. return await super.run(Buffer.from(text), {skipCheck: true, isText: true});
  238. }
  239. }
  240. module.exports = ConvertPdf;