pdfAnnotations.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. define(['base', './pdfJsLoader'], (App, PDFJS) => {
  2. const EXTERNAL_LINK_TARGET = '_blank'
  3. const REL_NOOPENER = 'noreferrer noopener'
  4. App.factory('pdfAnnotations', function() {
  5. class pdfAnnotations {
  6. constructor(options) {
  7. this.annotationsLayerDiv = options.annotations
  8. this.viewport = options.viewport
  9. this.navigateFn = options.navigateFn
  10. }
  11. setAnnotations(annotations) {
  12. const result = []
  13. for (let annotation of annotations) {
  14. switch (annotation.subtype) {
  15. case 'Link':
  16. result.push(this.addLink(annotation))
  17. break
  18. case 'Text':
  19. continue
  20. default:
  21. result.push(undefined)
  22. }
  23. }
  24. }
  25. addLink(link) {
  26. const element = this.buildLinkElementFromRect(link.rect)
  27. this.setLinkTarget(element, link)
  28. this.annotationsLayerDiv.appendChild(element)
  29. }
  30. buildLinkElementFromRect(rect) {
  31. rect = this.viewport.convertToViewportRectangle(rect)
  32. rect = PDFJS.Util.normalizeRect(rect)
  33. const element = document.createElement('a')
  34. element.style.left = Math.floor(rect[0]) + 'px'
  35. element.style.top = Math.floor(rect[1]) + 'px'
  36. element.style.width = Math.ceil(rect[2] - rect[0]) + 'px'
  37. element.style.height = Math.ceil(rect[3] - rect[1]) + 'px'
  38. return element
  39. }
  40. setLinkTarget(element, link) {
  41. if (link.url) {
  42. element.href = link.url
  43. element.target = EXTERNAL_LINK_TARGET
  44. element.rel = REL_NOOPENER
  45. } else if (link.dest) {
  46. element.href = `#${link.dest}`
  47. element.onclick = () => {
  48. this.navigateFn(link)
  49. return false
  50. }
  51. }
  52. }
  53. }
  54. return pdfAnnotations
  55. })
  56. })