Articles in this section
Category / Section

How to view and edit Word documents in Vue3 app using Word Processor?

7 mins read

This article will explain how to view and edit Word documents with the key features of Syncfusion’s Vue Word Processor component, and the procedure to integrate it into a Vue3 application.

The Syncfusion Vue Word Processor is also known as document editor. It is a component used to compose, edit, view, and print Word (DOCX, WordML, DOC, RTF, TXT) documents in your Vue applications. It provides all the standard Word processing features, such as:

  • Editing text
  • Formatting content
  • Resizing images and tables
  • Finding and replacing text
  • Bookmarks
  • Tables of contents
  • Printing
  • Importing and exporting Word documents.

All the user interactions and editing operations run purely on the client side using our own SFDT (Syncfusion document text) file format. This approach provides a very fast editing experience to the end users.

Syncfusion offers two components for the same purpose:

  • Document editor provides just the main document view area. Here, the user can compose, view, and edit the Word documents. You may prefer to use this component when you want to design your own UI options for your application.

Syncfusion Document Editor

Syncfusion Document Editor

  • Document editor container provides the main document view area along with the built-in toolbar and properties pane.

Syncfusion Document Editor Container

Syncfusion Document Editor Container

Features of Word Processor

  • Compose Word documents.
  • View or edit existing Word documents.
  • Print Word documents.
  • Find and replace.
  • Spell checking.
  • Track changes.
  • Add, edit, or delete comments.
  • Copy and paste content from other applications.
  • Protect the entire Word document or a particular range of the document.
  • Render right-to-left (RTL).
  • View in print layout (page-by-page view) or web layout.
  • Customize toolbar and context menu.
  • Format text, paragraphs, and tables.
  • Style characters and paragraphs. Add custom styles.
  • Bullets and numbering.
  • Hyperlinks.
  • Bookmarks.
  • Page setup.
  • Headers and footers.
  • Footnote and endnote.
  • Legacy form fields.
  • Tables of contents.
  • Page numbers.
    Note:

    This component requires server-side interaction for these operations:

    • Opening Word documents (converting Word to SFDT file format)
    • Pasting with formatting
    • Restricting editing
    • Spell checking

     

    A server-side Web API can be created using ASP.NET MVC and ASP.NET Core. Access the Document Editor Web API service projects from GitHub.

     

    Also, you can directly pull and consume our predefined Word Processor server Docker image from Docker Hub. This server-side Web API project is targeting ASP.NET Core 2.1.

At present, Syncfusion Word Processor performs spell checking for an entire document’s content for only one language at a time. The spell checker identifies the language through the languageID property. Whereas you can add multiple language dictionaries in the server-side Web API. Then, switch the `languageID` in client-side to different languages.

Host Word Processor Web API from Docker Hub image

The Vue Word Processor component facilitates a predefined Word Processor server Docker image. This image contains all the mandatory web APIs for opening Word documents, pasting with formatting, restricting editing, spell checking, and saving documents. You can pull this Docker image and deploy it directly in your server on the go.

If you want to add new functionality or customize any existing functionalities, create your own Docker file by referencing the existing Word Processor Docker project.

Please refer our UG documentation to know more about deploying Word Processor docker image.

Create new Vue3 app with Word Processor component

To create a Vue3 app, please set up your environment with the following prerequisites:

Now, proceed in creating a new Vue3 app and integrate the Word Processor component using the following steps:

Step 1: First, create a new Vue3 demo project. Please refer to the documentation for creating a new Vue3 app in the local machine.

Step 2: After creating a new Vue3 app, install the Vue document editor NuGet package.

The following command installs Vue document editor and its dependent packages. The --save command instructs the NPM to include the document editor package inside the dependencies section of the package.json file.

npm install @syncfusion/ej2-vue-documenteditor --save

Step 3: Reference the theme-specific CSS files that you prefer for document editor component in the <script> section of the src/App.vue file. Here, we have referenced Material theme CSS files.

import '../node_modules/@syncfusion/ej2-base/styles/material.css';
import '../node_modules/@syncfusion/ej2-buttons/styles/material.css';
import '../node_modules/@syncfusion/ej2-inputs/styles/material.css';
import '../node_modules/@syncfusion/ej2-popups/styles/material.css';
import '../node_modules/@syncfusion/ej2-lists/styles/material.css';
import '../node_modules/@syncfusion/ej2-navigations/styles/material.css';
import '../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css';
import '../node_modules/@syncfusion/ej2-dropdowns/styles/material.css';
import "../node_modules/@syncfusion/ej2-vue-documenteditor/styles/material.css"

Step 4: In the src/App.vue file, register the Document Editor Container component like below:

import { DocumentEditorContainerComponent, Toolbar } from '@syncfusion/ej2-vue-documenteditor';
//Component registeration
  export default {
  name: "App",
  components: {
    'ejs-documenteditorcontainer' : DocumentEditorContainerComponent
  }
  }

Step 5: Add the Vue Document Editor Container by using <ejs-documenteditorcontainer> selector in <template> section of the src/App.vue file. In the src/App.vue file, declare the serviceUrl property. This service URL will be used for the document editor’s server-side dependent functionalities.

Then, the modified src/App.vue file will be like the following.

<template>
  <ejs-documenteditorcontainer :serviceUrl='serviceUrl' :enableToolbar='true' :height='600px'> </ejs-documenteditorcontainer>
</template>
<script>
  import { DocumentEditorContainerComponent, Toolbar } from '@syncfusion/ej2-vue-documenteditor';
  import '../node_modules/@syncfusion/ej2-base/styles/material.css';
  import '../node_modules/@syncfusion/ej2-buttons/styles/material.css';
  import '../node_modules/@syncfusion/ej2-inputs/styles/material.css';
  import '../node_modules/@syncfusion/ej2-popups/styles/material.css';
  import '../node_modules/@syncfusion/ej2-lists/styles/material.css';
  import '../node_modules/@syncfusion/ej2-navigations/styles/material.css';
  import '../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css';
  import '../node_modules/@syncfusion/ej2-dropdowns/styles/material.css';
  import "../node_modules/@syncfusion/ej2-vue-documenteditor/styles/material.css";
 
  //Component registeration
  export default {
name: 'App',
components: {
  // Declaring component
  'ejs-documenteditorcontainer' : DocumentEditorContainerComponent
},
data () {
  return {
    serviceUrl:'https://ej2services.syncfusion.com/production/web-services/api/documenteditor/'
  };
},
provide: {
  DocumentEditorContainer: [Toolbar]
}
  }
</script>

Then, execute the project using the npm run serve command in the terminal window. Now, you will see the browser opens with the Word Processor component.

Document Editor with Toolbar and Properties Pane

Document Editor with Toolbar and Properties Pane

In the previous output image, the Word Processor is added to the page without a title bar and doesn’t fit the full size of the browser window.

Add title bar for Word Processor

Step 1: Add the following div element as the first line of the src/App.vue file. Then, add the required styles in the <style> section of the  src/App.vue file.

<div id="default_title_bar" className="e-de-ctn-title"></div>

Step 2: Then, refer the title-bar changes from GitHub to add title bar.

Step 3: Now, install the following packages used in the src/App.vue title bar file.

npm install @syncfusion/ej2-vue-buttons -save
npm install @syncfusion/ej2-vue-splitbuttons -save
npm install @syncfusion/ej2-vue-navigations -save

Step 4: In the src/App.vue file, import the changes for title bar. Also, add the created and documentChange event handlers for the document editor component.

import {
  DocumentEditorContainerComponent,
  Toolbar,
} from '@syncfusion/ej2-vue-documenteditor';
import { DropDownButtonComponent } from '@syncfusion/ej2-vue-splitbuttons';
import { ButtonComponent } from '@syncfusion/ej2-vue-buttons';
import '../node_modules/@syncfusion/ej2-base/styles/material.css';
import '../node_modules/@syncfusion/ej2-buttons/styles/material.css';
import '../node_modules/@syncfusion/ej2-inputs/styles/material.css';
import '../node_modules/@syncfusion/ej2-popups/styles/material.css';
import '../node_modules/@syncfusion/ej2-lists/styles/material.css';
import '../node_modules/@syncfusion/ej2-navigations/styles/material.css';
import '../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css';
import '../node_modules/@syncfusion/ej2-dropdowns/styles/material.css';
import '../node_modules/@syncfusion/ej2-vue-documenteditor/styles/material.css';
import '../node_modules/@syncfusion/ej2-vue-buttons/styles/material.css';
import '../node_modules/@syncfusion/ej2-vue-splitbuttons/styles/material.css';
 
//Component registeration
export default {
  name: 'App',
  components: {
    // Declaring component
    'ejs-documenteditorcontainer': DocumentEditorContainerComponent,
    'ejs-button': ButtonComponent,
    'ejs-dropdownbutton': DropDownButtonComponent,
  },    data: function() {
        return {
          hostUrl : 'https://ej2services.syncfusion.com/production/web-services/',
          documentName : 'Getting Started',
          documentTitle: 'Untitled Document',
          iconStyle: 'float:right;background: transparent;box-shadow:none;border-color: transparent;border-radius: 2px;color:inherit;font-size:12px;text-transform:capitalize;margin-top:4px;height:28px;font-weight:400;font-family:inherit;',
            titileStyle: 'text-transform:capitalize;font-weight:400;font-family:inherit;text-overflow:ellipsis;white-space:pre;overflow:hidden;user-select:none;cursor:text',
            printIconCss: 'e-de-icon-Print e-de-padding-right',
            exportIconCss: 'e-de-icon-Download e-de-padding-right',
            exportItems: [
                { text: 'Microsoft Word (.docx)', id: 'word' },
                { text: 'Syncfusion Document Text (.sfdt)', id: 'sfdt' }
            ]
        };
    },  
    provide:{
        DocumentEditorContainer:[Toolbar]
    },
      methods: {
        onExport: function (args) {
            switch (args.item.id) {
                case 'word':
                    this.save('Docx');
                    break;
                case 'sfdt':
                    this.save('Sfdt');
                    break;
            }
        },
        openExportDropDown: function () {
            // tslint:disable-next-line:max-line-length
            document.getElementById('word').setAttribute('title', 'Download a copy of this document to your computer as a DOCX file.');
            // tslint:disable-next-line:max-line-length
            document.getElementById('sfdt').setAttribute('title', 'Download a copy of this document to your computer as an SFDT file.');
        },
        save: function (format) {
          debugger;
            // tslint:disable-next-line:max-line-length
             this.$refs.doceditcontainer.ej2Instances.documentEditor.save( this.$refs.doceditcontainer.ej2Instances.documentEditor.documentName == '' ? 'sample' :  this.$refs.doceditcontainer.ej2Instances.documentEditor.documentName, format);
        },
        openBtnClick: function () {
            this.$refs.uploadDocument.click();
        },
        printBtnClick: function () {
            this.$refs.doceditcontainer.ej2Instances.documentEditor.print();
        },
        titleBarKeydownEvent: function (e) {
            if (e.keyCode === 13) {
                e.preventDefault();
                document.getElementById("documenteditor_title_contentEditor").contentEditable = 'false';
                if (document.getElementById("documenteditor_title_contentEditor").textContent === '') {
                    document.getElementById("documenteditor_title_contentEditor").textContent = 'Document1';
                }
            }
        },
        titleBarBlurEvent: function (args) {
            if (document.getElementById("documenteditor_title_contentEditor").textContent === '') {
                document.getElementById("documenteditor_title_contentEditor").textContent = 'Document1';
            }
            document.getElementById("documenteditor_title_contentEditor").contentEditable = 'false';
            this.$refs.doceditcontainer.ej2Instances.documentEditor.documentName = document.getElementById("documenteditor_title_name").textContent;
        },
        titleBarClickEvent: function () {
            this.updateDocumentEditorTitle();
        },
        updateDocumentEditorTitle: function () {
            document.getElementById("documenteditor_title_contentEditor").contentEditable = 'true';
            document.getElementById("documenteditor_title_contentEditor").focus();
            window.getSelection().selectAllChildren(document.getElementById("documenteditor_title_contentEditor"));
        },
        documentChangedEvent: function () {
            var obj = this.$refs.doceditcontainer.ej2Instances.documentEditor;
            this.documentTitle = obj.documentName === '' ? 'Untitled Document' : obj.documentName;
            document.getElementById("documenteditor_title_name").textContent = obj.documentName ;
            setTimeout(() => { obj.scrollToPage(1); }, 10);
        }
    },
    mounted() {
        this.$nextTick(function () {
          this.$refs.doceditcontainer.ej2Instances.locale='en-US';
          var obj = this.$refs.doceditcontainer.ej2Instances.documentEditor;
          this.$refs.doceditcontainer.ej2Instances.serviceUrl = this.hostUrl + 'api/documenteditor/';
          this.$refs.doceditcontainer.ej2Instances.documentChange = () => {
                this.documentChangedEvent();
            };
       });
    }
});

Now, execute the project and you can see the browser opens with a title bar and document editor.

Document Editor Container with Title Bar

Document Editor Container with Title Bar

Fit Word Processor to browser window size

In the src/App.vue file, add logic to resize the document editor with respect to the window’s available size. Then, add an event listener for the browser window resize event.

Refer to the following code example.

onCreated : function () {
    setInterval(()=>{
      this.updateDocumentEditorSize();
    }, 100);
    //Adds event listener for browser window resize event.
    window.addEventListener("resize", this.onWindowResize);
  }
  onWindowResize= function () {    //Resizes the document editor component to fit full browser window automatically whenever the browser resized.
    this.updateDocumentEditorSize();
  }
  updateDocumentEditorSize : function () {
    //Resizes the document editor component to fit full browser window.
    var windowWidth = window.innerWidth;
    //Reducing the size of title bar, to fit Document editor component in remaining height.
    var windowHeight = window.innerHeight - this.getHeight();
    this.$refs.doceditcontainer.resize(windowWidth, windowHeight);
  }

Then, execute the project. Now, you can see the browser opens with a complete Word Processor including title bar, toolbar, properties pane and document editor in full window.

Word Document Editor Fit to Full WindowCaption

Word Document Editor Fit to Full Window

Open a template document in Word Processor

You can open an existing Word document as an initial template using created event.

In the src/app.tsx file, add the following code to get SFDT for the specified template file. Then, open it in the Vue Word Processor component. The file name specified should be one of the files copied to the Docker container.

openTemplate : function () { 
    var uploadDocument = new FormData();
    uploadDocument.append('DocumentName', 'Getting Started.docx');
    var loadDocumentUrl = this.$refs.doceditcontainer.ej2Instances.serviceUrl + 'LoadDocument';
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('POST', loadDocumentUrl, true);
    var dataContext = this;
    httpRequest.onreadystatechange = function () {
      if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200 || httpRequest.status === 304) {
          //Opens the SFDT for the specified file received from the web API.
          dataContext.$refs.doceditcontainer.ej2Instances.documentEditor.open(httpRequest.responseText);
        }
      }
    };
    //Sends the request with template file name to web API. 
    httpRequest.send(uploadDocument);
  }

Then, execute the project. Now, you can see the browser opens with a complete Word Processor loaded with a template document.

Document Editor Loaded with a Template Document

Document Editor Loaded with a Template Document

GitHub repository

For more information, refer to the complete working example to view and edit Word documents in Vue app.

Summary

Thank you for taking time to read this article. We have seen how to set up the Vue Word Processor and integrate the component into your application. With this, you can easily view and edit Word documents in your Vue app.

Also, take a moment to peruse the documentation, where you’ll find other features, all with accompanying code examples.

Are you already a Syncfusion user? Then, you can download the product setup here. If you’re not yet a Syncfusion user, you can download a free, 30-day trial here.

If you have any questions about these features, please let us know in the comments below. You can also contact us through our support forum, Direct-Trac, or feedback portal. We are happy to assist you!

Related Articles

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied