ConvertPdf.js 12 KB

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