I am trying to convert html to word. My code is working but i have two seperated paragraphs and i want to style them seperately .
function convertToWord() {
var divContent = document.getElementById("dataContainer").innerHTML;
var temp = document.createElement('div');
temp.innerHTML = divContent;
// Remove images from the HTML
var elementsToRemove = temp.querySelectorAll('img');
for (let i = 0; i < elementsToRemove.length; i++) {
elementsToRemove[i].remove();
}
var docContent = "<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='ISO-8859-9'><title>Export HTML to Word Document with JavaScript</title>" +
"<style>" +
"body { margin: 20px; }" +
".first-paragraph { color: #108be2; }" +
".second-paragraph { color: #ff0000; }" +
"</style></head><body>";
// Convert div elements to paragraphs
var divElements = temp.querySelectorAll('p');
for (let i = 0; i < divElements.length; i++) {
var className = "";
if (i === 0) {
className = "first-paragraph";
} else if (i === 1) {
className = "second-paragraph";
}
docContent += "<p class='" + className + "'>" + stripHTML(divElements[i].innerHTML) + "</p>";
}
docContent += "</body></html>";
// Create a download link for the Word document
var link = document.createElement('a');
link.href = 'data:application/msword;charset=ISO-8859-9,' + encodeURIComponent(docContent);
link.download = 'document.doc';
link.click();
}
function stripHTML(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
// Replace special characters with their HTML entities
var textContent = temp.textContent || temp.innerText || '';
textContent = textContent.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/Ş/g, "Ş")
.replace(/ş/g, "ş")
.replace(/Ğ/g, "Ğ")
.replace(/ğ/g, "ğ")
.replace(/Ç/g, "Ç")
.replace(/ç/g, "ç")
.replace(/İ/g, "İ")
.replace(/ı/g, "ı")
.replace(/Ü/g, "Ü")
.replace(/ü/g, "ü")
.replace(/Ö/g, "Ö")
.replace(/ö/g, "ö");
return textContent;
}
Here is my code . As you can see i got first-paragraph and second-paragraph classes but they doesn't appy the document. If i use plain p tag it works .But i need to seperate their styles.