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