libs/pdfname.js

  1. /**
  2. * Convert string to `PDF Name Object`.
  3. * Detail: PDF Reference 1.3 - Chapter 3.2.4 Name Object
  4. * @param str
  5. */
  6. function toPDFName(str) {
  7. // eslint-disable-next-line no-control-regex
  8. if (/[^\u0000-\u00ff]/.test(str)) {
  9. // non ascii string
  10. throw new Error(
  11. "Invalid PDF Name Object: " + str + ", Only accept ASCII characters."
  12. );
  13. }
  14. var result = "",
  15. strLength = str.length;
  16. for (var i = 0; i < strLength; i++) {
  17. var charCode = str.charCodeAt(i);
  18. if (
  19. charCode < 0x21 ||
  20. charCode === 0x23 /* # */ ||
  21. charCode === 0x25 /* % */ ||
  22. charCode === 0x28 /* ( */ ||
  23. charCode === 0x29 /* ) */ ||
  24. charCode === 0x2f /* / */ ||
  25. charCode === 0x3c /* < */ ||
  26. charCode === 0x3e /* > */ ||
  27. charCode === 0x5b /* [ */ ||
  28. charCode === 0x5d /* ] */ ||
  29. charCode === 0x7b /* { */ ||
  30. charCode === 0x7d /* } */ ||
  31. charCode > 0x7e
  32. ) {
  33. // Char CharCode hexStr paddingHexStr Result
  34. // "\t" 9 9 09 #09
  35. // " " 32 20 20 #20
  36. // "©" 169 a9 a9 #a9
  37. var hexStr = charCode.toString(16),
  38. paddingHexStr = ("0" + hexStr).slice(-2);
  39. result += "#" + paddingHexStr;
  40. } else {
  41. // Other ASCII printable characters between 0x21 <= X <= 0x7e
  42. result += str[i];
  43. }
  44. }
  45. return result;
  46. }
  47. export { toPDFName };