You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Buffer类型PDF数据转为ArrayBuffer适配PDF-LIB加载?

解决方案

你的this.datatemplate是Node.js Buffer的序列化结构(包含type标识和data数字数组),PDF-LIB无法直接识别这种格式,需要将其转换为库支持的Uint8Array或ArrayBuffer类型。

具体修改代码

直接将datatemplate.data数组转换为Uint8Array,传入PDFDocument.load()即可:

this.templateService.get(data[0].templateId).subscribe({
  next: async (data) => {
    this.datatemplate = data.datatemplate;
    
    // 转换Buffer数据为Uint8Array
    const pdfData = new Uint8Array(this.datatemplate.data);
    const pdfDoc = await PDFDocument.load(pdfData);
    
    const form = pdfDoc.getForm();
    const fields = form.getFields();
    fields.forEach(field => {
      const type = field.constructor.name;
      const name = field.getName();
      console.log(`${type}: ${name}`);
    });
  }
});

可选:转换为ArrayBuffer

如果需要明确转成ArrayBuffer,可以在Uint8Array基础上获取其buffer属性:

const pdfArrayBuffer = new Uint8Array(this.datatemplate.data).buffer;
const pdfDoc = await PDFDocument.load(pdfArrayBuffer);

内容的提问来源于stack exchange,提问作者meth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 18:55:21