Generally, the export feature is used to download web page content as a file and save it for offline use. Microsoft Word or Doc (.doc) format is ideal for exporting HTML content in a file. The export to doc functionality can be easily implemented on the web application without server-side interaction. There is a client-side solution to export HTML to word document using JavaScript. The client-side export to doc functionality makes the web application user-friendly. The user can export a specific part of the web page content without page refresh.
Converting HTML content into a Microsoft Word document is a common requirement in web applications. For example, you might want to let users download an article, invoice, report, or specific section of a webpage as an editable Word document.
In this tutorial, we will learn how to export a specific HTML element to a Microsoft Word document (.docx) using vanilla JavaScript, without relying on any external libraries or third-party dependencies.
We will create a reusable JavaScript script that allows users to select an HTML section through an Export to Word button and download its content as a .docx file directly from the browser.
The implementation uses JavaScript and native browser APIs to generate the required Office Open XML (OOXML) document structure and package it into a valid DOCX file.
Following are the steps to implement the export functionality using JavaScript:
First, we will implement the JavaScript code in a separate script file (e.g., export-to-word.js). This script will contain the logic to convert the selected HTML content into a Word document format and trigger the download.
Unlike a simple HTML download with a .docx extension, a valid DOCX file requires a specific internal structure based on Office Open XML.
The implementation handles the following operations:
| HTML element | Word document representation |
|---|---|
| <h1> – <h6> | Heading styles |
| <p> | Paragraph |
| <strong> / <b> | Bold text |
| <em> / <i> | Italic text |
| <u> | Underlined text |
| <ul> / <ol> | Lists |
| <table> | Word table |
| <a> | Hyperlink |
The actual formatting support depends on the elements implemented in the JavaScript conversion logic.
(function () {
"use strict";
const ZIP_SIGNATURE = 0x04034b50;
const CENTRAL_SIGNATURE = 0x02014b50;
const END_SIGNATURE = 0x06054b50;
const encoder = new TextEncoder();
function escapeXml(value) {
return String(value == null ? "" : value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function sanitizeFilename(filename) {
const fallback = "document.docx";
let name = typeof filename === "string" && filename.trim() ? filename.trim() : fallback;
name = name.replace(/[<>:"/\\|?*\u0000-\u001F]/g, "_").replace(/[. ]+$/g, "");
name = name.replace(/(?:\.docx)+$/i, "");
return name ? `${name}.docx` : fallback;
}
function crc32(bytes) {
let crc = 0xffffffff;
for (let i = 0; i < bytes.length; i++) {
crc ^= bytes[i];
for (let bit = 0; bit < 8; bit++) {
crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
}
}
return (crc ^ 0xffffffff) >>> 0;
}
function createZip(entries) {
const localParts = [];
const centralParts = [];
let localOffset = 0;
const dosDateTime = { time: 0, date: 33 };
entries.forEach((entry) => {
const nameBytes = encoder.encode(entry.name);
const dataBytes = entry.data instanceof Uint8Array ? entry.data : encoder.encode(entry.data);
const checksum = crc32(dataBytes);
const localHeader = new Uint8Array(30 + nameBytes.length);
const localView = new DataView(localHeader.buffer);
localView.setUint32(0, ZIP_SIGNATURE, true);
localView.setUint16(4, 20, true);
localView.setUint16(6, 0x0800, true);
localView.setUint16(8, 0, true);
localView.setUint16(10, dosDateTime.time, true);
localView.setUint16(12, dosDateTime.date, true);
localView.setUint32(14, checksum, true);
localView.setUint32(18, dataBytes.length, true);
localView.setUint32(22, dataBytes.length, true);
localView.setUint16(26, nameBytes.length, true);
localView.setUint16(28, 0, true);
localHeader.set(nameBytes, 30);
localParts.push(localHeader, dataBytes);
const centralHeader = new Uint8Array(46 + nameBytes.length);
const centralView = new DataView(centralHeader.buffer);
centralView.setUint32(0, CENTRAL_SIGNATURE, true);
centralView.setUint16(4, 20, true);
centralView.setUint16(6, 20, true);
centralView.setUint16(8, 0x0800, true);
centralView.setUint16(10, 0, true);
centralView.setUint16(12, dosDateTime.time, true);
centralView.setUint16(14, dosDateTime.date, true);
centralView.setUint32(16, checksum, true);
centralView.setUint32(20, dataBytes.length, true);
centralView.setUint32(24, dataBytes.length, true);
centralView.setUint16(28, nameBytes.length, true);
centralView.setUint16(30, 0, true);
centralView.setUint16(32, 0, true);
centralView.setUint16(34, 0, true);
centralView.setUint16(36, 0, true);
centralView.setUint32(38, 0, true);
centralView.setUint32(42, localOffset, true);
centralHeader.set(nameBytes, 46);
centralParts.push(centralHeader);
localOffset += localHeader.length + dataBytes.length;
});
const centralSize = centralParts.reduce((sum, part) => sum + part.length, 0);
const centralOffset = localOffset;
const end = new Uint8Array(22);
const endView = new DataView(end.buffer);
endView.setUint32(0, END_SIGNATURE, true);
endView.setUint16(4, 0, true);
endView.setUint16(6, 0, true);
endView.setUint16(8, entries.length, true);
endView.setUint16(10, entries.length, true);
endView.setUint32(12, centralSize, true);
endView.setUint32(16, centralOffset, true);
endView.setUint16(20, 0, true);
return new Blob(
[...localParts, ...centralParts, end].map((part) => part.buffer.slice(part.byteOffset, part.byteOffset + part.byteLength)),
{ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }
);
}
function normalizedCssColor(color) {
if (!color || color === "transparent") return null;
const rgba = String(color).trim().match(/^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:[,\s/]+([\d.]+))?\s*\)$/i);
if (rgba && rgba[4] !== undefined && Number(rgba[4]) <= 0) return null;
const match = String(color).trim().match(/^#([0-9a-f]{6}|[0-9a-f]{3})$/i);
if (match) {
let hex = match[1].toLowerCase();
if (hex.length === 3) hex = hex.split("").map((char) => char + char).join("");
return hex.toUpperCase();
}
const rgb = String(color).match(/rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)/i);
if (rgb) {
return rgb.slice(1).map((value) => Math.max(0, Math.min(255, Number(value))).toString(16).padStart(2, "0")).join("").toUpperCase();
}
return null;
}
function getAlignment(element) {
const align = element.getAttribute("align") || (window.getComputedStyle ? getComputedStyle(element).textAlign : "");
return ["left", "center", "right", "justify"].includes(String(align).toLowerCase())
? String(align).toLowerCase()
: null;
}
function getEffectiveInlineStyles(element) {
const style = window.getComputedStyle ? getComputedStyle(element) : null;
const parentStyle = element.parentElement && window.getComputedStyle
? getComputedStyle(element.parentElement)
: null;
if (!style) return {};
const color = normalizedCssColor(style.color);
const parentColor = parentStyle ? normalizedCssColor(parentStyle.color) : null;
const background = normalizedCssColor(style.backgroundColor);
const parentBackground = parentStyle ? normalizedCssColor(parentStyle.backgroundColor) : null;
return {
color: color && color !== parentColor ? color : null,
background: background && background !== parentBackground ? background : null
};
}
function paragraphStart(element, extraStyle, numPr) {
const parts = [];
const align = getAlignment(element);
if (align) parts.push(`<w:jc w:val="${align}"/>`);
if (extraStyle) parts.push(extraStyle);
if (numPr) parts.push(numPr);
return parts.length ? `<w:pPr>${parts.join("")}</w:pPr>` : "";
}
function makeTextRun(text, formatting = {}) {
if (!text) return "";
const properties = [];
if (formatting.bold) properties.push("<w:b/>");
if (formatting.italic) properties.push("<w:i/>");
if (formatting.underline) properties.push('<w:u w:val="single"/>');
if (formatting.strike) properties.push("<w:strike/>");
if (formatting.superscript) properties.push('<w:vertAlign w:val="superscript"/>');
if (formatting.subscript) properties.push('<w:vertAlign w:val="subscript"/>');
if (formatting.code) properties.push('<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas"/>');
if (formatting.color) properties.push(`<w:color w:val="${formatting.color}"/>`);
if (formatting.background) properties.push(`<w:shd w:val="clear" w:fill="${formatting.background}"/>`);
const runProps = properties.length ? `<w:rPr>${properties.join("")}</w:rPr>` : "";
return `<w:r>${runProps}<w:t xml:space="preserve">${escapeXml(text)}</w:t></w:r>`;
}
async function imageData(src) {
if (!src) return null;
if (src.startsWith("data:")) {
const match = src.match(/^data:([^;,]+)?(?:;[^,]*)?,(.*)$/s);
if (!match) return null;
const contentType = match[1] || "application/octet-stream";
const payload = match[2];
let binary;
if (src.includes(";base64,")) {
binary = atob(payload);
} else {
binary = decodeURIComponent(payload);
}
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return { bytes, contentType };
}
try {
const resolvedUrl = src.startsWith("blob:")
? src
: new URL(src, document.baseURI).href;
const response = await fetch(resolvedUrl);
if (!response.ok) return null;
const blob = await response.blob();
const contentType = blob.type || response.headers.get("content-type") || "application/octet-stream";
return {
bytes: new Uint8Array(await blob.arrayBuffer()),
contentType: contentType.split(";")[0]
};
} catch (_) {
}
try {
const resolvedUrl = src.startsWith("blob:")
? src
: new URL(src, document.baseURI).href;
const image = await new Promise((resolve, reject) => {
const loadedImage = new Image();
loadedImage.onload = () => resolve(loadedImage);
loadedImage.onerror = reject;
loadedImage.crossOrigin = "anonymous";
loadedImage.src = resolvedUrl;
});
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth || 320;
canvas.height = image.naturalHeight || 240;
const context = canvas.getContext("2d");
if (!context) return null;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
if (!blob) return null;
return {
bytes: new Uint8Array(await blob.arrayBuffer()),
contentType: "image/png"
};
} catch (_) {
return null;
}
}
function imageExtension(contentType, src) {
const map = { "image/png": "png", "image/jpeg": "jpeg", "image/gif": "gif", "image/bmp": "bmp" };
if (map[contentType]) return map[contentType];
const match = String(src).match(/\.([a-z0-9]+)(?:[?#]|$)/i);
return match ? match[1].toLowerCase().replace(/[^a-z0-9]/g, "") : "png";
}
async function collectInline(node, formatting, state, maxDepth = 40) {
if (maxDepth <= 0 || node.nodeType === Node.COMMENT_NODE) return "";
if (node.nodeType === Node.TEXT_NODE) return makeTextRun(node.nodeValue, formatting);
if (node.nodeType !== Node.ELEMENT_NODE) return "";
const tag = node.tagName.toLowerCase();
const next = { ...formatting };
if (tag === "b" || tag === "strong") next.bold = true;
if (tag === "i" || tag === "em") next.italic = true;
if (tag === "u") next.underline = true;
if (tag === "s" || tag === "strike" || tag === "del") next.strike = true;
if (tag === "sup") next.superscript = true;
if (tag === "sub") next.subscript = true;
if (tag === "code") next.code = true;
const inlineStyle = window.getComputedStyle ? getComputedStyle(node) : null;
const effectiveStyles = getEffectiveInlineStyles(node);
if (effectiveStyles.color) next.color = effectiveStyles.color;
if (effectiveStyles.background) next.background = effectiveStyles.background;
if (inlineStyle && (inlineStyle.fontWeight === "bold" || Number(inlineStyle.fontWeight) >= 600)) next.bold = true;
if (inlineStyle && inlineStyle.fontStyle === "italic") next.italic = true;
if (inlineStyle && inlineStyle.textDecorationLine && inlineStyle.textDecorationLine.includes("underline")) next.underline = true;
if (tag === "br") return "<w:r><w:br/></w:r>";
if (tag === "img") {
const data = await imageData(node.getAttribute("src"));
if (!data) return "";
const extension = imageExtension(data.contentType, node.getAttribute("src"));
const index = state.images.length + 1;
const naturalWidth = Number(node.naturalWidth) > 0 ? Number(node.naturalWidth) : 320;
const naturalHeight = Number(node.naturalHeight) > 0 ? Number(node.naturalHeight) : 240;
const requestedWidth = parseInt(node.getAttribute("width"), 10);
let width = Number.isFinite(requestedWidth) && requestedWidth > 0
? Math.min(requestedWidth, 720)
: Math.min(naturalWidth, 480);
const requestedHeight = parseInt(node.getAttribute("height"), 10);
let height = Number.isFinite(requestedHeight) && requestedHeight > 0
? requestedHeight
: Math.max(1, Math.round(width * naturalHeight / naturalWidth));
state.images.push({
name: `word/media/image${index}.${extension}`,
bytes: data.bytes,
relationshipId: `rIdImage${index}`,
contentType: data.contentType
});
const cx = width * 9525;
const cy = Math.max(1, height) * 9525;
return `<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="${cx}" cy="${cy}"/><wp:effectExtent l="0" t="0" r="0" b="0"/><wp:docPr id="${index}" name="Picture ${index}" descr="Embedded image"/><wp:cNvGraphicFramePr/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:nvPicPr><pic:cNvPr id="${index}" name="Picture ${index}"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rIdImage${index}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`;
}
if (tag === "a" && node.getAttribute("href")) {
const href = node.getAttribute("href");
const relationshipId = `rIdLink${state.links.length + 1}`;
state.links.push({ id: relationshipId, href });
let body = "";
for (const child of node.childNodes) body += await collectInline(child, { ...next, underline: true, color: "0563C1" }, state, maxDepth - 1);
return `<w:hyperlink r:id="${relationshipId}" w:history="1">${body}</w:hyperlink>`;
}
let output = "";
for (const child of node.childNodes) {
output += await collectInline(child, next, state, maxDepth - 1);
}
return output;
}
async function convertTable(table, state) {
const rows = Array.from(table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr"));
if (!rows.length) return "";
const gridCells = Math.max(1, ...rows.map((row) => row.children.length));
const grid = Array.from({ length: gridCells }, () => '<w:gridCol w:w="2400"/>').join("");
let xml = `<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/><w:tblBorders><w:top w:val="single" w:sz="4" w:color="808080"/><w:left w:val="single" w:sz="4" w:color="808080"/><w:bottom w:val="single" w:sz="4" w:color="808080"/><w:right w:val="single" w:sz="4" w:color="808080"/><w:insideH w:val="single" w:sz="4" w:color="808080"/><w:insideV w:val="single" w:sz="4" w:color="808080"/></w:tblBorders></w:tblPr><w:tblGrid>${grid}</w:tblGrid>`;
for (const row of rows) {
xml += "<w:tr>";
for (const cell of row.children) {
const tag = cell.tagName.toLowerCase();
if (tag !== "td" && tag !== "th") continue;
const align = getAlignment(cell);
const inline = await collectInlineForContainer(cell, state);
const shade = normalizedCssColor(window.getComputedStyle ? getComputedStyle(cell).backgroundColor : null);
const shadeXml = shade ? `<w:shd w:val="clear" w:fill="${shade}"/>` : "";
const header = tag === "th" ? "<w:rPr><w:b/></w:rPr>" : "";
xml += `<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/><w:vAlign w:val="center"/>${shadeXml}</w:tcPr><w:p>${paragraphStart(cell, align ? `<w:jc w:val="${align}"/>` : "")}${header}${inline}</w:p></w:tc>`;
}
xml += "</w:tr>";
}
return xml + "</w:tbl>";
}
async function collectInlineForContainer(element, state) {
let output = "";
const formatting = {};
const elementStyle = window.getComputedStyle ? getComputedStyle(element) : null;
if (elementStyle) {
const effectiveStyles = getEffectiveInlineStyles(element);
if (effectiveStyles.color) formatting.color = effectiveStyles.color;
if (effectiveStyles.background) formatting.background = effectiveStyles.background;
if (elementStyle.fontWeight === "bold" || Number(elementStyle.fontWeight) >= 600) formatting.bold = true;
if (elementStyle.fontStyle === "italic") formatting.italic = true;
if (elementStyle.textDecorationLine && elementStyle.textDecorationLine.includes("underline")) formatting.underline = true;
}
for (const child of element.childNodes) output += await collectInline(child, formatting, state);
return output;
}
async function convertNode(node, state, depth = 0) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.nodeValue.replace(/\s+/g, " ").trim();
return text ? `<w:p>${makeTextRun(text)}</w:p>` : "";
}
if (node.nodeType !== Node.ELEMENT_NODE) return "";
if (depth > 60) return "";
const tag = node.tagName.toLowerCase();
if (tag === "script" || tag === "style" || tag === "template" || tag === "noscript") return "";
if (tag === "table") return await convertTable(node, state);
if (/^h[1-6]$/.test(tag)) {
const level = Number(tag.slice(1));
const style = `<w:keepNext/><w:outlineLvl w:val="${level - 1}"/>`;
const content = await collectInlineForContainer(node, state);
return `<w:p>${paragraphStart(node, `${style}<w:pStyle w:val="Heading${level}"/>`)}${content}</w:p>`;
}
if (tag === "p" || tag === "div") {
const content = await collectInlineForContainer(node, state);
return content ? `<w:p>${paragraphStart(node)}${content}</w:p>` : "";
}
if (tag === "blockquote") {
let body = "";
for (const child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
if (child.nodeValue.trim()) {
body += `<w:p>${makeTextRun(child.nodeValue.trim())}</w:p>`;
}
} else if (child.nodeType === Node.ELEMENT_NODE) {
body += await convertNode(child, state, depth + 1);
}
}
if (!body) return "";
const quoteProperties = '<w:ind w:left="720"/><w:pBdr><w:left w:val="single" w:sz="12" w:space="4" w:color="A6A6A6"/></w:pBdr>';
return body
.replace(/<w:pPr>/g, `<w:pPr>${quoteProperties}`)
.replace(/<w:p>(?!<w:pPr>)/g, `<w:p><w:pPr>${quoteProperties}</w:pPr>`);
}
if (tag === "ul" || tag === "ol") return await convertList(node, tag === "ol", state, depth + 1, 0);
if (tag === "hr") {
return '<w:p><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="808080"/></w:pBdr></w:p>';
}
if (tag === "br") return "<w:p/>";
if (tag === "img") return `<w:p>${await collectInline(node, {}, state)}</w:p>`;
let output = "";
for (const child of node.childNodes) output += await convertNode(child, state, depth + 1);
return output;
}
async function convertList(list, ordered, state, depth, level) {
let output = "";
let itemIndex = 1;
const children = Array.from(list.children).filter((child) => child.tagName && child.tagName.toLowerCase() === "li");
for (const item of children) {
const numId = ordered ? (level === 0 ? 2 : 3) : 1;
const numPr = `<w:numPr><w:ilvl w:val="${level}"/><w:numId w:val="${numId}"/></w:numPr>`;
let inline = "";
for (const child of item.childNodes) {
if (child.nodeType === Node.ELEMENT_NODE && ["ul", "ol"].includes(child.tagName.toLowerCase())) continue;
inline += await collectInline(child, {}, state);
}
output += `<w:p>${paragraphStart(item, `<w:ind w:left="${720 * (level + 1)}" w:hanging="360"/>`, numPr)}${inline}</w:p>`;
itemIndex++;
for (const child of item.children) {
const childTag = child.tagName && child.tagName.toLowerCase();
if (childTag === "ul" || childTag === "ol") {
output += await convertList(child, childTag === "ol", state, depth + 1, level + 1);
}
}
}
return output;
}
async function convertHtml(targetElement) {
const state = { links: [], images: [] };
const images = Array.from(targetElement.querySelectorAll("img"));
await Promise.all(images.map((image) => {
if (image.complete) return Promise.resolve();
return new Promise((resolve) => {
image.addEventListener("load", resolve, { once: true });
image.addEventListener("error", resolve, { once: true });
});
}));
let body = "";
for (const child of targetElement.childNodes) body += await convertNode(child, state);
if (!body.trim()) throw new Error("The target element is empty.");
return { body, ...state };
}
function getStylesXml() {
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="160"/></w:pPr></w:pPrDefault></w:docDefaults>
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="22"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="120"/><w:outlineLvl w:val="0"/></w:pPr><w:rPr><w:rFonts w:ascii="Calibri Light" w:hAnsi="Calibri Light"/><w:b/><w:color w:val="2F5597"/><w:sz w:val="32"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="200" w:after="100"/><w:outlineLvl w:val="1"/></w:pPr><w:rPr><w:rFonts w:ascii="Calibri Light" w:hAnsi="Calibri Light"/><w:b/><w:color w:val="2F5597"/><w:sz w:val="26"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="160" w:after="80"/><w:outlineLvl w:val="2"/></w:pPr><w:rPr><w:b/><w:color w:val="1F4E79"/><w:sz w:val="24"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading4"><w:name w:val="heading 4"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/><w:color w:val="2F5597"/><w:sz w:val="22"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading5"><w:name w:val="heading 5"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/><w:sz w:val="22"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading6"><w:name w:val="heading 6"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/><w:color w:val="666666"/><w:sz w:val="20"/></w:rPr></w:style>
</w:styles>`;
}
function getNumberingXml() {
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/>
${[0,1,2,3,4,5,6,7,8].map((level) => `<w:lvl w:ilvl="${level}"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="•"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (level + 1)}" w:hanging="360"/></w:pPr></w:lvl>`).join("")}</w:abstractNum>
<w:abstractNum w:abstractNumId="1"><w:multiLevelType w:val="hybridMultilevel"/>
${[0,1,2,3,4,5,6,7,8].map((level) => `<w:lvl w:ilvl="${level}"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%${level + 1}."/><w:lvlJc w:val="right"/><w:pPr><w:ind w:left="${720 * (level + 1)}" w:hanging="360"/></w:pPr></w:lvl>`).join("")}</w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num><w:num w:numId="3"><w:abstractNumId w:val="1"/></w:num>
</w:numbering>`;
}
function getDocumentXml(body) {
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
<w:body>${body}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr></w:body></w:document>`;
}
function getContentTypes(images) {
let defaults = '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>';
const mediaTypes = new Map();
images.forEach((image) => {
const extension = image.name.split(".").pop();
mediaTypes.set(extension, image.contentType === "application/octet-stream" ? "image/png" : image.contentType);
});
for (const [extension, type] of mediaTypes) defaults += `<Default Extension="${escapeXml(extension)}" ContentType="${escapeXml(type)}"/>`;
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${defaults}
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>
</Types>`;
}
function getPackageRelationships() {
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>`;
}
function getDocumentRelationships(links, images) {
const relationships = [
'<Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>',
'<Relationship Id="rIdNumbering" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>'
];
links.forEach((link) => relationships.push(`<Relationship Id="${escapeXml(link.id)}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="${escapeXml(link.href)}" TargetMode="External"/>`));
images.forEach((image) => relationships.push(`<Relationship Id="${escapeXml(image.relationshipId)}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/${image.name.split("/").pop()}"/>`));
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationships.join("")}</Relationships>`;
}
function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.style.display = "none";
document.body.appendChild(anchor);
try {
anchor.click();
} finally {
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
}
async function exportToWord(target, filename = "document.docx") {
if (!target) throw new Error("A target ID or CSS selector is required.");
let element;
try {
element = typeof target === "string"
? (document.getElementById(target.replace(/^#/, "")) || document.querySelector(target))
: target;
} catch (error) {
throw new Error(`Invalid target selector: ${error.message}`);
}
if (!element || !(element instanceof Element)) throw new Error(`Export target "${target}" was not found.`);
const converted = await convertHtml(element);
const entries = [
{ name: "[Content_Types].xml", data: getContentTypes(converted.images) },
{ name: "_rels/.rels", data: getPackageRelationships() },
{ name: "word/document.xml", data: getDocumentXml(converted.body) },
{ name: "word/styles.xml", data: getStylesXml() },
{ name: "word/numbering.xml", data: getNumberingXml() },
{ name: "word/_rels/document.xml.rels", data: getDocumentRelationships(converted.links, converted.images) }
];
converted.images.forEach((image) => entries.push({ name: image.name, data: image.bytes }));
const blob = createZip(entries);
const safeFilename = sanitizeFilename(filename);
downloadBlob(blob, safeFilename);
return { filename: safeFilename, blob };
}
function initializeExportButtons() {
document.querySelectorAll(".export-to-word").forEach((button) => {
if (button.dataset.wordExportBound === "true") return;
button.dataset.wordExportBound = "true";
button.addEventListener("click", async () => {
const originalText = button.textContent;
button.disabled = true;
try {
await exportToWord(button.dataset.target, button.dataset.filename || "document.docx");
} catch (error) {
console.error("Word export failed:", error);
window.alert(`Word export failed: ${error.message}`);
} finally {
button.disabled = false;
button.textContent = originalText;
}
});
});
}
window.exportToWord = exportToWord;
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initializeExportButtons);
} else {
initializeExportButtons();
}
})();
Create the HTML structure for your webpage, including the content you want to export and the export button. Use the export-to-word class for the button and specify the target element’s ID in the data-target attribute.
<!-- Export Button -->
<button
type="button"
class="export-to-word"
data-target="word-content"
data-filename="sample-document.docx">
Export to Word
</button>
<!-- Content to Export -->
<main id="word-content">
<h1>Sample Document</h1>
<p>Hello from HTML.</p>
<h2>Introduction</h2>
<p>
This is an example of exporting HTML content
to a Microsoft Word document using JavaScript.
</p>
<h2>Features</h2>
<ul>
<li>No external JavaScript libraries</li>
<li>Client-side document generation</li>
<li>Downloadable DOCX document</li>
</ul>
</main>
Include the JavaScript File:
Include the JavaScript file in your HTML page using a <script> tag, preferably at the end of the body section to ensure that the DOM is fully loaded before the script runs.
<script src="export-to-word.js"></script>
How it works:
export-to-word class identifies the export button.data-target attribute specifies which HTML element should be converted.data-filename attribute defines the downloaded document’s filename.word-content ID identifies the content container.When the button is clicked, the JavaScript script retrieves the HTML content from the specified element and generates a Word document.
You can use the same JavaScript file to export multiple sections of a webpage.
Simply add multiple export buttons and specify a different target element for each button.
For example:
<!-- First Export Button -->
<button
type="button"
class="export-to-word"
data-target="article-content"
data-filename="article.docx">
Export Article
</button>
<!-- First Content Section -->
<div id="article-content">
<h2>Article Content</h2>
<p>This is the first section to export.</p>
</div>
<!-- Second Export Button -->
<button
type="button"
class="export-to-word"
data-target="report-content"
data-filename="report.docx">
Export Report
</button>
<!-- Second Content Section -->
<div id="report-content">
<h2>Report Content</h2>
<p>This is another section to export.</p>
</div>
<script src="export-to-word.js"></script>
Each button exports only the HTML content of its corresponding target element.
There is no need to initialize a separate JavaScript function for every export button.
Besides using HTML buttons, you can also call the exported JavaScript function directly from your application.
The script exposes the exportToWord() function through the global window object.
Syntax:
exportToWord(target, filename);
Parameters:
Example:
exportToWord('word-content', 'my-document.docx');
You can also use a CSS selector:
exportToWord('#word-content', 'my-document.docx');
If the filename is omitted, the script uses its default filename.
This approach is useful when integrating the export functionality into custom application workflows or existing JavaScript event handlers.
.docx document using Office Open XML rather than simply changing an HTML file extension.In this tutorial, we learned how to export HTML content to a Microsoft Word document (.docx) using vanilla JavaScript without external libraries.
By generating the required Office Open XML files and packaging them into a ZIP archive, we can create genuine Word documents directly in the browser without relying on third-party dependencies or server-side processing.
The reusable exportToWord() function makes it easy to integrate this functionality into any webpage. You can also use multiple export buttons to download different HTML sections as separate Word documents.
This approach is particularly useful for web applications that need to provide downloadable reports, articles, invoices, and other structured HTML content in an editable Word document format.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
It’s default portrait how can i do it landscape.
Nice tutorial, however when i open file using word, it keeps default option as webpage. Is there any way to change that??
Hello I’d like to ask is there any way to mantain the formatting in the exported file? Asking about span content that has been italicized.
How to remove header and footer ??
How to remove some content in .doc file when exporting from html file?
How to add header and footer?
Is there a way to password protect the file so it can only be viewed and not edited?
Is there a way to create custom document properties for the generated word document? Trying to create an information dump for retrieving the parameters that originally created the word document.
Dear CodexWorld,
Thanks for this great article.
I need to change font size and font family in the word document.
Kindly help me out pls.
Thanks,
V. Sangeetha
is there any chance to change font ?
Thanks for the assistance. I have one question. I am using a style sheet to modify my table when displaying. But these styles aren’t inherited to the word doc created from your code. How can I achieve this?
This is excellent, thank you.
Using your tutorial I have built an app on my website that populates user data (like name, address and other fields) into a user agreement which they can then download as a word doc.
But I have a question. I would like to have that word doc emailed to me as well, so I need to build a php handler. Would you be able to tell me if it’s possible to include this word doc in the handler?
Need to print the content of each div in different page in word document. Any help is appreciated. Thank You.
Hello,
I need to print content of each ‘div’ element in HTML in separate page in .docx. Any idea, how to achieve that?
Hello!
Nice article!
How could I use Image base64 data in the document word?
Regards
THANK YOU!!!!!!!!!!!!!!!!
How can I use this for exporting Chart.js charts and set the portrait to landscape.
Great tutorial! However, I cannot open .doc file in Pages on Mac. Tried .docx with no success. Are there any formatting issues regarding Apple? Thanx.
Hi,
Thanks for sharing this article.
What are those minor changes i have to make if i want to export the file as .docx format?
You don’t need to do any modification in the code. Just use
.docxextension in the filename.