Certainly! Below is a comprehensive HTML website that includes JavaScript and CSS to create Word files. The website features:
- Styler Panel: Allows users to add and modify predefined styles.
- Input Editor: A rich text editor where users can input and format their content.
- Preview Section: Displays a live preview of the formatted content.
- Export Button: Enables users to download the content as a
.docx Word file.
The implementation uses the docx library to handle Word file generation. We'll include it via a CDN for simplicity.
Complete HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word File Creator</title>
<!-- Include docx library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/docx/7.3.0/docx.min.js" integrity="sha512-jTR0kPq/cn061pMZhkg0eCQ18hkx94vBSkveA0aghzHbjPEN4QrTOpd4WEdmCDFwZBvh6NrFmsu4UAou4TeZ6A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
height: 100vh;
}
.sidebar {
width: 250px;
background-color: #f4f4f4;
padding: 20px;
box-sizing: border-box;
border-right: 1px solid #ccc;
overflow-y: auto;
}
.content {
flex: 1;
display: flex;
flex-direction: column;
}
.editor-container, .preview-container {
flex: 1;
padding: 20px;
box-sizing: border-box;
overflow-y: auto;
}
.editor-container textarea {
width: 100%;
height: 100%;
resize: none;
padding: 10px;
box-sizing: border-box;
font-size: 16px;
}
.preview-container {
border-top: 1px solid #ccc;
}
h2 {
margin-top: 0;
}
.style-item {
margin-bottom: 10px;
}
.style-item input, .style-item select {
width: 100%;
padding: 5px;
margin-top: 5px;
box-sizing: border-box;
}
.buttons {
margin-top: 20px;
}
.buttons button {
width: 100%;
padding: 10px;
margin-bottom: 10px;
font-size: 16px;
cursor: pointer;
}
/* Preview Styles */
#preview {
border: 1px solid #ddd;
padding: 20px;
height: 100%;
overflow-y: auto;
background-color: #fff;
}
</style>
</head>
<body>
<div class="sidebar">
<h2>Styler</h2>
<div id="styles">
<!-- Predefined styles will be here -->
</div>
<div class="buttons">
<button id="add-style">Add New Style</button>
<button id="export-word">Export to Word</button>
</div>
</div>
<div class="content">
<div class="editor-container">
<h2>Input Editor</h2>
<div contenteditable="true" id="editor" style="border:1px solid #ccc; padding:10px; height: 100%; overflow-y: auto;">
<p>Start writing your content here...</p>
</div>
</div>
<div class="preview-container">
<h2>Preview</h2>
<div id="preview">
<p>Start writing your content here...</p>
</div>
</div>
</div>
<script>
// Initialize styles
let styles = [
{ name: 'Heading 1', tag: 'h1', style: 'color: #2e6da4; font-size: 24px;' },
{ name: 'Heading 2', tag: 'h2', style: 'color: #2e6da4; font-size: 20px;' },
{ name: 'Paragraph', tag: 'p', style: 'color: #333; font-size: 16px;' }
];
const stylesContainer = document.getElementById('styles');
// Function to render styles
function renderStyles() {
stylesContainer.innerHTML = '';
styles.forEach((style, index) => {
const div = document.createElement('div');
div.className = 'style-item';
div.innerHTML = `
<label>Style Name:</label>
<input type="text" value="${style.name}" data-index="${index}" class="style-name"/>
<label>HTML Tag:</label>
<select data-index="${index}" class="style-tag">
<option value="p" ${style.tag === 'p' ? 'selected' : ''}>Paragraph (p)</option>
<option value="h1" ${style.tag === 'h1' ? 'selected' : ''}>Heading 1 (h1)</option>
<option value="h2" ${style.tag === 'h2' ? 'selected' : ''}>Heading 2 (h2)</option>
<option value="h3" ${style.tag === 'h3' ? 'selected' : ''}>Heading 3 (h3)</option>
<option value="span" ${style.tag === 'span' ? 'selected' : ''}>Span</option>
</select>
<label>CSS Style:</label>
<input type="text" value="${style.style}" data-index="${index}" class="style-css"/>
`;
stylesContainer.appendChild(div);
});
}
renderStyles();
// Event delegation for style inputs
stylesContainer.addEventListener('input', function(e) {
if (e.target.classList.contains('style-name')) {
const index = e.target.getAttribute('data-index');
styles[index].name = e.target.value;
updateEditorAndPreview();
}
if (e.target.classList.contains('style-tag')) {
const index = e.target.getAttribute('data-index');
styles[index].tag = e.target.value;
updateEditorAndPreview();
}
if (e.target.classList.contains('style-css')) {
const index = e.target.getAttribute('data-index');
styles[index].style = e.target.value;
updateEditorAndPreview();
}
});
// Add new style
document.getElementById('add-style').addEventListener('click', function() {
styles.push({ name: 'New Style', tag: 'p', style: 'color: #000; font-size: 16px;' });
renderStyles();
});
// Editor and Preview Synchronization
const editor = document.getElementById('editor');
const preview = document.getElementById('preview');
function applyStyles(content) {
let styledContent = content;
styles.forEach(style => {
// Simple regex to replace based on tag
const regex = new RegExp(`<${style.tag}>(.*?)<\/${style.tag}>`, 'gi');
styledContent = styledContent.replace(regex, `<${style.tag} style="${style.style}">$1</${style.tag}>`);
});
return styledContent;
}
function updateEditorAndPreview() {
const content = editor.innerHTML;
const styled = applyStyles(content);
preview.innerHTML = styled;
}
editor.addEventListener('input', updateEditorAndPreview);
// Initial update
updateEditorAndPreview();
// Export to Word
document.getElementById('export-word').addEventListener('click', function() {
const { Document, Packer, Paragraph, TextRun } = docx;
// Function to parse HTML and convert to docx elements
function parseHTML(html) {
const div = document.createElement('div');
div.innerHTML = html;
const elements = [];
div.childNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
let paragraph;
const text = node.textContent;
const style = styles.find(s => s.tag.toLowerCase() === node.tagName.toLowerCase());
const textRun = new TextRun({
text: text,
color: style ? style.style.match(/color:\s*([^;]+)/i)[1] : '000000',
size: style ? parseInt(style.style.match(/font-size:\s*(\d+)px/i)?.[1] || 16) * 2 : 32
});
paragraph = new Paragraph({
children: [textRun],
heading: style && style.tag.toLowerCase().startsWith('h') ? style.tag.toLowerCase() : undefined
});
elements.push(paragraph);
} else if (node.nodeType === Node.TEXT_NODE) {
const textRun = new TextRun({
text: node.textContent,
size: 32
});
const paragraph = new Paragraph({
children: [textRun]
});
elements.push(paragraph);
}
});
return elements;
}
const doc = new Document({
sections: [{
properties: {},
children: parseHTML(preview.innerHTML)
}]
});
Packer.toBlob(doc).then(blob => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'document.docx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
});
</script>
</body>
</html>
Features Breakdown
-
Styler Panel:
- Displays predefined styles (e.g., Heading 1, Heading 2, Paragraph).
- Allows users to add new styles by specifying:
- Style Name: A descriptive name for the style.
- HTML Tag: The HTML tag associated with the style (e.g.,
p, h1).
- CSS Style: Inline CSS styles (e.g.,
color: red; font-size: 18px;).
- Any changes in the styles update both the editor and the preview in real-time.
-
Input Editor:
- A
contenteditable div serves as a rich text editor.
- Users can input and format text using standard browser editing capabilities.
- As users edit the content, the preview updates automatically.
-
Preview Section:
- Reflects the formatted content based on the defined styles.
- Applies inline styles as specified in the styler panel.
-
Export to Word:
- Utilizes the
docx library to generate a .docx file.
- Parses the HTML content from the preview and converts it into Word document elements.
- Offers a download link for the generated Word file.
Usage Instructions
-
Styling Content:
- In the Styler panel on the left, you can modify existing styles or add new ones by clicking the "Add New Style" button.
- Each style requires:
- Style Name: For your reference.
- HTML Tag: Determines how the text is structured (e.g., paragraphs, headings).
- CSS Style: Defines the appearance (e.g., color, font-size).
-
Editing Content:
- In the Input Editor, type your content. Use the HTML tags defined in the styles to format your text.
- For example, to create a Heading 1, you can select the text and apply the
h1 tag if supported by your editor, or manually write it if implementing additional editor controls.
-
Previewing Content:
- The Preview section shows how your document will look with the applied styles.
- Any changes in the styler or the editor will reflect here instantly.
-
Exporting to Word:
- Once satisfied with the content and styling, click the "Export to Word" button.
- A
.docx file named document.docx will be downloaded, containing your formatted content.
Notes and Improvements
-
Rich Text Options: For a more advanced editor with toolbar options (bold, italic, etc.), consider integrating a rich text editor library like Quill or TinyMCE.
-
Style Application: Currently, styles are applied based on the HTML tags used. For a more dynamic application of styles (e.g., adding classes), additional JavaScript would be required.
-
Error Handling: The current implementation assumes correct CSS input. Adding validation for CSS properties can enhance robustness.
-
Advanced Word Features: The docx library allows for more complex document structures and styling. Explore its documentation to add features like tables, images, headers, footers, etc.
This setup provides a foundational structure for creating and styling Word documents through a web interface. You can further extend and refine it based on specific requirements and use cases.