helloworld.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>'Hello, world!' example</title>
  6. </head>
  7. <body>
  8. <h1>'Hello, world!' example</h1>
  9. <canvas id="the-canvas" style="border: 1px solid black; direction: ltr;"></canvas>
  10. <script src="../../node_modules/pdfjs-dist/build/pdf.js"></script>
  11. <script id="script">
  12. //
  13. // If absolute URL from the remote server is provided, configure the CORS
  14. // header on that server.
  15. //
  16. const url = './helloworld.pdf';
  17. //
  18. // The workerSrc property shall be specified.
  19. //
  20. pdfjsLib.GlobalWorkerOptions.workerSrc =
  21. '../../node_modules/pdfjs-dist/build/pdf.worker.js';
  22. //
  23. // Asynchronous download PDF
  24. //
  25. const loadingTask = pdfjsLib.getDocument(url);
  26. (async () => {
  27. const pdf = await loadingTask.promise;
  28. //
  29. // Fetch the first page
  30. //
  31. const page = await pdf.getPage(1);
  32. const scale = 1.5;
  33. const viewport = page.getViewport({ scale });
  34. // Support HiDPI-screens.
  35. const outputScale = window.devicePixelRatio || 1;
  36. //
  37. // Prepare canvas using PDF page dimensions
  38. //
  39. const canvas = document.getElementById("the-canvas");
  40. const context = canvas.getContext("2d");
  41. canvas.width = Math.floor(viewport.width * outputScale);
  42. canvas.height = Math.floor(viewport.height * outputScale);
  43. canvas.style.width = Math.floor(viewport.width) + "px";
  44. canvas.style.height = Math.floor(viewport.height) + "px";
  45. const transform = outputScale !== 1
  46. ? [outputScale, 0, 0, outputScale, 0, 0]
  47. : null;
  48. //
  49. // Render PDF page into canvas context
  50. //
  51. const renderContext = {
  52. canvasContext: context,
  53. transform,
  54. viewport,
  55. };
  56. page.render(renderContext);
  57. })();
  58. </script>
  59. <hr>
  60. <h2>JavaScript code:</h2>
  61. <pre id="code"></pre>
  62. <script>
  63. document.getElementById('code').textContent =
  64. document.getElementById('script').text;
  65. </script>
  66. </body>
  67. </html>