Now I want to implement a functionality to add QR code image at the first page of an existing docx file in nodejs.
I've tried these three methods but not able to solve.
{%image}
into image file.Is there any solution here? Thanks in advance.
Actually, it is hard to attach image directly to docx file.
To do so, you need to add the image into word/media
folder, update relation in word/_rels/document.xml.rels
file and add proper xml string which represent the image to word/document.xml
file.
But it doesn't work well with most files and it will corrupt even though the file is recoverable.
So my suggestion is to add {%image}
text into docx file and replace it with the image using docxtemplater.
To add {%image}
into docx file, you need to add this xml string <w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">{%image}</w:t></w:r></w:p>
into word/document.xml
.
const originFile = fs.readFileSync(path.resolve('origin.docx'), 'binary');
const originZip = await JSZip.loadAsync(originFile);
const originDocumentFile = originZip.file(/^word\/document[0-9]*.xml$/)[0];
let originDocumentXml = await originDocumentFile.async("string");
const startIndex = originDocumentXml.indexOf("<w:body>") + 8;
originDocumentXml = originDocumentXml.slice(0, startIndex) + '<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">{%image}</w:t></w:r></w:p>' + originDocumentXml.slice(startIndex);
originZip.file(originDocumentFile.name, originDocumentXml);
const updateFile = await originZip.generateAsync({ type: 'nodebuffer' });
fs.writeFile("output.docx", updateFile, function(err) {/*...*/});