display_utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.addLinkAttributes = addLinkAttributes;
  27. exports.getFilenameFromUrl = getFilenameFromUrl;
  28. exports.isFetchSupported = isFetchSupported;
  29. exports.isValidFetchUrl = isValidFetchUrl;
  30. exports.loadScript = loadScript;
  31. exports.deprecated = deprecated;
  32. exports.PDFDateString = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.BaseCMapReaderFactory = exports.DOMCanvasFactory = exports.BaseCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;
  33. var _util = require("../shared/util.js");
  34. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  35. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  36. const SVG_NS = "http://www.w3.org/2000/svg";
  37. class BaseCanvasFactory {
  38. constructor() {
  39. if (this.constructor === BaseCanvasFactory) {
  40. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  41. }
  42. }
  43. create(width, height) {
  44. (0, _util.unreachable)("Abstract method `create` called.");
  45. }
  46. reset(canvasAndContext, width, height) {
  47. if (!canvasAndContext.canvas) {
  48. throw new Error("Canvas is not specified");
  49. }
  50. if (width <= 0 || height <= 0) {
  51. throw new Error("Invalid canvas size");
  52. }
  53. canvasAndContext.canvas.width = width;
  54. canvasAndContext.canvas.height = height;
  55. }
  56. destroy(canvasAndContext) {
  57. if (!canvasAndContext.canvas) {
  58. throw new Error("Canvas is not specified");
  59. }
  60. canvasAndContext.canvas.width = 0;
  61. canvasAndContext.canvas.height = 0;
  62. canvasAndContext.canvas = null;
  63. canvasAndContext.context = null;
  64. }
  65. }
  66. exports.BaseCanvasFactory = BaseCanvasFactory;
  67. class DOMCanvasFactory extends BaseCanvasFactory {
  68. constructor({
  69. ownerDocument = globalThis.document
  70. } = {}) {
  71. super();
  72. this._document = ownerDocument;
  73. }
  74. create(width, height) {
  75. if (width <= 0 || height <= 0) {
  76. throw new Error("Invalid canvas size");
  77. }
  78. const canvas = this._document.createElement("canvas");
  79. const context = canvas.getContext("2d");
  80. canvas.width = width;
  81. canvas.height = height;
  82. return {
  83. canvas,
  84. context
  85. };
  86. }
  87. }
  88. exports.DOMCanvasFactory = DOMCanvasFactory;
  89. class BaseCMapReaderFactory {
  90. constructor({
  91. baseUrl = null,
  92. isCompressed = false
  93. }) {
  94. if (this.constructor === BaseCMapReaderFactory) {
  95. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  96. }
  97. this.baseUrl = baseUrl;
  98. this.isCompressed = isCompressed;
  99. }
  100. async fetch({
  101. name
  102. }) {
  103. if (!this.baseUrl) {
  104. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  105. }
  106. if (!name) {
  107. throw new Error("CMap name must be specified.");
  108. }
  109. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  110. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  111. return this._fetchData(url, compressionType).catch(reason => {
  112. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  113. });
  114. }
  115. _fetchData(url, compressionType) {
  116. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  117. }
  118. }
  119. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  120. class DOMCMapReaderFactory extends BaseCMapReaderFactory {
  121. _fetchData(url, compressionType) {
  122. if (isFetchSupported() && isValidFetchUrl(url, document.baseURI)) {
  123. return fetch(url).then(async response => {
  124. if (!response.ok) {
  125. throw new Error(response.statusText);
  126. }
  127. let cMapData;
  128. if (this.isCompressed) {
  129. cMapData = new Uint8Array(await response.arrayBuffer());
  130. } else {
  131. cMapData = (0, _util.stringToBytes)(await response.text());
  132. }
  133. return {
  134. cMapData,
  135. compressionType
  136. };
  137. });
  138. }
  139. return new Promise((resolve, reject) => {
  140. const request = new XMLHttpRequest();
  141. request.open("GET", url, true);
  142. if (this.isCompressed) {
  143. request.responseType = "arraybuffer";
  144. }
  145. request.onreadystatechange = () => {
  146. if (request.readyState !== XMLHttpRequest.DONE) {
  147. return;
  148. }
  149. if (request.status === 200 || request.status === 0) {
  150. let cMapData;
  151. if (this.isCompressed && request.response) {
  152. cMapData = new Uint8Array(request.response);
  153. } else if (!this.isCompressed && request.responseText) {
  154. cMapData = (0, _util.stringToBytes)(request.responseText);
  155. }
  156. if (cMapData) {
  157. resolve({
  158. cMapData,
  159. compressionType
  160. });
  161. return;
  162. }
  163. }
  164. reject(new Error(request.statusText));
  165. };
  166. request.send(null);
  167. });
  168. }
  169. }
  170. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  171. class DOMSVGFactory {
  172. create(width, height) {
  173. (0, _util.assert)(width > 0 && height > 0, "Invalid SVG dimensions");
  174. const svg = document.createElementNS(SVG_NS, "svg:svg");
  175. svg.setAttribute("version", "1.1");
  176. svg.setAttribute("width", width + "px");
  177. svg.setAttribute("height", height + "px");
  178. svg.setAttribute("preserveAspectRatio", "none");
  179. svg.setAttribute("viewBox", "0 0 " + width + " " + height);
  180. return svg;
  181. }
  182. createElement(type) {
  183. (0, _util.assert)(typeof type === "string", "Invalid SVG element type");
  184. return document.createElementNS(SVG_NS, type);
  185. }
  186. }
  187. exports.DOMSVGFactory = DOMSVGFactory;
  188. class PageViewport {
  189. constructor({
  190. viewBox,
  191. scale,
  192. rotation,
  193. offsetX = 0,
  194. offsetY = 0,
  195. dontFlip = false
  196. }) {
  197. this.viewBox = viewBox;
  198. this.scale = scale;
  199. this.rotation = rotation;
  200. this.offsetX = offsetX;
  201. this.offsetY = offsetY;
  202. const centerX = (viewBox[2] + viewBox[0]) / 2;
  203. const centerY = (viewBox[3] + viewBox[1]) / 2;
  204. let rotateA, rotateB, rotateC, rotateD;
  205. rotation = rotation % 360;
  206. rotation = rotation < 0 ? rotation + 360 : rotation;
  207. switch (rotation) {
  208. case 180:
  209. rotateA = -1;
  210. rotateB = 0;
  211. rotateC = 0;
  212. rotateD = 1;
  213. break;
  214. case 90:
  215. rotateA = 0;
  216. rotateB = 1;
  217. rotateC = 1;
  218. rotateD = 0;
  219. break;
  220. case 270:
  221. rotateA = 0;
  222. rotateB = -1;
  223. rotateC = -1;
  224. rotateD = 0;
  225. break;
  226. case 0:
  227. rotateA = 1;
  228. rotateB = 0;
  229. rotateC = 0;
  230. rotateD = -1;
  231. break;
  232. default:
  233. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  234. }
  235. if (dontFlip) {
  236. rotateC = -rotateC;
  237. rotateD = -rotateD;
  238. }
  239. let offsetCanvasX, offsetCanvasY;
  240. let width, height;
  241. if (rotateA === 0) {
  242. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  243. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  244. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  245. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  246. } else {
  247. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  248. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  249. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  250. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  251. }
  252. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  253. this.width = width;
  254. this.height = height;
  255. }
  256. clone({
  257. scale = this.scale,
  258. rotation = this.rotation,
  259. offsetX = this.offsetX,
  260. offsetY = this.offsetY,
  261. dontFlip = false
  262. } = {}) {
  263. return new PageViewport({
  264. viewBox: this.viewBox.slice(),
  265. scale,
  266. rotation,
  267. offsetX,
  268. offsetY,
  269. dontFlip
  270. });
  271. }
  272. convertToViewportPoint(x, y) {
  273. return _util.Util.applyTransform([x, y], this.transform);
  274. }
  275. convertToViewportRectangle(rect) {
  276. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  277. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  278. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  279. }
  280. convertToPdfPoint(x, y) {
  281. return _util.Util.applyInverseTransform([x, y], this.transform);
  282. }
  283. }
  284. exports.PageViewport = PageViewport;
  285. class RenderingCancelledException extends _util.BaseException {
  286. constructor(msg, type) {
  287. super(msg);
  288. this.type = type;
  289. }
  290. }
  291. exports.RenderingCancelledException = RenderingCancelledException;
  292. const LinkTarget = {
  293. NONE: 0,
  294. SELF: 1,
  295. BLANK: 2,
  296. PARENT: 3,
  297. TOP: 4
  298. };
  299. exports.LinkTarget = LinkTarget;
  300. function addLinkAttributes(link, {
  301. url,
  302. target,
  303. rel,
  304. enabled = true
  305. } = {}) {
  306. (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
  307. const urlNullRemoved = (0, _util.removeNullCharacters)(url);
  308. if (enabled) {
  309. link.href = link.title = urlNullRemoved;
  310. } else {
  311. link.href = "";
  312. link.title = `Disabled: ${urlNullRemoved}`;
  313. link.onclick = () => {
  314. return false;
  315. };
  316. }
  317. let targetStr = "";
  318. switch (target) {
  319. case LinkTarget.NONE:
  320. break;
  321. case LinkTarget.SELF:
  322. targetStr = "_self";
  323. break;
  324. case LinkTarget.BLANK:
  325. targetStr = "_blank";
  326. break;
  327. case LinkTarget.PARENT:
  328. targetStr = "_parent";
  329. break;
  330. case LinkTarget.TOP:
  331. targetStr = "_top";
  332. break;
  333. }
  334. link.target = targetStr;
  335. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  336. }
  337. function getFilenameFromUrl(url) {
  338. const anchor = url.indexOf("#");
  339. const query = url.indexOf("?");
  340. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  341. return url.substring(url.lastIndexOf("/", end) + 1, end);
  342. }
  343. class StatTimer {
  344. constructor() {
  345. this.started = Object.create(null);
  346. this.times = [];
  347. }
  348. time(name) {
  349. if (name in this.started) {
  350. (0, _util.warn)(`Timer is already running for ${name}`);
  351. }
  352. this.started[name] = Date.now();
  353. }
  354. timeEnd(name) {
  355. if (!(name in this.started)) {
  356. (0, _util.warn)(`Timer has not been started for ${name}`);
  357. }
  358. this.times.push({
  359. name,
  360. start: this.started[name],
  361. end: Date.now()
  362. });
  363. delete this.started[name];
  364. }
  365. toString() {
  366. const outBuf = [];
  367. let longest = 0;
  368. for (const time of this.times) {
  369. const name = time.name;
  370. if (name.length > longest) {
  371. longest = name.length;
  372. }
  373. }
  374. for (const time of this.times) {
  375. const duration = time.end - time.start;
  376. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  377. }
  378. return outBuf.join("");
  379. }
  380. }
  381. exports.StatTimer = StatTimer;
  382. function isFetchSupported() {
  383. return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype && typeof ReadableStream !== "undefined";
  384. }
  385. function isValidFetchUrl(url, baseUrl) {
  386. try {
  387. const {
  388. protocol
  389. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  390. return protocol === "http:" || protocol === "https:";
  391. } catch (ex) {
  392. return false;
  393. }
  394. }
  395. function loadScript(src) {
  396. return new Promise((resolve, reject) => {
  397. const script = document.createElement("script");
  398. script.src = src;
  399. script.onload = resolve;
  400. script.onerror = function () {
  401. reject(new Error(`Cannot load script at: ${script.src}`));
  402. };
  403. (document.head || document.documentElement).appendChild(script);
  404. });
  405. }
  406. function deprecated(details) {
  407. console.log("Deprecated API usage: " + details);
  408. }
  409. let pdfDateStringRegex;
  410. class PDFDateString {
  411. static toDateObject(input) {
  412. if (!input || !(0, _util.isString)(input)) {
  413. return null;
  414. }
  415. if (!pdfDateStringRegex) {
  416. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  417. }
  418. const matches = pdfDateStringRegex.exec(input);
  419. if (!matches) {
  420. return null;
  421. }
  422. const year = parseInt(matches[1], 10);
  423. let month = parseInt(matches[2], 10);
  424. month = month >= 1 && month <= 12 ? month - 1 : 0;
  425. let day = parseInt(matches[3], 10);
  426. day = day >= 1 && day <= 31 ? day : 1;
  427. let hour = parseInt(matches[4], 10);
  428. hour = hour >= 0 && hour <= 23 ? hour : 0;
  429. let minute = parseInt(matches[5], 10);
  430. minute = minute >= 0 && minute <= 59 ? minute : 0;
  431. let second = parseInt(matches[6], 10);
  432. second = second >= 0 && second <= 59 ? second : 0;
  433. const universalTimeRelation = matches[7] || "Z";
  434. let offsetHour = parseInt(matches[8], 10);
  435. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  436. let offsetMinute = parseInt(matches[9], 10) || 0;
  437. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  438. if (universalTimeRelation === "-") {
  439. hour += offsetHour;
  440. minute += offsetMinute;
  441. } else if (universalTimeRelation === "+") {
  442. hour -= offsetHour;
  443. minute -= offsetMinute;
  444. }
  445. return new Date(Date.UTC(year, month, day, hour, minute, second));
  446. }
  447. }
  448. exports.PDFDateString = PDFDateString;