0

我在客户端上传了一个 docx 文件并用于fast-xml-parser将 docx 文件解析为 xml,在此之前jszip,我使用 打开文档存档。

const doc = fs.readFileSync(files.uploadFile.path);
const zip = new JSZip();
await zip.loadAsync(doc);
const xml = await zip?.file("word/document.xml")?.async("string");
const options = {
      attributeNamePrefix: "@_",
      attrNodeName: "attr", //default is 'false'
      textNodeName: "#text",
      ignoreAttributes: true,
      ignoreNameSpace: false,
      allowBooleanAttributes: false,
      parseNodeValue: true,
      parseAttributeValue: false,
      trimValues: true,
      cdataTagName: "__cdata", //default is 'false'
      cdataPositionChar: "\\c",
      localeRange: "", //To support non english character in tag/attribute values.
      parseTrueNumberOnly: false
};
let docObj = parser.parse(xml, options, true);
docObj['w:document'] = [...docObj['w:document'], await QRCode.toDataURL('2323'), 50, 330, { width: 50, height: 50 }];

解析后,我尝试在文档末尾插入二维码(使用qrcode库),结果出现错误docObj.w:document is not iterable

解析后的文档结构

docObj:  {
  'w:document': { 'w:body': { 'w:p': [Array], 'w:sectPr': [Object] } }
}

我在做什么错,为什么 w:document 不可迭代?如何将 qrcode 插入到文档中?

我还尝试使用docxtemplater读取 docx 文件

const content = fs.readFileSync(files.uploadFile.path, 'binary');
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true });
doc.setData('test');
doc.render();
const buf = doc.getZip().generate({type: 'nodebuffer'});
fs.writeFileSync('testDoc.docx', buf);

但是文件保存不变,是否可以在没有占位符的情况下以某种方式对文件进行更改?

4

0 回答 0