ConvertPdf.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. //парсим xml
  36. let lines = [];
  37. let pagelines = [];
  38. let line = {text: ''};
  39. let images = [];
  40. let loading = [];
  41. let title = '';
  42. let author = '';
  43. let prevTop = 0;
  44. let i = -1;
  45. const loadImage = async(image) => {
  46. const src = path.parse(image.src);
  47. let type = 'unknown';
  48. switch (src.ext) {
  49. case '.jpg': type = 'image/jpeg'; break;
  50. case '.png': type = 'image/png'; break;
  51. }
  52. if (type != 'unknown') {
  53. image.data = (await fs.readFile(image.src)).toString('base64');
  54. image.type = type;
  55. image.name = src.base;
  56. }
  57. };
  58. const putImage = (curTop) => {
  59. if (!isNaN(curTop) && images.length) {
  60. while (images.length && images[0].top < curTop) {
  61. i++;
  62. lines[i] = images[0];
  63. images.shift();
  64. }
  65. }
  66. };
  67. const putPageLines = () => {
  68. pagelines.sort((a, b) => (a.top - b.top)*10000 + (a.left - b.left))
  69. //объединяем в одну строку равные по высоте
  70. const pl = [];
  71. let pt = -100;
  72. let j = -1;
  73. pagelines.forEach(line => {
  74. if (Math.abs(pt - line.top) > 3) {
  75. j++;
  76. pl[j] = line;
  77. } else {
  78. pl[j].text += line.text;
  79. }
  80. pt = line.top;
  81. });
  82. //заполняем lines
  83. pl.forEach(line => {
  84. putImage(line.top);
  85. i++;
  86. lines[i] = line;
  87. });
  88. pagelines = [];
  89. };
  90. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  91. if (tag == 'page') {
  92. putPageLines();
  93. putImage(100000);
  94. }
  95. if (tag == 'textline') {
  96. const attrs = sax.getAttrsSync(tail);
  97. line = {
  98. text: '',
  99. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10),
  100. left: parseInt((attrs.hpos && attrs.hpos.value ? attrs.hpos.value : null), 10),
  101. width: parseInt((attrs.width && attrs.width.value ? attrs.width.value : null), 10),
  102. height: parseInt((attrs.height && attrs.height.value ? attrs.height.value : null), 10),
  103. };
  104. if (line.width != 0 || line.height != 0) {
  105. if (Math.abs(prevTop - line.top) > 3) {
  106. pagelines.push(line);
  107. }
  108. prevTop = line.top;
  109. }
  110. }
  111. if (tag == 'string') {
  112. const attrs = sax.getAttrsSync(tail);
  113. if (attrs.content && attrs.content.value) {
  114. line.text += `${attrs.content.value} `;
  115. }
  116. }
  117. if (tag == 'illustration') {
  118. const attrs = sax.getAttrsSync(tail);
  119. if (attrs.type && attrs.type.value == 'image') {
  120. let src = (attrs.fileid && attrs.fileid.value ? attrs.fileid.value : '');
  121. if (src) {
  122. const image = {
  123. isImage: true,
  124. src,
  125. data: '',
  126. type: '',
  127. top: parseInt((attrs.vpos && attrs.vpos.value ? attrs.vpos.value : null), 10) || 0,
  128. };
  129. loading.push(loadImage(image));
  130. images.push(image);
  131. images.sort((a, b) => a.top - b.top)
  132. }
  133. }
  134. }
  135. };
  136. let buf = this.decode(data).toString();
  137. sax.parseSync(buf, {
  138. onStartNode
  139. });
  140. putPageLines();
  141. putImage(100000);
  142. await Promise.all(loading);
  143. //найдем параграфы и отступы
  144. const indents = [];
  145. for (const line of lines) {
  146. if (line.isImage)
  147. continue;
  148. if (!isNaN(line.left)) {
  149. indents[line.left] = 1;
  150. }
  151. }
  152. let j = 0;
  153. for (let i = 0; i < indents.length; i++) {
  154. if (indents[i]) {
  155. j++;
  156. indents[i] = j;
  157. }
  158. }
  159. indents[0] = 0;
  160. //title
  161. if (fs.pathExists(metaFile)) {
  162. const metaXmlString = (await fs.readFile(metaFile)).toString();
  163. let metaXmlParsed = xmlParser.parseXml(metaXmlString);
  164. metaXmlParsed = xmlParser.simplifyXmlParsed(metaXmlParsed);
  165. if (metaXmlParsed.metadata) {
  166. title = (metaXmlParsed.metadata.title ? metaXmlParsed.metadata.title._t : null);
  167. author = (metaXmlParsed.metadata.author ? metaXmlParsed.metadata.author._t : null);
  168. }
  169. }
  170. if (!title && uploadFileName)
  171. title = uploadFileName;
  172. //формируем текст
  173. const limitSize = 2*this.config.maxUploadFileSize;
  174. let text = '';
  175. text += `<fb2-title>${title}</fb2-title>`;
  176. text += `<fb2-author>${author}</fb2-author>`;
  177. let concat = '';
  178. let sp = '';
  179. for (const line of lines) {
  180. if (text.length > limitSize) {
  181. throw new Error(`Файл для конвертирования слишком большой|FORLOG| text.length: ${text.length} > ${limitSize}`);
  182. }
  183. if (line.isImage) {
  184. text += `<fb2-image type="${line.type}" name="${line.name}">${line.data}</fb2-image>`;
  185. continue;
  186. }
  187. if (concat == '') {
  188. const left = line.left || 0;
  189. sp = ' '.repeat(indents[left]);
  190. }
  191. let t = line.text.trim();
  192. if (t.substr(-1) == '-') {
  193. t = t.substr(0, t.length - 1);
  194. concat += t;
  195. } else {
  196. text += sp + concat + t + "\n";
  197. concat = '';
  198. }
  199. }
  200. if (concat)
  201. text += sp + concat + "\n";
  202. return await super.run(Buffer.from(text), {skipCheck: true, isText: true});
  203. }
  204. }
  205. module.exports = ConvertPdf;