This content originally appeared on DEV Community and was authored by Shaked
Hey, my name is Shaked, and I want you to have the easiest time learning how to create and save a docx file client side. So without more talking, let's start.
By the way, this code is with Vue js, but this example can be used in any other framework, like React Angular and Svelte.
One last thing if you are using a server side framework like nuxt.js/ next.js, please use client-side rending for this component, so you do not have any issues with that (only when you create the file in the server-side life cycle hook)
<template>
<div>
<div @click="exportDocx">
Generate .docx file
</div>
</div>
</template>
<script>
import { Document, Packer, Paragraph, TextRun } from "docx";
// import { saveAs } from 'file-saver'; // you can use this also
const FileSaver = require("file-saver");
export default {
methods: {
exportDocx() {
// Create a new Document an save it in a variable
const doc = new Document({
sections: [
{
properties: {},
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
new TextRun({
text: "אני אדם כמו כל אדם אחר בעולם חחחחחחחחחח הצחקתי את עצמי ",
bold: true,
}),
],
}),
],
},
],
});
const mimeType =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const fileName = "test.docx";
Packer.toBlob(doc).then((blob) => {
const docblob = blob.slice(0, blob.size, mimeType);
FileSaver.saveAs(docblob, fileName);
});
},
},
};
</script>
<style lang="scss" scoped>
</style>```
This content originally appeared on DEV Community and was authored by Shaked
Shaked | Sciencx (2021-08-29T07:51:17+00:00) Vue and Docx file. Retrieved from https://www.scien.cx/2021/08/29/vue-and-docx-file/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.