### Initialize Server and Set Up Port Forwarding Source: https://context7.com/naskio/docx-viewer/llms.txt Details the steps for setting up the development environment, including cloning the repository, installing dependencies with yarn, and preparing the server for public URL access via port forwarding, which is necessary for online document viewers. ```bash # Installation and setup git clone git@github.com:naskio/docx-viewer.git cd docx-viewer yarn install ``` -------------------------------- ### GET / - Main Viewer Page Source: https://context7.com/naskio/docx-viewer/llms.txt Serves the main HTML page for the live DOCX viewer. This page includes an EJS template with configuration variables for the client-side application and connects to Socket.IO for real-time updates. ```APIDOC ## GET / ### Description Serves the main HTML page that displays the live DOCX viewer interface. It renders an EJS template with necessary configuration variables injected for the client-side application. ### Method GET ### Endpoint / ### Parameters None ### Request Example ```bash curl http://localhost:3000/ ``` ### Response #### Success Response (200) - **HTML Page** - The served page connects to Socket.IO and listens for 'reload' events. When a reload event is received, the iframe source is updated with a new version timestamp. #### Response Example (HTML content with embedded viewer and WebSocket connection) ``` -------------------------------- ### GET /static/:filename - Static File Serving Source: https://context7.com/naskio/docx-viewer/llms.txt Serves pre-generated DOCX files from the build directory. This endpoint is used when the STRATEGY environment variable is set to "static", providing faster document delivery without runtime generation overhead. ```APIDOC ## GET /static/:filename ### Description Serves pre-generated DOCX files from the build directory. This endpoint is used when the STRATEGY environment variable is set to "static", providing faster document delivery without runtime generation overhead. ### Method GET ### Endpoint /static/:filename ### Parameters #### Path Parameters - **filename** (string) - Required - The name of the DOCX file to serve (e.g., "output.docx"). #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:3000/static/output.docx ``` ### Response #### Success Response (200) - **Binary DOCX file** - The requested DOCX file is served. #### Response Example (Binary DOCX file content) ``` -------------------------------- ### GET /generate/:id - Dynamic Document Generation Source: https://context7.com/naskio/docx-viewer/llms.txt Dynamically generates and serves a DOCX file on each request. It imports the document definition, converts it to a base64 string, and returns it as a downloadable file. The `:id` parameter is used for cache-busting. ```APIDOC ## GET /generate/:id ### Description Dynamically generates and serves the DOCX file on each request. It imports the source document definition, converts it to a base64 string, and returns it as a downloadable file. The `:id` parameter is typically a timestamp used for cache-busting. ### Method GET ### Endpoint /generate/:id ### Parameters #### Path Parameters - **id** (string) - Required - A timestamp used for cache-busting. #### Query Parameters None #### Request Body None ### Request Example ```bash curl -o document.docx http://localhost:3000/generate/1698765432100 ``` ### Response #### Success Response (200) - **Binary DOCX file** - The response contains the DOCX file with a `Content-Disposition` header set for attachment. #### Response Example (Binary DOCX file content) ``` -------------------------------- ### Configure Application with Environment Variables Source: https://context7.com/naskio/docx-viewer/llms.txt Sets up application behavior using environment variables for document generation, viewer preferences, and deployment. Variables control the output filename, debounce timing, public URL, and viewer type. ```bash # .env configuration file GENERATED_FILENAME=output.docx DEBOUNCE_TIME=250 NODE_ENV=production PUBLIC_URL=https://your-ngrok-url.ngrok.io VIEWER=MICROSOFT STRATEGY=dynamic ``` -------------------------------- ### Serve Main Viewer Page - JavaScript Source: https://context7.com/naskio/docx-viewer/llms.txt This endpoint serves the main HTML page for the live DOCX viewer. It renders an EJS template and injects configuration variables necessary for the client-side application. The page connects to Socket.IO and listens for 'reload' events to update the viewer. ```javascript app.get('/', (req, res) => { res.render(path.join(__dirname, 'public', 'index.html'), { PUBLIC_URL: 'https://your-ngrok-url.ngrok.io', GENERATED_FILENAME: 'output.docx', NODE_ENV: 'development', DEBOUNCE_TIME: 250, VIEWER: 'GOOGLE', STRATEGY: 'static', }); }); ``` -------------------------------- ### Serve Static DOCX Files - JavaScript Source: https://context7.com/naskio/docx-viewer/llms.txt This endpoint serves pre-generated DOCX files from the build directory. It's used when the STRATEGY environment variable is set to 'static', offering faster delivery. This is often combined with a file watcher for automatic regeneration. ```javascript app.use('/static', express.static(BUILD_DIR)); ``` -------------------------------- ### Monitor Source Files for Changes - JavaScript Source: https://context7.com/naskio/docx-viewer/llms.txt This code sets up a file watcher using chokidar to monitor the `docx-src` directory for changes. Upon detecting a change, it dynamically imports the source file, regenerates the DOCX buffer, and writes it to the build directory. Debouncing is used to prevent excessive rebuilds. ```javascript import chokidar from 'chokidar'; import { Packer } from 'docx'; const SRC_DIR = './docx-src'; const BUILD_DIR = './docx-build'; const GENERATED_FILENAME = 'output.docx'; const DEBOUNCE_TIME = 250; const watcher_src = chokidar.watch(`${SRC_DIR}`); watcher_src.on('change', async (_path) => { try { console.log(`File source.js has been changed`); const doc_sample = await import(`./docx-src/source.js?version=${new Date()}`); const buffer = await Packer.toBuffer(doc_sample.default); fs.writeFileSync(path.join(BUILD_DIR, GENERATED_FILENAME), buffer); console.log(GENERATED_FILENAME, "has been generated"); } catch (err) { console.error("Error while generating file", GENERATED_FILENAME, err.message); } }); ``` -------------------------------- ### Dynamically Generate DOCX File - JavaScript Source: https://context7.com/naskio/docx-viewer/llms.txt This endpoint dynamically generates and serves DOCX files on each request. It imports the document definition, converts it to a base64 string, and returns it as a downloadable file. The `:id` parameter is used for cache-busting. This is used when the STRATEGY is set to 'dynamic'. ```javascript app.get("/generate/:id", async (req, res) => { try { const doc_sample = await import(`./docx-src/source.js?version=${new Date()}`); const b64string = await Packer.toBase64String(doc_sample.default); res.setHeader('Content-Disposition', `attachment; filename=output.docx`); res.send(Buffer.from(b64string, 'base64')); } catch (err) { console.error("Error while generating file", 'output.docx', err.message); res.status(500).send('Error generating document'); } }); ``` -------------------------------- ### Docx Viewer Initialization and Reloading (JavaScript) Source: https://github.com/naskio/docx-viewer/blob/main/public/index.html This JavaScript code initializes the Docx viewer by setting the iframe source and handles real-time document updates via WebSocket. It defines a function `getDocxUrl` to construct the document URL based on the viewer strategy and embed type (Google Docs or Microsoft Office Online). The `onLoadEvent` function sets up the initial iframe source and listens for 'reload' events from the server, debouncing the updates to prevent excessive reloads. ```javascript function onLoadEvent() { const public_url = "<%= PUBLIC_URL %>"; const file_name = "<%= GENERATED_FILENAME %>"; const node_env = "<%= NODE_ENV %>"; const debounce_time = +"<%= DEBOUNCE_TIME %>"; const viewer = "<%= VIEWER %>"; const strategy = "<%= STRATEGY %>"; const socket = io(); function getDocxUrl(public_url, file_name, strategy, version) { const iframe = viewer === 'GOOGLE' ? "https://docs.google.com/gview?embedded=true&url=" : "https://view.officeapps.live.com/op/embed.aspx?src="; if (strategy === "static") { return iframe + public_url + "/static/" + file_name + "&__version__=" + version; } else { return iframe + public_url + "/generate/" + version + "/"; } } if (node_env === 'production') { console.log('file_public_url', public_url); console.log('file_public_url', getDocxUrl(public_url, file_name, strategy, new Date().getTime())); console.log = function() {}; } // load iframe on page load document.getElementById('docx-viewer-iframe').src = getDocxUrl(public_url, file_name, strategy, new Date().getTime()); // reloading the iframe when the file is updated socket.on('reload', _.debounce(function() { document.getElementById('docx-viewer-iframe').src = getDocxUrl(public_url, file_name, strategy, new Date().getTime()); console.log('reload event received'); }, debounce_time, { leading: false, trailing: true, })); } ``` -------------------------------- ### Monitor DOCX File Changes with Socket.IO and Chokidar Source: https://context7.com/naskio/docx-viewer/llms.txt Monitors the generated DOCX file for changes using chokidar and emits Socket.IO 'reload' events to clients. This triggers browser refreshes for live preview. Dependencies include socket.io and chokidar. ```javascript import { Server } from 'socket.io'; const io = new Server(server); const watcher_build = chokidar.watch(`${BUILD_DIR}/${GENERATED_FILENAME}`); watcher_build.on('change', (_path) => { console.log(`File ${GENERATED_FILENAME} has been changed`); // Emit reload event to all connected clients io.sockets.emit('reload'); console.log(`reload event sent at`, new Date()); }); ``` ```javascript socket.on('reload', _.debounce(function () { const newUrl = getDocxUrl(public_url, file_name, strategy, new Date().getTime()); document.getElementById('docx-viewer-iframe').src = newUrl; console.log('reload event received'); }, debounce_time, { leading: false, trailing: true, })); ``` -------------------------------- ### Client-Side DOCX Viewer URL Generation (JavaScript) Source: https://context7.com/naskio/docx-viewer/llms.txt This JavaScript function constructs viewer URLs for DOCX files, supporting both Google Docs and Microsoft Office viewers. It handles static and dynamic rendering strategies, incorporating a version parameter for cache busting. It is intended for client-side integration within web applications. ```javascript function getDocxUrl(public_url, file_name, strategy, version) { // Select viewer based on configuration const iframe = viewer === 'GOOGLE' ? "https://docs.google.com/gview?embedded=true&url=" : "https://view.officeapps.live.com/op/embed.aspx?src=" ; if (strategy === "static") { // Static strategy: Points to pre-generated file with cache-busting return iframe + public_url + "/static/" + file_name + "&__version__=" + version; // Example: https://docs.google.com/gview?embedded=true&url=https://abc123.ngrok.io/static/output.docx&__version__=1698765432100 } else { // Dynamic strategy: Points to generation endpoint return iframe + public_url + "/generate/" + version + "/"; // Example: https://view.officeapps.live.com/op/embed.aspx?src=https://abc123.ngrok.io/generate/1698765432100/ } } // Usage in reload handler socket.on('reload', function () { const newUrl = getDocxUrl( 'https://abc123.ngrok.io', 'output.docx', 'static', new Date().getTime() ); document.getElementById('docx-viewer-iframe').src = newUrl; }); // The version parameter ensures browsers don't cache old document versions ``` -------------------------------- ### Manage Socket.IO Connections for Real-time Updates Source: https://context7.com/naskio/docx-viewer/llms.txt Handles WebSocket connections between the server and browser clients using Socket.IO. It logs connection/disconnection events and provides the infrastructure for sending 'reload' events to update the document viewer. ```javascript import { Server } from 'socket.io'; import * as http from 'http'; const app = express(); const server = http.createServer(app); const io = new Server(server); io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => { console.log('user disconnected'); }); }); ``` ```javascript const socket = io(); // Listens for 'reload' events from server socket.on('reload', function() { // Refresh iframe with new document version }); ``` -------------------------------- ### File Watcher - Source File Monitoring Source: https://context7.com/naskio/docx-viewer/llms.txt Monitors changes to files in the `docx-src` directory and automatically regenerates the DOCX output file. It uses chokidar for efficient file watching and debouncing. ```APIDOC ## File Watcher ### Description The source file watcher monitors changes to files in the `docx-src` directory and automatically regenerates the DOCX output file. It uses chokidar for efficient file watching and debouncing to prevent excessive rebuilds. ### Method N/A (Event-driven) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response N/A ### Details - Watches files in the `./docx-src` directory. - Uses chokidar for file system event monitoring. - Employs debouncing with a `DEBOUNCE_TIME` of 250ms. - Automatically regenerates `output.docx` in the `./docx-build` directory upon file changes. - Logs changes and generation status to the console. ``` -------------------------------- ### Define DOCX Document Structure with docx.js Source: https://context7.com/naskio/docx-viewer/llms.txt Defines the structure and content of a Word document using the docx.js API. This file is intended to be watched for changes, triggering document regeneration. It exports a Document object. ```javascript import docx from 'docx'; const { TextRun, Paragraph, Document, HeadingLevel, AlignmentType } = docx; const doc = new Document({ sections: [{ properties: {}, children: [ new Paragraph({ text: "Document Title", heading: HeadingLevel.HEADING_1, alignment: AlignmentType.CENTER, }), new Paragraph({ children: [ new TextRun({ text: "Hello", italics: true, size: 40, // Size in half-points (40 = 20pt) }), ], }), new Paragraph({ children: [ new TextRun({ text: "World !", bold: true, size: 40, color: "FF0000", // Hex color code }), ], }), ], }], }); export default doc; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.