2
0

display_utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 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.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
  27. exports.deprecated = deprecated;
  28. exports.getColorValues = getColorValues;
  29. exports.getCurrentTransform = getCurrentTransform;
  30. exports.getCurrentTransformInverse = getCurrentTransformInverse;
  31. exports.getFilenameFromUrl = getFilenameFromUrl;
  32. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  33. exports.getRGB = getRGB;
  34. exports.getXfaPageViewport = getXfaPageViewport;
  35. exports.isDataScheme = isDataScheme;
  36. exports.isPdfFile = isPdfFile;
  37. exports.isValidFetchUrl = isValidFetchUrl;
  38. exports.loadScript = loadScript;
  39. var _base_factory = require("./base_factory.js");
  40. var _util = require("../shared/util.js");
  41. const SVG_NS = "http://www.w3.org/2000/svg";
  42. const AnnotationPrefix = "pdfjs_internal_id_";
  43. exports.AnnotationPrefix = AnnotationPrefix;
  44. class PixelsPerInch {
  45. static CSS = 96.0;
  46. static PDF = 72.0;
  47. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  48. }
  49. exports.PixelsPerInch = PixelsPerInch;
  50. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  51. constructor({
  52. ownerDocument = globalThis.document
  53. } = {}) {
  54. super();
  55. this._document = ownerDocument;
  56. }
  57. _createCanvas(width, height) {
  58. const canvas = this._document.createElement("canvas");
  59. canvas.width = width;
  60. canvas.height = height;
  61. return canvas;
  62. }
  63. }
  64. exports.DOMCanvasFactory = DOMCanvasFactory;
  65. async function fetchData(url, asTypedArray = false) {
  66. if (isValidFetchUrl(url, document.baseURI)) {
  67. const response = await fetch(url);
  68. if (!response.ok) {
  69. throw new Error(response.statusText);
  70. }
  71. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  72. }
  73. return new Promise((resolve, reject) => {
  74. const request = new XMLHttpRequest();
  75. request.open("GET", url, true);
  76. if (asTypedArray) {
  77. request.responseType = "arraybuffer";
  78. }
  79. request.onreadystatechange = () => {
  80. if (request.readyState !== XMLHttpRequest.DONE) {
  81. return;
  82. }
  83. if (request.status === 200 || request.status === 0) {
  84. let data;
  85. if (asTypedArray && request.response) {
  86. data = new Uint8Array(request.response);
  87. } else if (!asTypedArray && request.responseText) {
  88. data = (0, _util.stringToBytes)(request.responseText);
  89. }
  90. if (data) {
  91. resolve(data);
  92. return;
  93. }
  94. }
  95. reject(new Error(request.statusText));
  96. };
  97. request.send(null);
  98. });
  99. }
  100. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  101. _fetchData(url, compressionType) {
  102. return fetchData(url, this.isCompressed).then(data => {
  103. return {
  104. cMapData: data,
  105. compressionType
  106. };
  107. });
  108. }
  109. }
  110. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  111. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  112. _fetchData(url) {
  113. return fetchData(url, true);
  114. }
  115. }
  116. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  117. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  118. _createSVG(type) {
  119. return document.createElementNS(SVG_NS, type);
  120. }
  121. }
  122. exports.DOMSVGFactory = DOMSVGFactory;
  123. class PageViewport {
  124. constructor({
  125. viewBox,
  126. scale,
  127. rotation,
  128. offsetX = 0,
  129. offsetY = 0,
  130. dontFlip = false
  131. }) {
  132. this.viewBox = viewBox;
  133. this.scale = scale;
  134. this.rotation = rotation;
  135. this.offsetX = offsetX;
  136. this.offsetY = offsetY;
  137. const centerX = (viewBox[2] + viewBox[0]) / 2;
  138. const centerY = (viewBox[3] + viewBox[1]) / 2;
  139. let rotateA, rotateB, rotateC, rotateD;
  140. rotation %= 360;
  141. if (rotation < 0) {
  142. rotation += 360;
  143. }
  144. switch (rotation) {
  145. case 180:
  146. rotateA = -1;
  147. rotateB = 0;
  148. rotateC = 0;
  149. rotateD = 1;
  150. break;
  151. case 90:
  152. rotateA = 0;
  153. rotateB = 1;
  154. rotateC = 1;
  155. rotateD = 0;
  156. break;
  157. case 270:
  158. rotateA = 0;
  159. rotateB = -1;
  160. rotateC = -1;
  161. rotateD = 0;
  162. break;
  163. case 0:
  164. rotateA = 1;
  165. rotateB = 0;
  166. rotateC = 0;
  167. rotateD = -1;
  168. break;
  169. default:
  170. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  171. }
  172. if (dontFlip) {
  173. rotateC = -rotateC;
  174. rotateD = -rotateD;
  175. }
  176. let offsetCanvasX, offsetCanvasY;
  177. let width, height;
  178. if (rotateA === 0) {
  179. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  180. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  181. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  182. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  183. } else {
  184. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  185. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  186. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  187. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  188. }
  189. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  190. this.width = width;
  191. this.height = height;
  192. }
  193. clone({
  194. scale = this.scale,
  195. rotation = this.rotation,
  196. offsetX = this.offsetX,
  197. offsetY = this.offsetY,
  198. dontFlip = false
  199. } = {}) {
  200. return new PageViewport({
  201. viewBox: this.viewBox.slice(),
  202. scale,
  203. rotation,
  204. offsetX,
  205. offsetY,
  206. dontFlip
  207. });
  208. }
  209. convertToViewportPoint(x, y) {
  210. return _util.Util.applyTransform([x, y], this.transform);
  211. }
  212. convertToViewportRectangle(rect) {
  213. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  214. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  215. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  216. }
  217. convertToPdfPoint(x, y) {
  218. return _util.Util.applyInverseTransform([x, y], this.transform);
  219. }
  220. }
  221. exports.PageViewport = PageViewport;
  222. class RenderingCancelledException extends _util.BaseException {
  223. constructor(msg, type) {
  224. super(msg, "RenderingCancelledException");
  225. this.type = type;
  226. }
  227. }
  228. exports.RenderingCancelledException = RenderingCancelledException;
  229. function isDataScheme(url) {
  230. const ii = url.length;
  231. let i = 0;
  232. while (i < ii && url[i].trim() === "") {
  233. i++;
  234. }
  235. return url.substring(i, i + 5).toLowerCase() === "data:";
  236. }
  237. function isPdfFile(filename) {
  238. return typeof filename === "string" && /\.pdf$/i.test(filename);
  239. }
  240. function getFilenameFromUrl(url) {
  241. const anchor = url.indexOf("#");
  242. const query = url.indexOf("?");
  243. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  244. return url.substring(url.lastIndexOf("/", end) + 1, end);
  245. }
  246. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  247. if (typeof url !== "string") {
  248. return defaultFilename;
  249. }
  250. if (isDataScheme(url)) {
  251. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  252. return defaultFilename;
  253. }
  254. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  255. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  256. const splitURI = reURI.exec(url);
  257. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  258. if (suggestedFilename) {
  259. suggestedFilename = suggestedFilename[0];
  260. if (suggestedFilename.includes("%")) {
  261. try {
  262. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  263. } catch (ex) {}
  264. }
  265. }
  266. return suggestedFilename || defaultFilename;
  267. }
  268. class StatTimer {
  269. constructor() {
  270. this.started = Object.create(null);
  271. this.times = [];
  272. }
  273. time(name) {
  274. if (name in this.started) {
  275. (0, _util.warn)(`Timer is already running for ${name}`);
  276. }
  277. this.started[name] = Date.now();
  278. }
  279. timeEnd(name) {
  280. if (!(name in this.started)) {
  281. (0, _util.warn)(`Timer has not been started for ${name}`);
  282. }
  283. this.times.push({
  284. name,
  285. start: this.started[name],
  286. end: Date.now()
  287. });
  288. delete this.started[name];
  289. }
  290. toString() {
  291. const outBuf = [];
  292. let longest = 0;
  293. for (const time of this.times) {
  294. const name = time.name;
  295. if (name.length > longest) {
  296. longest = name.length;
  297. }
  298. }
  299. for (const time of this.times) {
  300. const duration = time.end - time.start;
  301. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  302. }
  303. return outBuf.join("");
  304. }
  305. }
  306. exports.StatTimer = StatTimer;
  307. function isValidFetchUrl(url, baseUrl) {
  308. try {
  309. const {
  310. protocol
  311. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  312. return protocol === "http:" || protocol === "https:";
  313. } catch (ex) {
  314. return false;
  315. }
  316. }
  317. function loadScript(src, removeScriptElement = false) {
  318. return new Promise((resolve, reject) => {
  319. const script = document.createElement("script");
  320. script.src = src;
  321. script.onload = function (evt) {
  322. if (removeScriptElement) {
  323. script.remove();
  324. }
  325. resolve(evt);
  326. };
  327. script.onerror = function () {
  328. reject(new Error(`Cannot load script at: ${script.src}`));
  329. };
  330. (document.head || document.documentElement).append(script);
  331. });
  332. }
  333. function deprecated(details) {
  334. console.log("Deprecated API usage: " + details);
  335. }
  336. let pdfDateStringRegex;
  337. class PDFDateString {
  338. static toDateObject(input) {
  339. if (!input || typeof input !== "string") {
  340. return null;
  341. }
  342. if (!pdfDateStringRegex) {
  343. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  344. }
  345. const matches = pdfDateStringRegex.exec(input);
  346. if (!matches) {
  347. return null;
  348. }
  349. const year = parseInt(matches[1], 10);
  350. let month = parseInt(matches[2], 10);
  351. month = month >= 1 && month <= 12 ? month - 1 : 0;
  352. let day = parseInt(matches[3], 10);
  353. day = day >= 1 && day <= 31 ? day : 1;
  354. let hour = parseInt(matches[4], 10);
  355. hour = hour >= 0 && hour <= 23 ? hour : 0;
  356. let minute = parseInt(matches[5], 10);
  357. minute = minute >= 0 && minute <= 59 ? minute : 0;
  358. let second = parseInt(matches[6], 10);
  359. second = second >= 0 && second <= 59 ? second : 0;
  360. const universalTimeRelation = matches[7] || "Z";
  361. let offsetHour = parseInt(matches[8], 10);
  362. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  363. let offsetMinute = parseInt(matches[9], 10) || 0;
  364. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  365. if (universalTimeRelation === "-") {
  366. hour += offsetHour;
  367. minute += offsetMinute;
  368. } else if (universalTimeRelation === "+") {
  369. hour -= offsetHour;
  370. minute -= offsetMinute;
  371. }
  372. return new Date(Date.UTC(year, month, day, hour, minute, second));
  373. }
  374. }
  375. exports.PDFDateString = PDFDateString;
  376. function getXfaPageViewport(xfaPage, {
  377. scale = 1,
  378. rotation = 0
  379. }) {
  380. const {
  381. width,
  382. height
  383. } = xfaPage.attributes.style;
  384. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  385. return new PageViewport({
  386. viewBox,
  387. scale,
  388. rotation
  389. });
  390. }
  391. function getRGB(color) {
  392. if (color.startsWith("#")) {
  393. const colorRGB = parseInt(color.slice(1), 16);
  394. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  395. }
  396. if (color.startsWith("rgb(")) {
  397. return color.slice(4, -1).split(",").map(x => parseInt(x));
  398. }
  399. if (color.startsWith("rgba(")) {
  400. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  401. }
  402. (0, _util.warn)(`Not a valid color format: "${color}"`);
  403. return [0, 0, 0];
  404. }
  405. function getColorValues(colors) {
  406. const span = document.createElement("span");
  407. span.style.visibility = "hidden";
  408. document.body.append(span);
  409. for (const name of colors.keys()) {
  410. span.style.color = name;
  411. const computedColor = window.getComputedStyle(span).color;
  412. colors.set(name, getRGB(computedColor));
  413. }
  414. span.remove();
  415. }
  416. function getCurrentTransform(ctx) {
  417. const {
  418. a,
  419. b,
  420. c,
  421. d,
  422. e,
  423. f
  424. } = ctx.getTransform();
  425. return [a, b, c, d, e, f];
  426. }
  427. function getCurrentTransformInverse(ctx) {
  428. const {
  429. a,
  430. b,
  431. c,
  432. d,
  433. e,
  434. f
  435. } = ctx.getTransform().invertSelf();
  436. return [a, b, c, d, e, f];
  437. }