简体   繁体   English

如何将客户端 PDF 文件对象上传到 pdf-lib JavaScript 库

[英]How to upload a client PDF file object to the pdf-lib JavaScript library

I have looked at the pdf-lib website and do not see any example to load a PDF using an "input file" on the client side.我查看了 pdf-lib 网站,没有看到任何在客户端使用“输入文件”加载 PDF 的示例。 All examples points to a URL to load a PDF.所有示例都指向加载 PDF 的 URL。 Is it possible to pass a file object to the function that reads the PDF instead of a URL?是否可以将文件对象传递给读取 PDF 而不是 URL 的函数?

const formPDFBytes = await fetch(url).then(res => res.arrayBuffer())
const pdfDoc= await PDFDocument.load(formPDFBytes );

I think if we can somehow set the file object as an array buffer to formPDFBytes, that may do the trick.我认为如果我们能以某种方式将文件对象设置为形成 PDFBytes 的数组缓冲区,那可能会奏效。

[From OP comments] [来自OP评论]

The user is the one who has the PDF and loads it via the DOM input file dialog.用户是拥有 PDF 并通过 DOM 输入文件对话框加载它的人。 So nothing here would be sent to the server and the entire PDF parsing operation is done by the client.所以这里什么都不会发送到服务器,整个 PDF 解析操作由客户端完成。

According to pdf-lib 's code, the PDFDocument.load function accepts in the first argument a string | Uint8Array | ArrayBuffer根据pdf-lib的代码, PDFDocument.load函数在第一个参数中接受一个string | Uint8Array | ArrayBuffer string | Uint8Array | ArrayBuffer string | Uint8Array | ArrayBuffer . string | Uint8Array | ArrayBuffer

If you want to read a file locally, you can do this:如果要在本地读取文件,可以这样做:

import fs from 'fs'
const uint8Array = fs.readFileSync('/path/to/myFile.pdf')
const pdfDoc3 = await PDFDocument.load(uint8Array)

if you want to load the file from the <input type="file" /> element, you need firstly to read the file as ArrayBuffer.如果要从<input type="file" />元素加载文件,首先需要将文件作为 ArrayBuffer 读取。

      <input type="file" id="file">
      //


      const file = document.getElementById('file').files[0]

      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = () => {
        const pdfDoc = await PDFDocument.load(reader.result);
        //...
      };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM