I'm curious if it is possible to append to a generated Word document that I've created with Js and docx module. Currently I can generate the document and format it. Yet, I'm not seeing anything in their documentation about appending or adding a paragraph to an existing document (there is a section on exporting, but it always creates a new file, even if its the same name). Is this a limitation in JavaScript? I'm assuming that since I'd want to look for the document in the system files, that this creates a security issue (JS from a browser looking for a file in a end user's system) and hence why docx doesn't do it. Any guidance on this is greatly appreciated. Also, if it's not then would using Word APIs solve this?
P.S. I can share the code that generates the document, but that part is running fine, I just need to know if what I want is possible or if I'm wasting time.
This is a function I've tried and found from stackoverflow, but it was for a web app, this is a chrome extension. I've looked around and can't find anything else to try. Idally I'd like to write to the doc generated and add to it.
// pretty sure I cann't utilize a function like this unfornately
// all code is functional before this is call
function writeToDocument(doc, text){
let paragraph = new docx.Paragraph();
// invalid code
// paragraph.addRun(new docx.TextRun(text));
// doc.addParagraph(paragraph);
let packer = new docx.Packer();
docx.packer.toBuffer(doc).then((buffer) =>{
fs.writeFileSync(docName + ".docx",buffer);
});
}
It looks this is limitation of library. There is addSection() but it is private. Also, there are no methods to open a previously generated file.
Only way is: first create content, and later create doc and save it:
let paragraphs = [];
//any way to add element to array, eg
paragraphs[paragraphs.length] = new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
new TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
});
//paragraphs[paragraphs.length] = addAnotherParagraph()
//create document
const doc = new Document({
sections: [
{
properties: {},
children: paragraphs,
},
],
});
//and save it in fauvorite way
Packer.toBuffer(doc).then((buffer) => {
//why in `docx` documentation uses sync versioin?... You should avoid it
fs.writeFileSync("My Document.docx", buffer);
});