watermark.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { floatToHex } from './utility';
  2. import { xmlParser, getElementsByTagName } from './dom';
  3. type WatermarkAnnotType = {
  4. obj_type: string;
  5. obj_attr: WatermarkType;
  6. };
  7. export const parseWatermarkFromXml = (
  8. xmlString: string,
  9. ): WatermarkAnnotType => {
  10. if (!xmlString) return { obj_type: 'watermark', obj_attr: {} };
  11. const xmlDoc = xmlParser(xmlString);
  12. const elements = xmlDoc.firstElementChild || xmlDoc.firstChild;
  13. const data: WatermarkType = {};
  14. const element = getElementsByTagName(elements as ChildNode, 'watermarks');
  15. if (element && element[1]) {
  16. const array: Element[] = Array.prototype.slice.call(element[1].childNodes);
  17. array.forEach((ele, index) => {
  18. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19. const attr: any = ele.attributes;
  20. switch (ele.tagName) {
  21. case 'Font':
  22. data.type = 'text';
  23. data.text = (array[index + 1].textContent as string).trim();
  24. break;
  25. case 'Opacity': {
  26. data.opacity = attr.value.value;
  27. break;
  28. }
  29. case 'Rotation': {
  30. data.rotation = parseFloat(attr.value.value);
  31. break;
  32. }
  33. case 'Scale': {
  34. data.scale = parseFloat(attr.value.value);
  35. break;
  36. }
  37. case 'Color': {
  38. const r = attr.r.value;
  39. const g = attr.g.value;
  40. const b = attr.b.value;
  41. data.textcolor = floatToHex(r, g, b);
  42. break;
  43. }
  44. case 'PageRange': {
  45. data.pages = (array[index + 1].textContent as string).trim();
  46. break;
  47. }
  48. default:
  49. break;
  50. }
  51. });
  52. }
  53. return {
  54. obj_type: 'watermark',
  55. obj_attr: {
  56. vertalign: 'center',
  57. horizalign: 'center',
  58. xoffset: 0,
  59. yoffset: 0,
  60. isfront: 'yes',
  61. ...data,
  62. },
  63. };
  64. };
  65. export default parseWatermarkFromXml;