在 PDF 到 JPG 转换网页中设置 GlobalWorkerOptions.workerSrc 和加载 jsPDF 库的问题

问题描述 投票:0回答:1

我正在尝试创建一个 HTML 网页,可以将 PDF 文件转换为 JPG 图像,然后将重新排列的页面导出为新的 PDF 文件。

代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>PDF pages rearranger</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
    <style>
      /* Define the style for the container element */
      #container {
        width: 600px;
        height: 400px;
        border: 1px solid black;
        margin: 20px auto;
        overflow: auto;
      }

      /* Define the style for the image elements */
      img {
        width: 100px;
        height: 100px;
        margin: 10px;
        cursor: move; /* Change the cursor to indicate that the images are draggable */
      }
    </style>

    <!-- Load the jQuery library from a CDN -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Load the jQuery UI library from a CDN -->
    <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>

    <!-- Load the jsPDF library from a CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
  </head>
  <body>
    <input type="file" id="fileInput" accept=".pdf" />
    <button id="convertButton">Convert to JPG</button>
    <!-- Create a div element to hold the images -->
    <div id="container"></div>
    <!-- Create a button to export the rearranged pages as a new PDF file -->
    <button id="exportButton">Export as PDF</button>

    <script>
      // Set the GlobalWorkerOptions.workerSrc property
      window.GlobalWorkerOptions = {
        workerSrc: 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js'
      };

      const fileInput = document.getElementById('fileInput');
      const convertButton = document.getElementById('convertButton');
      const container = document.getElementById('container');
      const exportButton = document.getElementById('exportButton');

      convertButton.addEventListener('click', async () => {
        const file = fileInput.files[0];
        if (!file) {
          alert('Please select a PDF file first');
          return;
        }

        // Clear any existing images in the container
        container.innerHTML = '';

        const reader = new FileReader();
        reader.onload = async (event) => {
          const typedArray = new Uint8Array(event.target.result);
          const pdfDocument = await pdfjsLib.getDocument(typedArray).promise;
          const numPages = pdfDocument.numPages;

          for (let i = 1; i <= numPages; i++) {
            const page = await pdfDocument.getPage(i);
            const viewport = page.getViewport({ scale: 1.0 });
            const canvas = document.createElement('canvas');
            canvas.width = viewport.width;
            canvas.height = viewport.height;
            const ctx = canvas.getContext('2d');
            await page.render({ canvasContext: ctx, viewport }).promise;
            const dataUrl = canvas.toDataURL('image/jpeg');
            download(dataUrl, `page${i}.jpg`);

            // Create an img element for each page and add it to the container
            const img = document.createElement('img');
            img.src = dataUrl;
            img.alt = `Page ${i}`;
            container.appendChild(img);
          }

          // Make the image elements draggable and sortable using jQuery UI
          $("#container").sortable({
            // Define a helper function to create a clone of the dragged image
            helper: function(e, ui) {
              return $(ui).clone().appendTo("#container").show();
            }
          });
        };
        reader.readAsArrayBuffer(file);
      });

      exportButton.addEventListener('click', () => {
        // Create a new jsPDF instance
        const doc = new jsPDF();

        // Get all the img elements in the container
        const images = container.querySelectorAll('img');

        // Add each image to the PDF document
        images.forEach((img, index) => {
          if (index > 0) {
            doc.addPage();
          }
          doc.addImage(img.src, 'JPEG', 10, 10);
        });

        // Save the PDF document
        doc.save('rearranged.pdf');
      });

      function download(dataUrl, filename) {
        const link = document.createElement('a');
        link.href = dataUrl;
        link.download = filename;
        link.click();
      }
    </script>
  </body>
</html>

但是,当我尝试运行代码时,遇到了两个问题:

当我单击“转换为 JPG”按钮时,出现第一条警告消息,显示“已弃用的 API 使用:未指定 GlobalWorkerOptions.workerSrc”。我猜这是由于 GlobalWorkerOptions.workerSrc 属性设置不正确造成的。

当我单击“导出为 PDF”按钮时,出现第二条警告消息,显示“未捕获的引用错误:jsPDF 未定义”。看来 jsPDF 库没有正确加载。

任何人都可以帮助我了解可能导致这些问题的原因并提供如何解决这些问题的建议吗?

javascript html jquery-ui jspdf pdf.js
1个回答
0
投票

您面临的问题确实与外部库的加载顺序和潜在的计时问题有关。让我们分别解决每个问题:

  1. 已弃用的 API 使用警告 (GlobalWorkerOptions.workerSrc): 要修复“已弃用的 API 使用”警告,您需要在加载

    GlobalWorkerOptions.workerSrc
    库后设置
    pdf.js
    属性。您可以在初始化
    workerSrc
    对象时使用
    pdfjsLib
    选项来实现此目的。将以下代码放在脚本的开头:

    const workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';
    const pdfjsLib = window['pdfjs-dist/build/pdf'];
    
    pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;
    

    然后,您可以像以前一样继续编写脚本的其余部分。

  2. 未捕获的引用错误:jsPDF 未定义: 发生此错误的原因是未加载或识别

    jsPDF
    库。在使用之前,您需要确保
    jsPDF
    库已完全加载。

    要解决此问题,您可以将导出代码包含在

    jsPDF
    脚本的
    load
    事件的事件侦听器中。具体方法如下:

    const jsPDFScript = document.createElement('script');
    jsPDFScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
    jsPDFScript.onload = () => {
      // Your export code here
      exportButton.addEventListener('click', () => {
        // ... (your existing export code)
      });
    };
    document.body.appendChild(jsPDFScript);
    

    将此脚本放在定义

    exportButton
    和其他元素的部分之后。

通过解决这两个问题,您的代码应该按预期工作,不会出现警告和错误。关键是确保所需的库以正确的顺序加载和初始化。

© www.soinside.com 2019 - 2024. All rights reserved.