Below is a complete HTML, CSS, and JavaScript code for a website that allows users to create and export Word files. The website includes:
- Styler Panel: Users can select and customize predefined styles (e.g., Heading, Paragraph).
- Input Area: A rich text editor where users can input and format their text.
- Preview Area: A live preview of the formatted content.
- Export Functionality: Users can export their content as a Word (
.doc) file.
The export feature uses a simple approach by embedding the HTML content into a .doc file, which Microsoft Word can interpret and render correctly.
Complete Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Word File Creator</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
height: 100vh;
}
/* Sidebar Styling */
.sidebar {
width: 250px;
background-color: #f4f4f4;
padding: 20px;
box-sizing: border-box;
border-right: 1px solid #ddd;
overflow-y: auto;
}
.sidebar h2 {
margin-top: 0;
}
.style-group {
margin-bottom: 20px;
}
.style-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.style-group input, .style-group select {
width: 100%;
padding: 5px;
margin-bottom: 10px;
box-sizing: border-box;
}
.style-group button {
width: 100%;
padding: 5px;
background-color: #4285f4;
color: white;
border: none;
cursor: pointer;
}
.style-group button:hover {
background-color: #306acb;
}
/* Main Content Styling */
.main {
flex: 1;
display: flex;
flex-direction: column;
}
.toolbar {
padding: 10px;
background-color: #eee;
border-bottom: 1px solid #ddd;
}
.toolbar button {
padding: 8px 12px;
margin-right: 5px;
border: none;
background-color: #4285f4;
color: white;
cursor: pointer;
border-radius: 4px;
}
.toolbar button:hover {
background-color: #306acb;
}
.editor-preview {
display: flex;
flex: 1;
overflow: hidden;
}
.editor, .preview {
width: 50%;
padding: 20px;
box-sizing: border-box;
overflow-y: auto;
}
.editor {
border-right: 1px solid #ddd;
}
.editor[contenteditable="true"] {
min-height: 100%;
}
.preview {
background-color: #fff;
}
/* Export Button */
.export-btn {
padding: 10px 20px;
margin: 10px;
background-color: #34a853;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
align-self: flex-end;
}
.export-btn:hover {
background-color: #2c8e46;
}
</style>
</head>
<body>
<div class="sidebar">
<h2>Styler</h2>
<div class="style-group">
<label for="style-name">Style Name:</label>
<input type="text" id="style-name" placeholder="e.g., Heading 1">
<label for="style-type">Style Type:</label>
<select id="style-type">
<option value="h1">Heading 1</option>
<option value="h2">Heading 2</option>
<option value="h3">Heading 3</option>
<option value="p">Paragraph</option>
</select>
<label for="style-color">Text Color:</label>
<input type="color" id="style-color" value="#000000">
<label for="style-font-size">Font Size:</label>
<input type="number" id="style-font-size" value="16" min="8" max="72">
<button id="add-style">Add/Update Style</button>
</div>
<div class="style-group">
<label for="apply-style">Apply Style:</label>
<select id="apply-style">
<option value="">--Select Style--</option>
</select>
<button id="apply-selected-style">Apply</button>
</div>
</div>
<div class="main">
<div class="toolbar">
<button onclick="execCmd('bold')"><b>Bold</b></button>
<button onclick="execCmd('italic')"><i>Italic</i></button>
<button onclick="execCmd('underline')"><u>Underline</u></button>
<button onclick="execCmd('insertOrderedList')">OL</button>
<button onclick="execCmd('insertUnorderedList')">UL</button>
</div>
<div class="editor-preview">
<div class="editor" id="editor" contenteditable="true">
<p>Start typing your content here...</p>
</div>
<div class="preview" id="preview">
<p>Start typing your content here...</p>
</div>
</div>
<button class="export-btn" onclick="exportToWord()">Export as Word</button>
</div>
<script>
// Function to execute document commands for formatting
function execCmd(command) {
document.execCommand(command, false, null);
updatePreview();
}
// Update the preview area with the editor's content
function updatePreview() {
const editorContent = document.getElementById('editor').innerHTML;
document.getElementById('preview').innerHTML = editorContent;
}
// Event listener to update preview on input
document.getElementById('editor').addEventListener('input', updatePreview);
// Styling functionality
const styles = {};
document.getElementById('add-style').addEventListener('click', () => {
const styleName = document.getElementById('style-name').value.trim();
const styleType = document.getElementById('style-type').value;
const styleColor = document.getElementById('style-color').value;
const styleFontSize = document.getElementById('style-font-size').value;
if (styleName === '') {
alert('Please enter a style name.');
return;
}
// Save the style
styles[styleName] = {
type: styleType,
color: styleColor,
fontSize: styleFontSize
};
// Update the apply-style dropdown
updateStyleDropdown();
alert('Style added/updated successfully!');
});
function updateStyleDropdown() {
const applyStyleSelect = document.getElementById('apply-style');
// Clear existing options except the first
applyStyleSelect.options.length = 1;
for (const styleName in styles) {
const option = document.createElement('option');
option.value = styleName;
option.textContent = styleName;
applyStyleSelect.appendChild(option);
}
}
document.getElementById('apply-selected-style').addEventListener('click', () => {
const selectedStyle = document.getElementById('apply-style').value;
if (selectedStyle === '') {
alert('Please select a style to apply.');
return;
}
const style = styles[selectedStyle];
if (style) {
// Apply the style by wrapping the selected text with the appropriate tag and styles
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const span = document.createElement(style.type);
span.style.color = style.color;
span.style.fontSize = style.fontSize + 'px';
span.appendChild(range.extractContents());
range.insertNode(span);
}
updatePreview();
}
});
// Export to Word functionality
function exportToWord() {
const htmlContent = document.getElementById('editor').innerHTML;
const preHtml = `
<html xmlns:o='urn:schemas-microsoft-com:office:office'
xmlns:w='urn:schemas-microsoft-com:office:word'
xmlns='http://www.w3.org/TR/REC-html40'>
<head>
<meta charset='utf-8'>
<title>Exported Document</title>
<style>
body { font-family: Arial, sans-serif; }
</style>
</head>
<body>
`;
const postHtml = "</body></html>";
const fullHtml = preHtml + htmlContent + postHtml;
const blob = new Blob(['\ufeff', fullHtml], {
type: 'application/msword'
});
// Specify filename
const filename = 'document.doc';
// Create download link
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
// Trigger download
document.body.appendChild(link);
link.click();
// Clean up
document.body.removeChild(link);
}
// Initialize preview on page load
window.onload = updatePreview;
</script>
</body>
</html>
Explanation of the Code
-
Layout Structure:
- The webpage is divided into two main sections:
- Sidebar (
.sidebar): Contains the Styler panel where users can add or modify predefined styles and apply them to the text.
- Main Content (
.main): Contains the formatting toolbar, the editor and preview areas side by side, and the export button.
-
Styler Panel:
- Add/Update Style:
- Users can define a new style by specifying:
- Style Name: A unique name for the style (e.g., "Heading 1").
- Style Type: HTML tags like
h1, h2, h3, or p.
- Text Color: Choose the color using a color picker.
- Font Size: Define the font size in pixels.
- Upon clicking the "Add/Update Style" button, the style is saved in the
styles object and the "Apply Style" dropdown is updated with the new style.
- Apply Style:
- Users can select a predefined style from the dropdown and apply it to the selected text in the editor by clicking the "Apply" button.
- The script wraps the selected text with the chosen HTML tag and applies the specified styles (color and font size).
-
Editor and Preview:
- The Editor is a
div with contenteditable="true", allowing users to input and format text directly.
- The Preview area mirrors the content of the editor in real-time, showing how the formatted text will appear.
- A simple JavaScript function
updatePreview() updates the preview whenever there's an input event in the editor.
-
Formatting Toolbar:
- Provides buttons for common text formatting actions such as Bold, Italic, Underline, Ordered List, and Unordered List.
- Clicking these buttons triggers the
execCmd function, which uses document.execCommand to apply the respective formatting to the selected text.
-
Export to Word:
- The "Export as Word" button triggers the function.
How to Use the Website
-
Adding a New Style:
- In the Styler panel on the left, enter a Style Name (e.g., "Heading 1").
- Select the Style Type corresponding to the HTML tag you want (e.g.,
h1 for Heading 1).
- Choose a Text Color using the color picker.
- Set the Font Size in pixels.
- Click the Add/Update Style button to save the style.
-
Applying a Style:
- Select the text in the Editor that you want to style.
- In the Styler panel, choose the desired style from the Apply Style dropdown.
- Click the Apply button to apply the style to the selected text.
-
Formatting Text:
- Use the buttons in the toolbar (Bold, Italic, Underline, OL, UL) to format your text as needed.
-
Previewing Content:
- As you edit and format your text in the Editor, the Preview area on the right updates in real-time to show how the content will appear.
-
Exporting to Word:
- Once you've finished editing and styling your document, click the Export as Word button at the bottom of the main content area.
- A
.doc file named document.doc will be downloaded to your computer.
- You can open this file in Microsoft Word to view and further edit your formatted document.
Notes
-
Browser Compatibility: The document.execCommand method used for formatting is widely supported but has been deprecated in some browsers. However, it still functions in most modern browsers. For more advanced and future-proof text editing features, consider integrating rich-text editor libraries like Quill, TinyMCE, or CKEditor.
-
Export Functionality: The export method provided creates a .doc file by embedding HTML content. This method is simple and effective for basic formatting. For more complex documents or better fidelity, you might want to explore libraries like docx.js or Pizzip combined with Docxtemplater, which provide more comprehensive Word document generation capabilities.
-
Security Considerations: Since the editor allows users to input HTML content, ensure that appropriate sanitization is done if integrating this tool into a larger application to prevent XSS attacks or other security vulnerabilities.
Feel free to customize and enhance this website further to suit your specific requirements!