ConvertPdf.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 page = {};
  41. let fonts = {};
  42. let sectionTitleFound = false;
  43. let images = [];
  44. let loading = [];
  45. let title = '';
  46. let author = '';
  47. let i = -1;
  48. const loadImage = async(image) => {
  49. const src = path.parse(image.src);
  50. let type = 'unknown';
  51. switch (src.ext) {
  52. case '.jpg': type = 'image/jpeg'; break;
  53. case '.png': type = 'image/png'; break;
  54. }
  55. if (type != 'unknown') {
  56. image.data = (await fs.readFile(image.src)).toString('base64');
  57. image.type = type;
  58. image.name = src.base;
  59. }
  60. };
  61. const putImage = (curTop) => {
  62. if (!isNaN(curTop) && images.length) {
  63. while (images.length && images[0].top < curTop) {
  64. i++;
  65. lines[i] = images[0];
  66. images.shift();
  67. }
  68. }
  69. };
  70. const putPageLines = () => {
  71. pagelines.sort((a, b) => (a.top - b.top)*10000 + (a.left - b.left))
  72. //объединяем в одну строку равные по высоте
  73. const pl = [];
  74. let pt = 0;
  75. let j = -1;
  76. pagelines.forEach(line => {
  77. //добавим закрывающий тег стиля
  78. line.text += line.tClose;
  79. //проверим, возможно это заголовок
  80. if (line.fonts.length == 1 && line.pageWidth) {
  81. const f = (line.fonts.length ? fonts[line.fonts[0]] : null);
  82. const centerLeft = (line.pageWidth - line.width)/2;
  83. if (f && f.isBold && Math.abs(centerLeft - line.left) < 3) {
  84. if (!sectionTitleFound) {
  85. line.isSectionTitle = true;
  86. sectionTitleFound = true;
  87. } else {
  88. line.isSubtitle = true;
  89. }
  90. }
  91. }
  92. //объединяем
  93. if (pt == 0 || Math.abs(pt - line.top) > 3) {
  94. j++;
  95. pl[j] = line;
  96. } else {
  97. pl[j].text += ` ${line.text}`;
  98. }
  99. pt = line.top;
  100. });
  101. //заполняем lines
  102. const lastIndex = i;
  103. pl.forEach(line => {
  104. putImage(line.top);
  105. //добавим пустую строку, если надо
  106. const prevLine = (i > lastIndex ? lines[i] : {fonts: [], top: 0});
  107. if (prevLine && !prevLine.isImage) {
  108. const f = (prevLine.fonts.length ? fonts[prevLine.fonts[0]] : (line.fonts.length ? fonts[line.fonts[0]] : null));
  109. if (f && f.fontSize && !line.isImage && line.top - prevLine.top > f.fontSize*1.8) {
  110. i++;
  111. lines[i] = {text: '<br>'};
  112. }
  113. }
  114. i++;
  115. lines[i] = line;
  116. });
  117. pagelines = [];
  118. putImage(100000);
  119. };
  120. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  121. if (tag == 'textstyle') {
  122. const attrs = sax.getAttrsSync(tail);
  123. const fontId = (attrs.id && attrs.id.value ? attrs.id.value : '');
  124. const fontStyle = (attrs.fontstyle && attrs.fontstyle.value ? attrs.fontstyle.value : '');
  125. const fontSize = (attrs.fontsize && attrs.fontsize.value ? attrs.fontsize.value : '');
  126. if (fontId) {
  127. const styleTags = {bold: 'b', italics: 'i', superscript: 'sup', subscript: 'sub'};
  128. const f = fonts[fontId] = {tOpen: '', tClose: '', isBold: false, fontSize};
  129. if (fontStyle) {
  130. const styles = fontStyle.split(' ');
  131. styles.forEach(style => {
  132. const s = styleTags[style];
  133. if (s) {
  134. f.tOpen += `<${s}>`;
  135. f.tClose = `</${s}>${f.tClose}`;
  136. if (s == 'b')
  137. f.isBold = true;
  138. }
  139. });
  140. }
  141. }
  142. }
  143. if (tag == 'page') {
  144. const attrs = sax.getAttrsSync(tail);
  145. page = {
  146. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10),
  147. };
  148. putPageLines();
  149. }
  150. if (tag == 'textline') {
  151. const attrs = sax.getAttrsSync(tail);
  152. line = {
  153. text: '',
  154. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10),
  155. left: parseInt((attrs.hpos && attrs.hpos.value ? attrs.hpos.value : null), 10),
  156. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10),
  157. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10),
  158. tOpen: '',
  159. tClose: '',
  160. isSectionTitle: false,
  161. isSubtitle: false,
  162. pageWidth: page.width,
  163. fonts: [],
  164. };
  165. if (line.width != 0 || line.height != 0) {
  166. pagelines.push(line);
  167. }
  168. }
  169. if (tag == 'string') {
  170. const attrs = sax.getAttrsSync(tail);
  171. if (attrs.content && attrs.content.value) {
  172. let tOpen = '';
  173. let tClose = '';
  174. const fontId = (attrs.stylerefs && attrs.stylerefs.value ? attrs.stylerefs.value : '');
  175. if (fontId && fonts[fontId]) {
  176. tOpen = fonts[fontId].tOpen;
  177. tClose = fonts[fontId].tClose;
  178. if (!line.fonts.length || line.fonts[0] != fontId)
  179. line.fonts.push(fontId);
  180. }
  181. if (line.tOpen != tOpen) {
  182. line.text += line.tClose + tOpen;
  183. line.tOpen = tOpen;
  184. line.tClose = tClose;
  185. }
  186. line.text += `${line.text.length ? ' ' : ''}${attrs.content.value}`;
  187. }
  188. }
  189. if (tag == 'illustration') {
  190. const attrs = sax.getAttrsSync(tail);
  191. if (attrs.type && attrs.type.value == 'image') {
  192. let src = (attrs.fileid && attrs.fileid.value ? attrs.fileid.value : '');
  193. if (src) {
  194. const image = {
  195. isImage: true,
  196. src,
  197. data: '',
  198. type: '',
  199. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10) || 0,
  200. left: parseInt((attrs.hpos && attrs.hpos.value ? attrs.hpos.value : null), 10) || 0,
  201. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10) || 0,
  202. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10) || 0,
  203. };
  204. const exists = images.filter(img => (img.top == image.top && img.left == image.left && img.width == image.width && img.height == image.height));
  205. if (!exists.length) {
  206. loading.push(loadImage(image));
  207. images.push(image);
  208. images.sort((a, b) => (a.top - b.top)*10000 + (a.left - b.left));
  209. }
  210. }
  211. }
  212. }
  213. };
  214. let buf = this.decode(data).toString();
  215. sax.parseSync(buf, {
  216. onStartNode
  217. });
  218. putPageLines();
  219. await Promise.all(loading);
  220. await utils.sleep(100);
  221. //найдем параграфы и отступы
  222. const indents = [];
  223. for (const line of lines) {
  224. if (line.isImage)
  225. continue;
  226. if (!isNaN(line.left)) {
  227. indents[line.left] = 1;
  228. }
  229. }
  230. let j = 0;
  231. for (let i = 0; i < indents.length; i++) {
  232. if (indents[i]) {
  233. j++;
  234. indents[i] = j;
  235. }
  236. }
  237. indents[0] = 0;
  238. //title
  239. if (fs.pathExists(metaFile)) {
  240. const metaXmlString = (await fs.readFile(metaFile)).toString();
  241. let metaXmlParsed = xmlParser.parseXml(metaXmlString);
  242. metaXmlParsed = xmlParser.simplifyXmlParsed(metaXmlParsed);
  243. if (metaXmlParsed.metadata) {
  244. title = (metaXmlParsed.metadata.title ? metaXmlParsed.metadata.title._t : '');
  245. author = (metaXmlParsed.metadata.author ? metaXmlParsed.metadata.author._t : '');
  246. }
  247. }
  248. if (!title && uploadFileName)
  249. title = uploadFileName;
  250. //console.log(JSON.stringify(lines, null, 2));
  251. //формируем текст
  252. const limitSize = 2*this.config.maxUploadFileSize;
  253. let text = '';
  254. if (title)
  255. text += `<fb2-title>${title}</fb2-title>`;
  256. if (author)
  257. text += `<fb2-author>${author}</fb2-author>`;
  258. let concat = '';
  259. let sp = '';
  260. for (const line of lines) {
  261. if (text.length > limitSize) {
  262. throw new Error(`Файл для конвертирования слишком большой|FORLOG| text.length: ${text.length} > ${limitSize}`);
  263. }
  264. if (line.isImage) {
  265. text += `<fb2-image type="${line.type}" name="${line.name}">${line.data}</fb2-image>`;
  266. continue;
  267. }
  268. if (line.isSectionTitle) {
  269. text += `<fb2-section-title>${line.text.trim()}</fb2-section-title>`;
  270. continue;
  271. }
  272. if (line.isSubtitle) {
  273. text += `<br><fb2-subtitle>${line.text.trim()}</fb2-subtitle>`;
  274. continue;
  275. }
  276. if (concat == '') {
  277. const left = line.left || 0;
  278. sp = ' '.repeat(indents[left]);
  279. }
  280. let t = line.text.trim();
  281. if (t.substr(-1) == '-') {
  282. t = t.substr(0, t.length - 1);
  283. concat += t;
  284. } else {
  285. text += sp + concat + t + "\n";
  286. concat = '';
  287. }
  288. }
  289. if (concat)
  290. text += sp + concat + "\n";
  291. //console.log(text);
  292. await utils.sleep(100);
  293. return await super.run(Buffer.from(text), {skipCheck: true, isText: true});
  294. }
  295. }
  296. module.exports = ConvertPdf;