How to embed DOCX file in HTML in React DOCX Editor easily?
The easiest way to embed a DOCX file in HTML for viewing and editing is by using the Syncfusion® React DOCX Editor component. This dedicated UI component provides a rich, Word-like editing experience, enabling users to create, edit, view, and print Word documents (DOCX, WordML, DOC, RTF, TXT) directly within a web page, and can be easily integrated with server APIs to load and save documents.
This article provides a step-by-step guide to embed a DOCX file in HTML for viewing and editing using Syncfusion® React DOCX Editor.
Prerequisites
Before starting, ensure your development environment meets the following requirements:
- Node.js: Version 14.0.0 or above
- React: Version 15.5.4 or higher.
For detailed system requirements, refer to the documentation.
Step-by-step guide to embed a DOCX file in HTML
Step 1 : Create or use a React application
To embed a DOCX file in HTML for viewing and editing in your React application, you first need an existing application or create a new React application. Refer to the documentation to create a new React application.
Step 2 : Install the Syncfusion® DOCX Editor package
All the Syncfusion React component packages are available in npmjs.com public registry. To install the Document Editor component, use the following command
npm install @syncfusion/ej2-react-documenteditor --save
Step 3: Create the Initial HTML Page Layout
First, let’s create the simple “Adventure Works Cycles” HTML page. This is the “existing html page” before the editor is added.
- Update
src/App.tsxwith the following code for the page structure:
import React from 'react';
import './App.css';
function App() {
return (
<>
<header>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
</div>
<img src="/AdventureCycle.jpg" alt="Adventure Works Cycles Logo" className="logo">
</img>
</header>
<main>
<h2>Welcome to Our Site!</h2>
</main>
<footer>
© {new Date().getFullYear()} Adventure Works Cycles. All rights reserved.
</footer>
</>
);
}
export default App;
Note: Ensure your logo file AdventureCycle.jpg is in the public folder for this path to work.
- Replace the content of
src/App.csswith these minimal styles for the layout:
header {
display: flex;
align-items: center;
justify-content: center;
background: #f2f2f2;
padding: 12px 24px;
border-bottom: 1px solid #ddd;
}
.logo {
height: 134px;
width: auto;
margin-bottom: 8px;
align-items: center;
}
h1 {
font-size: 2rem;
font-weight: bold;
margin: 0;
color: #333;
text-align: center;
}
main {
padding: 24px;
}
h2 {
margin: 0 0 16px;
font-size: 1.5rem;
color: #444;
display: flex;
align-items: center;
justify-content: center;
}
.editor-box {
margin-top: 16px;
}
footer {
padding: 16px;
text-align: center;
color: #666;
border-top: 1px solid #ddd;
font-size: 0.9rem;
}
The web page currently looks like this:
Step 4: Set up the backend Web API for Document Processing
As the Syncfusion® DOCX editor client-side script requires the document in SFDT file format, you can convert the Word documents (.dotx, .docx, .doc), rich text format documents (.rtf), and text documents (.txt) into SFDT format by using this Web API.
Create an ASP.NET Core Web API with the following example code for importing Word documents into Document Editor component.
[AcceptVerbs("Post")]
[HttpPost]
[EnableCors("AllowAllOrigins")]
[Route("Import")]
public string Import(IFormCollection data)
{
if (data.Files.Count == 0)
return null;
Stream stream = new MemoryStream();
IFormFile file = data.Files[0];
int index = file.FileName.LastIndexOf('.');
string type = index > -1 && index < file.FileName.Length - 1 ?
file.FileName.Substring(index) : ".docx";
file.CopyTo(stream);
stream.Position = 0;
//Hooks MetafileImageParsed event.
WordDocument.MetafileImageParsed += OnMetafileImageParsed;
WordDocument document = WordDocument.Load(stream, GetFormatType(type.ToLower()));
//Unhooks MetafileImageParsed event.
WordDocument.MetafileImageParsed -= OnMetafileImageParsed;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);
document.Dispose();
return json;
}
Refer and reuse the GitHub Web Service example or Docker image for hosting your own web service and use it for the serviceUrl property.
Step 5 : Integrate the DOCX Editor into the HTML Page
- Now, let’s modify the HTML page to include the Syncfusion® DOCX Editor.
- Update
src/App.tsxwith the following code for the DOCX Editor to integrate with page structure:
import React, { useEffect, useRef } from 'react';
import './App.css';
import { DocumentEditorContainerComponent, Ribbon } from '@syncfusion/ej2-react-documenteditor';
DocumentEditorContainerComponent.Inject(Ribbon);
function App() {
const containerRef = useRef<DocumentEditorContainerComponent | null>(null);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const form = new FormData();
form.append('DocumentName', 'Getting Started.docx');
const url = container.serviceUrl + 'LoadDocument';
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
container.documentEditor?.open(xhr.responseText);
}
};
xhr.send(form);
}, []);
return (
<>
<header>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
</div>
<img src="/AdventureCycle.jpg" alt="Adventure Works Cycles Logo" className="logo">
</img>
</header>
<main>
<h2>Welcome to Our Site!</h2>
<div className="editor-box">
<DocumentEditorContainerComponent
id="doc-editor"
ref={containerRef}
height={'90vh'}
serviceUrl="http://localhost:62869/api/documenteditor/"
toolbarMode="Ribbon"
/>
</div>
</main>
<footer>
© {new Date().getFullYear()} Adventure Works Cycles. All rights reserved.
</footer>
</>
);
}
export default App;
- Open
src/App.cssand add the following lines at the top:
@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-documenteditor/styles/material.css";
@import "../node_modules/@syncfusion/ej2-ribbon/styles/material.css";
Step 6 : Add the license key
From v20.1.047 onwards, it is necessary to register a license key for Syncfusion® React components. For more information on obtaining and registering your license key, please refer to the documentation.
Step 7: Run the application
To see the Syncfusion® DOCX Editor in action with a functioning backend, ensure your Web API service is running, then run your React application.
- Start your Web API service
- Run your React application: Open your terminal in the React project directory and run:
npm start
Once the application starts, your browser will automatically open at http://localhost:3000, displaying the DOCX Editor embedded in your web page, with the default document loaded and ready for editing.
Editing and Formatting the Document
Once a document is loaded, the editor provides a rich, MS Word-like interface for comprehensive editing and formatting.
- Text Formatting: Apply styles such as bold, italic, and change font family, size, color, and highlight.
You can download a complete working sample of embedding a DOCX file in HTML for viewing and editing in React from GitHub.
Conclusion
I hope you enjoyed learning about what’s the easiest way to embed a DOCX file in HTML for viewing and editing.
You can refer to our React DOCX Editor feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React DOCX Editor example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!