我正在try 创建一个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>

然而,当我try 运行代码时,我遇到了两个问题:

当我单击"转换为JPG"按钮时,出现第一条警告消息,提示"不推荐使用API:未指定GlobalWorkerOptions.workerSrc".我想这是由于没有正确设置GlobalWorkerOptions.workerSrc属性造成的.

当我单击"导出为PDF"按钮时,出现第二条警告消息,提示"未定义unautReferenceError:jsPDF".因此,jsPDF库似乎没有正确加载.

谁能帮助我了解可能导致这些问题的原因,并提供如何解决这些问题的建议?

Edit:

在@Alirahmon Nuraliev的帮助下,我的第一个问题解决了,但是第二个问题仍然没有解决,那就是UnautReferenceError:jsPDF is not fined.

我更正的代码如下:

<!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>
  </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
      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;

      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);
      });

      // Load jsPDF library and add event listener for export button
      const jsPDFScript = document.createElement('script');
      jsPDFScript.src =
        'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
      jsPDFScript.onload = () => {
        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');
        });
      };
      document.body.appendChild(jsPDFScript);

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

推荐答案

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

  1. Deprecated API usage warning (GlobalWorkerOptions.workerSrc): 要修复"已弃用API用法"警告,需要在加载pdf.js库后设置GlobalWorkerOptions.workerSrc属性.可以通过在初始化pdfjsLib对象时使用workerSrc选项来实现这一点.将以下代码放在脚本的开头:

    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. Uncaught ReferenceError: jsPDF is not defined: 出现此错误的原因是无法加载或识别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和其他元素的部分之后.

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

Javascript相关问答推荐

如何在NightWatch.js测试中允许浏览器权限?

容器如何更改默认插槽中子项的显示?

仅圆角的甜甜圈图表

vscode扩展-webView Panel按钮不起任何作用

docx.js:如何在客户端使用文档修补程序

如何在Connect 4游戏中 for each 玩家使用位板寻找7形状?

如何在不创建新键的情况下动态更改 map 中的项目?

配置WebAssembly/Emscripten本地生成问题

函数返回与输入对象具有相同键的对象

CheckBox作为Vue3中的一个组件

S文本内容和值不必要的不同

在使用REACT更改了CSS类之后,无法更改CSS样式

如何在箭头函数中引入or子句?

为什么客户端没有收到来自服务器的响应消息?

在FAQ Accodion应用程序中使用React useState时出现问题

Vaadin定制组件-保持对javascrip变量的访问

将基元传递给THEN处理程序

如何在Java脚本中并行运行for或任意循环的每次迭代

$GTE的mongoose 问题

如果我将高度设置为其内容的100%,则在Java脚本中拖动以调整面板大小时会冻结