modules/fileloading.js

  1. /* global jsPDF */
  2. /**
  3. * jsPDF fileloading PlugIn
  4. * Copyright (c) 2018 Aras Abbasi (aras.abbasi@gmail.com)
  5. *
  6. * Licensed under the MIT License.
  7. * http://opensource.org/licenses/mit-license
  8. */
  9. /**
  10. * @name fileloading
  11. * @module
  12. */
  13. (function (jsPDFAPI) {
  14. 'use strict';
  15. /**
  16. * @name loadFile
  17. * @function
  18. * @param {string} url
  19. * @param {boolean} sync
  20. * @param {function} callback
  21. * @returns {string|undefined} result
  22. */
  23. jsPDFAPI.loadFile = function (url, sync, callback) {
  24. sync = (sync === false) ? false : true;
  25. callback = typeof callback === 'function' ? callback : function () { };
  26. var result = undefined;
  27. var xhr = function (url, sync, callback) {
  28. var request = new XMLHttpRequest();
  29. var i = 0;
  30. var sanitizeUnicode = function (data) {
  31. var dataLength = data.length;
  32. var charArray = [];
  33. var StringFromCharCode = String.fromCharCode;
  34. //Transform Unicode to ASCII
  35. for (i = 0; i < dataLength; i += 1) {
  36. charArray.push(StringFromCharCode(data.charCodeAt(i) & 0xff))
  37. }
  38. return charArray.join('');
  39. }
  40. request.open('GET', url, !sync)
  41. // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  42. request.overrideMimeType('text/plain; charset=x-user-defined');
  43. if (sync === false) {
  44. request.onload = function () {
  45. if (request.status === 200) {
  46. callback(sanitizeUnicode(this.responseText));
  47. } else {
  48. callback(undefined);
  49. }
  50. };
  51. }
  52. request.send(null);
  53. if (sync && request.status === 200) {
  54. return sanitizeUnicode(request.responseText);
  55. }
  56. }
  57. try {
  58. result = xhr(url, sync, callback);
  59. // eslint-disable-next-line no-empty
  60. } catch (e) {}
  61. return result;
  62. };
  63. /**
  64. * @name loadImageFile
  65. * @function
  66. * @param {string} path
  67. * @param {boolean} sync
  68. * @param {function} callback
  69. */
  70. jsPDFAPI.loadImageFile = jsPDFAPI.loadFile;
  71. })(jsPDF.API);