annotation.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /* eslint-disable no-param-reassign */
  2. import { v4 as uuidv4 } from 'uuid';
  3. import dayjs from 'dayjs';
  4. import queryString from 'query-string';
  5. import { ANNOTATION_TYPE, FORM_TYPE } from '../constants';
  6. import { getPdfPage, renderTextLayer } from './pdf';
  7. import { getPosition, parsePositionForBackend } from './position';
  8. import { normalizeRound, floatToHex } from './utility';
  9. import { xmlParser, getElementsByTagName } from './dom';
  10. type GetFontAttributeFunc = (
  11. type: string,
  12. element: Record<string, any>
  13. ) => Record<string, any>;
  14. const getContent = (type: string, element: Record<string, any>): string => {
  15. if (type !== 'Text' && type !== 'FreeText') return '';
  16. let content = '';
  17. let nodes: any = element.childNodes;
  18. nodes = Array.prototype.slice.call(nodes);
  19. nodes.forEach((ele: HTMLElement) => {
  20. if (ele.tagName === 'contents') {
  21. content = ele.innerHTML || ele.textContent || '';
  22. }
  23. });
  24. return content;
  25. };
  26. const getFontAttribute: GetFontAttributeFunc = (type, element) => {
  27. if (type !== 'FreeText') return {};
  28. const appearanceString =
  29. element.childNodes[1].innerHTML || element.childNodes[1].textContent;
  30. const arr = appearanceString.split(' ');
  31. return {
  32. fontsize: parseInt(arr[5], 10),
  33. fontname: arr[4].substr(1),
  34. textcolor: floatToHex(
  35. parseFloat(arr[0]),
  36. parseFloat(arr[1]),
  37. parseFloat(arr[2])
  38. ),
  39. };
  40. };
  41. export const parseAnnotationFromXml = (xmlString: string): AnnotationType[] => {
  42. if (!xmlString) return [];
  43. const xmlDoc = xmlParser(xmlString);
  44. const elements = xmlDoc.firstElementChild || xmlDoc.firstChild;
  45. const element = getElementsByTagName(elements as ChildNode, 'annots') || [];
  46. const annotations: Element[] = Array.prototype.slice.call(element);
  47. const filterAnnots = annotations.reduce((acc: any[], cur: any) => {
  48. const type = ANNOTATION_TYPE[cur.tagName];
  49. if (type) {
  50. const page = parseInt(cur.attributes.page.value, 10);
  51. acc.push({
  52. id: uuidv4(),
  53. obj_type: type,
  54. obj_attr: {
  55. title: cur.attributes.title ? cur.attributes.title.value : undefined,
  56. date: cur.attributes.date ? cur.attributes.date.value : undefined,
  57. page,
  58. position: getPosition(type, cur),
  59. bdcolor: cur.attributes.color
  60. ? cur.attributes.color.value
  61. : undefined,
  62. bdwidth: cur.attributes.width
  63. ? parseInt(cur.attributes.width.value, 10)
  64. : 0,
  65. transparency: cur.attributes.opacity
  66. ? cur.attributes.opacity.value
  67. : 1,
  68. content: getContent(type, cur) || undefined,
  69. fcolor: cur.attributes['interior-color']
  70. ? cur.attributes['interior-color'].value
  71. : undefined,
  72. ftransparency: cur.attributes['interior-opacity']
  73. ? cur.attributes['interior-opacity'].value
  74. : undefined,
  75. is_arrow: cur.attributes.tail,
  76. ...getFontAttribute(type, cur),
  77. },
  78. });
  79. }
  80. return acc;
  81. }, []);
  82. return filterAnnots;
  83. };
  84. export const parseFormElementFromXml = (
  85. xmlString: string
  86. ): AnnotationType[] => {
  87. if (!xmlString) return [];
  88. const xmlDoc = xmlParser(xmlString);
  89. const elements = xmlDoc.firstElementChild || xmlDoc.firstChild;
  90. const element = getElementsByTagName(elements as ChildNode, 'widgets') || [];
  91. const annotations: Element[] = Array.prototype.slice.call(element);
  92. const filterForm = annotations.reduce((acc: any[], cur: any) => {
  93. const type = FORM_TYPE[cur.tagName];
  94. if (type) {
  95. const page = parseInt(cur.attributes.page.value, 10);
  96. acc.push({
  97. id: uuidv4(),
  98. obj_type: type,
  99. obj_attr: {
  100. date: cur.attributes.date ? cur.attributes.date.value : undefined,
  101. page,
  102. position: getPosition(type, cur),
  103. bdcolor: cur.attributes.color
  104. ? cur.attributes.color.value
  105. : undefined,
  106. style: cur.attributes.style ? cur.attributes.style.value : undefined,
  107. bdwidth: cur.attributes.width
  108. ? parseInt(cur.attributes.width.value, 10)
  109. : 0,
  110. transparency: cur.attributes.opacity
  111. ? cur.attributes.opacity.value
  112. : 1,
  113. },
  114. });
  115. }
  116. return acc;
  117. }, []);
  118. return filterForm;
  119. };
  120. // eslint-disable-next-line consistent-return
  121. const getEleText = (
  122. coord: any,
  123. elements: any,
  124. viewport: any,
  125. scale: any
  126. ): string => {
  127. const top = normalizeRound(viewport.height - coord.top * scale);
  128. const left = normalizeRound(coord.left * scale);
  129. const bottom = normalizeRound(viewport.height - coord.bottom * scale);
  130. const right = normalizeRound(coord.right * scale);
  131. for (let i = 0, len = elements.length; i <= len; i += 1) {
  132. const element = elements[i];
  133. if (element) {
  134. const eleTop = normalizeRound(element.offsetTop);
  135. const eleLeft = normalizeRound(element.offsetLeft);
  136. const eleRight = normalizeRound(element.offsetLeft + element.offsetWidth);
  137. if (eleTop >= top && eleTop <= bottom) {
  138. const textLength = element.innerText.length;
  139. const width = element.offsetWidth;
  140. if (eleLeft < left && eleRight > right) {
  141. const distanceL = left - eleLeft;
  142. const rateL = distanceL / width;
  143. const start = Math.floor(textLength * rateL);
  144. const distanceR = eleRight - right;
  145. const rateR = distanceR / width;
  146. const end = Math.floor(textLength - textLength * rateR);
  147. return ` ${element.innerText.slice(start, end)}`;
  148. }
  149. if (eleLeft < left && eleRight > left) {
  150. const distance = left - eleLeft;
  151. const rate = distance / width;
  152. const start = Math.floor(textLength * rate);
  153. return ` ${element.innerText.slice(start)}`;
  154. }
  155. if (eleRight > right && eleLeft < right) {
  156. const distance = eleRight - right;
  157. const rate = distance / width;
  158. const end = Math.floor(textLength - textLength * rate);
  159. return ` ${element.innerText.slice(0, end)}`;
  160. }
  161. if (eleLeft >= left && eleRight <= right) {
  162. return ` ${element.innerText}`;
  163. }
  164. }
  165. }
  166. }
  167. return '';
  168. };
  169. export const getAnnotationText = async ({
  170. viewport,
  171. scale,
  172. page,
  173. coords,
  174. pdf,
  175. }: {
  176. viewport: ViewportType;
  177. scale: number;
  178. page: number;
  179. coords: PositionType[];
  180. pdf: any;
  181. }): Promise<any> => {
  182. const pageContainer = document.getElementById(`page_${page}`) as HTMLElement;
  183. const textLayer = pageContainer.querySelector(
  184. '[data-id="text-layer"]'
  185. ) as HTMLElement;
  186. const pdfPage = await getPdfPage(pdf, page);
  187. if (!textLayer.childNodes.length) {
  188. await renderTextLayer({
  189. textLayer,
  190. pdfPage,
  191. viewport,
  192. });
  193. }
  194. // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
  195. // @ts-ignore
  196. const textElements = [...textLayer.childNodes];
  197. let text = '';
  198. for (let i = 0, len = coords.length; i < len; i += 1) {
  199. const coord = coords[i];
  200. text += getEleText(coord, textElements, viewport, scale);
  201. }
  202. return text;
  203. };
  204. export const parseAnnotationObject = (
  205. {
  206. id,
  207. obj_type,
  208. obj_attr: {
  209. page,
  210. bdcolor,
  211. transparency,
  212. fcolor,
  213. ftransparency,
  214. position = '',
  215. content,
  216. style,
  217. bdwidth,
  218. fontname,
  219. fontsize,
  220. textcolor,
  221. is_arrow,
  222. src,
  223. },
  224. }: AnnotationType,
  225. pageHeight: number,
  226. scale: number
  227. ): AnnotationType => ({
  228. id: id || uuidv4(),
  229. obj_type,
  230. obj_attr: {
  231. page: page - 1,
  232. bdcolor,
  233. position: parsePositionForBackend(obj_type, position, pageHeight, scale),
  234. transparency: transparency ? transparency * 0.01 : 0,
  235. content: content || undefined,
  236. style,
  237. fcolor,
  238. ftransparency: ftransparency ? ftransparency * 0.01 : 0,
  239. bdwidth,
  240. fontname,
  241. fontsize,
  242. textcolor,
  243. is_arrow,
  244. src,
  245. },
  246. });
  247. export const appendUserIdAndDate = (
  248. annotateObj: AnnotationType
  249. ): AnnotationType => {
  250. const parsed = queryString.parse(window.location.search);
  251. if (parsed.watermark) {
  252. annotateObj.obj_attr.title = parsed.watermark;
  253. }
  254. const datetime = dayjs().format('YYYY-MM-DD_HH:mm:ss');
  255. annotateObj.obj_attr.date = datetime;
  256. return annotateObj;
  257. };