watermark.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. const attr: any = ele.attributes;
  19. switch (ele.tagName) {
  20. case 'Font':
  21. data.type = 'text';
  22. data.text = (array[index + 1].textContent as string).trim();
  23. break;
  24. case 'Opacity': {
  25. data.opacity = attr.value.value;
  26. break;
  27. }
  28. case 'Rotation': {
  29. data.rotation = parseFloat(attr.value.value);
  30. break;
  31. }
  32. case 'Scale': {
  33. data.scale = parseFloat(attr.value.value);
  34. break;
  35. }
  36. case 'Color': {
  37. const r = attr.r.value;
  38. const g = attr.g.value;
  39. const b = attr.b.value;
  40. data.textcolor = floatToHex(r, g, b);
  41. break;
  42. }
  43. case 'PageRange': {
  44. data.pages = (array[index + 1].textContent as string).trim();
  45. break;
  46. }
  47. default:
  48. break;
  49. }
  50. });
  51. }
  52. return {
  53. obj_type: 'watermark',
  54. obj_attr: {
  55. vertalign: 'center',
  56. horizalign: 'center',
  57. xoffset: 0,
  58. yoffset: 0,
  59. isfront: 'yes',
  60. ...data,
  61. },
  62. };
  63. };
  64. export default parseWatermarkFromXml;