ConvertPdf.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. //добавим закрывающий тег стиля
  77. line.text += line.tClose;
  78. if (Math.abs(pt - line.top) > 3) {
  79. j++;
  80. pl[j] = line;
  81. } else {
  82. pl[j].text += line.text;
  83. }
  84. pt = line.top;
  85. });
  86. //заполняем lines
  87. pl.forEach(line => {
  88. putImage(line.top);
  89. i++;
  90. lines[i] = line;
  91. });
  92. pagelines = [];
  93. };
  94. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  95. if (tag == 'textstyle') {
  96. const attrs = sax.getAttrsSync(tail);
  97. const fontId = (attrs.id && attrs.id.value ? attrs.id.value : '');
  98. const fontStyle = (attrs.fontstyle && attrs.fontstyle.value ? attrs.fontstyle.value : '');
  99. if (fontId && fontStyle) {
  100. const styles = fontStyle.split(' ');
  101. const styleTags = {bold: 'b', italics: 'i', superscript: 'sup', subscript: 'sub'};
  102. const f = fonts[fontId] = {tOpen: '', tClose: ''};
  103. styles.forEach(style => {
  104. const s = styleTags[style];
  105. if (s) {
  106. f.tOpen += `<${s}>`;
  107. f.tClose = `</${s}>${f.tClose}`;
  108. }
  109. });
  110. }
  111. }
  112. if (tag == 'page') {
  113. putPageLines();
  114. putImage(100000);
  115. }
  116. if (tag == 'textline') {
  117. const attrs = sax.getAttrsSync(tail);
  118. line = {
  119. text: '',
  120. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10),
  121. left: parseInt((attrs.hpos && attrs.hpos.value ? attrs.hpos.value : null), 10),
  122. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10),
  123. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10),
  124. tOpen: '',
  125. tClose: '',
  126. };
  127. if (line.width != 0 || line.height != 0) {
  128. if (Math.abs(prevTop - line.top) > 3) {
  129. putImage(line.top);
  130. pagelines.push(line);
  131. }
  132. prevTop = line.top;
  133. }
  134. }
  135. if (tag == 'string') {
  136. const attrs = sax.getAttrsSync(tail);
  137. if (attrs.content && attrs.content.value) {
  138. let tOpen = '';
  139. let tClose = '';
  140. const fontId = (attrs.stylerefs && attrs.stylerefs.value ? attrs.stylerefs.value : '');
  141. if (fontId && fonts[fontId]) {
  142. tOpen = fonts[fontId].tOpen;
  143. tClose = fonts[fontId].tClose;
  144. }
  145. if (line.tOpen != tOpen) {
  146. line.text += line.tClose + tOpen;
  147. line.tOpen = tOpen;
  148. line.tClose = tClose;
  149. }
  150. line.text += `${line.text.length ? ' ' : ''}${attrs.content.value}`;
  151. }
  152. }
  153. if (tag == 'illustration') {
  154. const attrs = sax.getAttrsSync(tail);
  155. if (attrs.type && attrs.type.value == 'image') {
  156. let src = (attrs.fileid && attrs.fileid.value ? attrs.fileid.value : '');
  157. if (src) {
  158. const image = {
  159. isImage: true,
  160. src,
  161. data: '',
  162. type: '',
  163. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10) || 0,
  164. left: parseInt((attrs.hpos && attrs.hpos.value ? attrs.hpos.value : null), 10) || 0,
  165. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10) || 0,
  166. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10) || 0,
  167. };
  168. const exists = images.filter(img => (img.top == image.top && img.left == image.left && img.width == image.width && img.height == image.height));
  169. if (!exists.length) {
  170. loading.push(loadImage(image));
  171. images.push(image);
  172. images.sort((a, b) => (a.top - b.top)*10000 + (a.left - b.left));
  173. }
  174. }
  175. }
  176. }
  177. };
  178. let buf = this.decode(data).toString();
  179. sax.parseSync(buf, {
  180. onStartNode
  181. });
  182. putPageLines();
  183. putImage(100000);
  184. await Promise.all(loading);
  185. await utils.sleep(100);
  186. //найдем параграфы и отступы
  187. const indents = [];
  188. for (const line of lines) {
  189. if (line.isImage)
  190. continue;
  191. if (!isNaN(line.left)) {
  192. indents[line.left] = 1;
  193. }
  194. }
  195. let j = 0;
  196. for (let i = 0; i < indents.length; i++) {
  197. if (indents[i]) {
  198. j++;
  199. indents[i] = j;
  200. }
  201. }
  202. indents[0] = 0;
  203. //title
  204. if (fs.pathExists(metaFile)) {
  205. const metaXmlString = (await fs.readFile(metaFile)).toString();
  206. let metaXmlParsed = xmlParser.parseXml(metaXmlString);
  207. metaXmlParsed = xmlParser.simplifyXmlParsed(metaXmlParsed);
  208. if (metaXmlParsed.metadata) {
  209. title = (metaXmlParsed.metadata.title ? metaXmlParsed.metadata.title._t : null);
  210. author = (metaXmlParsed.metadata.author ? metaXmlParsed.metadata.author._t : null);
  211. }
  212. }
  213. if (!title && uploadFileName)
  214. title = uploadFileName;
  215. //формируем текст
  216. const limitSize = 2*this.config.maxUploadFileSize;
  217. let text = '';
  218. text += `<fb2-title>${title}</fb2-title>`;
  219. text += `<fb2-author>${author}</fb2-author>`;
  220. let concat = '';
  221. let sp = '';
  222. for (const line of lines) {
  223. if (text.length > limitSize) {
  224. throw new Error(`Файл для конвертирования слишком большой|FORLOG| text.length: ${text.length} > ${limitSize}`);
  225. }
  226. if (line.isImage) {
  227. text += `<fb2-image type="${line.type}" name="${line.name}">${line.data}</fb2-image>`;
  228. continue;
  229. }
  230. if (concat == '') {
  231. const left = line.left || 0;
  232. sp = ' '.repeat(indents[left]);
  233. }
  234. let t = line.text.trim();
  235. if (t.substr(-1) == '-') {
  236. t = t.substr(0, t.length - 1);
  237. concat += t;
  238. } else {
  239. text += sp + concat + t + "\n";
  240. concat = '';
  241. }
  242. }
  243. if (concat)
  244. text += sp + concat + "\n";
  245. await utils.sleep(100);
  246. return await super.run(Buffer.from(text), {skipCheck: true, isText: true});
  247. }
  248. }
  249. module.exports = ConvertPdf;