Generate a advacned html website including js that is able to create word files. It…
- User
Generate a advacned html website including js that is able to create word files. It should have style tags that are configurable and it should be able to add more. The main part is a text field that can be edited with the text (including the sytle tags) that will represent the output The word file should be generated by using a button.
Heres an example of the frameworks you should use: import { Document, Packer } from "docx"; import { saveAs } from "file-saver";
// Listen for clicks on Generate Word Document button document.getElementById("generate").addEventListener( "click", function(event) { generateWordDocument(event); }, false );
function generateWordDocument(event) { event.preventDefault(); // Create a new instance of Document for the docx module let doc = new Document(); doc.theme = { font: { normal: { family: "Calibri", color: "303856" }, header: { family: "Calibri Light" } }, title: { color: "4ABDAC" }, headings: { one: { color: "FC4A1A" }, two: { color: "F7B733" } } }; doc.Styles.createParagraphStyle("customHeading1", "Custom Heading 1") .basedOn("Heading 1") .next("Normal") .quickFormat() .font(doc.theme.font.header.family) .size(32) .bold() .color(doc.theme.headings.one.color) .spacing({ after: 250 }); doc.Styles.createParagraphStyle("customHeading2", "Custom Heading 2") .basedOn("Heading 2") .next("Normal") .quickFormat() .font(doc.theme.font.header.family) .size(26) .bold() .color(doc.theme.headings.two.color) .spacing({ after: 150 }); doc.Styles.createParagraphStyle("customTitle", "Custom Title") .basedOn("Title") .next("Normal") .quickFormat() .font(doc.theme.font.header.family) .size(56) .bold() .color(doc.theme.font.normal.color) .spacing({ after: 250 }); doc.Styles.createParagraphStyle("customSubtitle", "Custom Subtitle") .basedOn("Subtitle") .next("Normal") .quickFormat() .font(doc.theme.font.header.family) .size(22) .color(doc.theme.font.normal.color) .spacing({ after: 150 }); doc.Styles.createParagraphStyle("customNormal", "Custom Normal") .basedOn("Normal") .quickFormat() .font(doc.theme.font.normal.family) .size(20) .color(doc.theme.font.normal.color) .spacing({ after: 150 }); doc.createParagraph("Title").style("customTitle"); doc.createParagraph("Subtitle").style("customSubtitle"); doc.createParagraph("Heading 1").style("customHeading1"); doc.createParagraph("Heading 2").style("customHeading2"); doc .createParagraph( "Aliquam gravida quam sapien, quis dapibus eros malesuada vel. Praesent tempor aliquam iaculis. Nam ut neque ex. Curabitur pretium laoreet nunc, ut ornare augue aliquet sed. Pellentesque laoreet sem risus. Cras sodales libero convallis, convallis ex sed, ultrices neque. Sed quis ullamcorper mi. Ut a leo consectetur, scelerisque nibh sit amet, egestas mauris. Donec augue sapien, vestibulum in urna et, cursus feugiat enim. Ut sit amet placerat quam, id tincidunt nulla. Cras et lorem nibh. Suspendisse posuere orci nec ligula mattis vestibulum. Suspendisse in vestibulum urna, non imperdiet enim. Vestibulum vel dolor eget neque iaculis ultrices." ) .style("customNormal"); // Call saveDocumentToFile with the document instance and a filename saveDocumentToFile(doc, "New Document.docx"); }
function saveDocumentToFile(doc, fileName) { // Create new instance of Packer for the docx module const packer = new Packer(); // Create a mime type that will associate the new file with Microsoft Word const mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; // Create a Blob containing the Document instance and the mimeType packer.toBlob(doc).then(blob => { const docblob = blob.slice(0, blob.size, mimeType); // Save the file using saveAs from the file-saver package saveAs(docblob, fileName); }); }
- Assistant
Sure! Below is a comprehensive example of an advanced HTML website that allows users to create and download Word documents with configurable styles. This implementation leverages the
docxandFileSaver.jslibraries via CDN links to enable client-side Word document generation and downloading.Features:
- Editable Text Area: Users can input and edit text, including applying predefined styles.
- Style Configuration Panel: Users can configure existing styles and add new custom styles.
- Generate Word Document: A button that triggers the creation and download of the Word document based on the input text and styles.
Dependencies:
- docx: For creating Word documents.
- FileSaver.js: For saving the generated document to the user's device.
- Bootstrap: For styling and layout (optional but recommended for better aesthetics).
Complete Implementation:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Advanced Word Document Generator</title> <!-- Bootstrap CSS for styling (Optional) --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" /> <style> body { padding: 20px; } .style-config { margin-bottom: 20px; } .editor { border: 1px solid #ced4da; padding: 10px; min-height: 200px; border-radius: 5px; background-color: #f8f9fa; } .style-list { max-height: 300px; overflow-y: auto; } </style> </head> <body> <div class="container"> <h1 class="mb-4">Advanced Word Document Generator</h1> <!-- Style Configuration Panel --> <div class="style-config card mb-4"> <div class="card-header"> <h5>Configure Styles</h5> </div> <div class="card-body"> <form id="styleForm"> <div class="form-row"> <div class="form-group col-md-3"> <label for="styleName">Style Name</label> <input type="text" class="form-control" id="styleName" placeholder="e.g., customHeading1" required> </div> <div class="form-group col-md-3"> <label for="baseStyle">Base Style</label> <select class="form-control" id="baseStyle" required> <option>Normal</option> <option>Heading1</option> <option>Heading2</option> <option>Title</option> <option>Subtitle</option> </select> </div> <div class="form-group col-md-2"> <label for="fontFamily">Font Family</label> <input type="text" class="form-control" id="fontFamily" placeholder="e.g., Calibri" required> </div> <div class="form-group col-md-2"> <label for="fontSize">Font Size (pt)</label> <input type="number" class="form-control" id="fontSize" placeholder="e.g., 24" required> </div> <div class="form-group col-md-1"> <label for="bold">Bold</label> <input type="checkbox" class="form-control" id="bold"> </div> <div class="form-group col-md-1"> <label for="italic">Italic</label> <input type="checkbox" class="form-control" id="italic"> </div> </div> <button type="submit" class="btn btn-primary">Add Style</button> </form> <hr> <h5>Existing Styles</h5> <ul class="list-group style-list" id="styleList"> <!-- Dynamically populated --> </ul> </div> </div> <!-- Text Editor --> <div class="card mb-4"> <div class="card-header"> <h5>Document Content</h5> </div> <div class="card-body"> <div id="textEditor" class="editor" contenteditable="true"> <p style="font-family: Calibri; font-size: 24pt;">Start writing your document here...</p> </div> </div> </div> <!-- Generate Button --> <button id="generate" class="btn btn-success btn-lg">Generate Word Document</button> </div> <!-- Dependencies --> <script src="https://cdnjs.cloudflare.com/ajax/libs/docx/7.8.1/docx.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script> <!-- Optional Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js" ></script> <script> // Initial Styles Configuration const stylesConfig = { Title: { fontFamily: "Calibri", fontSize: 56, bold: true, color: "4ABDAC", }, Subtitle: { fontFamily: "Calibri", fontSize: 22, bold: false, italic: false, color: "303856", }, Heading1: { fontFamily: "Calibri Light", fontSize: 32, bold: true, color: "FC4A1A", }, Heading2: { fontFamily: "Calibri Light", fontSize: 26, bold: true, color: "F7B733", }, Normal: { fontFamily: "Calibri", fontSize: 20, bold: false, color: "303856", }, }; // Function to render the styles list function renderStylesList() { const styleList = document.getElementById("styleList"); styleList.innerHTML = ""; for (const [name, config] of Object.entries(stylesConfig)) { const listItem = document.createElement("li"); listItem.className = "list-group-item d-flex justify-content-between align-items-center"; listItem.textContent = name; const badge = document.createElement("span"); badge.className = "badge badge-primary badge-pill"; badge.textContent = `Font: ${config.fontFamily}, Size: ${config.fontSize}pt`; listItem.appendChild(badge); styleList.appendChild(listItem); } } // Initial render renderStylesList(); // Handle Style Form Submission document.getElementById("styleForm").addEventListener("submit", function(event) { event.preventDefault(); const styleName = document.getElementById("styleName").value.trim(); const baseStyle = document.getElementById("baseStyle").value; const fontFamily = document.getElementById("fontFamily").value.trim(); const fontSize = parseInt(document.getElementById("fontSize").value); const bold = document.getElementById("bold").checked; const italic = document.getElementById("italic").checked; if (styleName in stylesConfig) { alert("Style name already exists!"); return; } stylesConfig[styleName] = { baseStyle, fontFamily, fontSize, bold, italic, }; renderStylesList(); document.getElementById("styleForm").reset(); }); // Function to parse the editable content and extract styled paragraphs function parseContent() { const editor = document.getElementById("textEditor"); const paragraphs = editor.querySelectorAll("p"); const docParagraphs = []; paragraphs.forEach(p => { let style = "Normal"; // Default style // In this example, we'll determine style based on font size const fontSize = p.style.fontSize ? parseInt(p.style.fontSize) : 20; for (const [name, config] of Object.entries(stylesConfig)) { if (config.fontSize === fontSize) { style = name; break; } } // Create a docx Paragraph with the appropriate style const docParagraph = new docx.Paragraph({ text: p.innerText, style: style, }); docParagraphs.push(docParagraph); }); return docParagraphs; } // Handle Generate Button Click document.getElementById("generate").addEventListener("click", function(event) { event.preventDefault(); generateWordDocument(); }); function generateWordDocument() { const { Document, Packer, Paragraph, TextRun } = docx; // Create a new Document const doc = new Document(); // Define Theme and Styles doc.Styles.createParagraphStyle("Title", "Custom Title") .basedOn("Title") .next("Normal") .quickFormat() .font(stylesConfig.Title.fontFamily) .size(stylesConfig.Title.fontSize * 2) // docx uses half-points .bold(stylesConfig.Title.bold) .color(stylesConfig.Title.color) .spacing({ after: 250 }); doc.Styles.createParagraphStyle("Subtitle", "Custom Subtitle") .basedOn("Subtitle") .next("Normal") .quickFormat() .font(stylesConfig.Subtitle.fontFamily) .size(stylesConfig.Subtitle.fontSize * 2) .bold(stylesConfig.Subtitle.bold) .italics(stylesConfig.Subtitle.italic || false) .color(stylesConfig.Subtitle.color) .spacing({ after: 150 }); doc.Styles.createParagraphStyle("Heading1", "Custom Heading 1") .basedOn("Heading1") .next("Normal") .quickFormat() .font(stylesConfig.Heading1.fontFamily) .size(stylesConfig.Heading1.fontSize * 2) .bold(stylesConfig.Heading1.bold) .color(stylesConfig.Heading1.color) .spacing({ after: 250 }); doc.Styles.createParagraphStyle("Heading2", "Custom Heading 2") .basedOn("Heading2") .next("Normal") .quickFormat() .font(stylesConfig.Heading2.fontFamily) .size(stylesConfig.Heading2.fontSize * 2) .bold(stylesConfig.Heading2.bold) .color(stylesConfig.Heading2.color) .spacing({ after: 150 }); doc.Styles.createParagraphStyle("Normal", "Custom Normal") .basedOn("Normal") .quickFormat() .font(stylesConfig.Normal.fontFamily) .size(stylesConfig.Normal.fontSize * 2) .bold(stylesConfig.Normal.bold) .italics(stylesConfig.Normal.italic || false) .color(stylesConfig.Normal.color) .spacing({ after: 150 }); // Add any custom styles defined by the user for (const [name, config] of Object.entries(stylesConfig)) { if (["Title", "Subtitle", "Heading1", "Heading2", "Normal"].includes(name)) { continue; // Skip predefined styles } doc.Styles.createParagraphStyle(name, name) .basedOn(config.baseStyle) .next("Normal") .quickFormat() .font(config.fontFamily) .size(config.fontSize * 2) .bold(config.bold) .italics(config.italic || false) .spacing({ after: 150 }); } // Parse the content from the editor const contentParagraphs = parseContent(); // Add paragraphs to the document contentParagraphs.forEach(p => doc.addSection({ properties: {}, children: [p], })); // Pack and save the document Packer.toBlob(doc).then(blob => { saveAs(blob, "GeneratedDocument.docx"); console.log("Document created successfully"); }); } </script> </body> </html>Explanation of the Implementation:
-
HTML Structure:
- Style Configuration Panel: Allows users to define new styles by specifying the style name, base style, font family, font size, and whether the text is bold or italic.
- Existing Styles List: Displays a list of all currently defined styles.
- Text Editor: A
contenteditablediv where users can input and format their text. For simplicity, this example assumes that styles are determined based on font size, but you can enhance it to recognize more complex style indicators. - Generate Button: Triggers the Word document generation process.
-
Styling:
- Utilizes Bootstrap for responsive design and better aesthetics.
- Custom CSS is added to style the editor and the style list.
-
JavaScript Functionality:
- Initial Styles Configuration: Predefines some styles like Title, Subtitle, Heading1, Heading2, and Normal.
- Render Styles List: Dynamically updates the list of styles displayed to the user whenever a new style is added.
- Handle Style Form Submission: Allows users to add new custom styles which are then stored in the
stylesConfigobject. - Parse Content Function: Reads the content from the editor, identifies the style based on font size (this can be enhanced), and creates corresponding
docx.Paragraphobjects with the appropriate styles. - Generate Word Document Function:
- Initializes a new
docx.Document. - Defines styles based on the
stylesConfig. Predefined styles are mapped to the corresponding Word styles, and any custom styles are also added. - Parses the content from the editor and adds it to the document.
- Uses
Packerfrom thedocxlibrary to generate a Blob and then usesFileSaver.jsto prompt the user to download the generated Word document.
- Initializes a new
Notes and Enhancements:
- Style Determination: In the current implementation, styles are determined based on the font size. For a more robust solution, you may want to implement a more sophisticated method of determining styles, such as using specific HTML tags or attributes.
- Rich Text Formatting: To support rich text formatting (like different fonts, colors, etc.), you would need to parse the HTML content more thoroughly and map it to
docxstyles and formatting options. - Error Handling: Additional error handling can be added to handle scenarios like invalid style names, unsupported characters, etc.
- Persisting Styles: If you want to persist the styles across sessions, consider storing the
stylesConfiginlocalStorageor another form of persistent storage.
Testing the Implementation:
- Open the HTML File: Save the above code in an
index.htmlfile and open it in your web browser. - Add or Modify Styles: Use the Style Configuration Panel to add new styles or modify existing ones.
- Enter Document Content: Write your document content in the editor area. Apply styles by adjusting the font size or other text properties as defined.
- Generate Document: Click the "Generate Word Document" button to download your customized Word document.
This implementation provides a flexible foundation for creating Word documents with customizable styles directly from the browser. You can further enhance it based on specific requirements or integrate more advanced features as needed.