Converting html do word

37 Views Asked by At

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, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;")
    .replace(/Ş/g, "&#350;")
    .replace(/ş/g, "&#351;")
    .replace(/Ğ/g, "&#286;")
    .replace(/ğ/g, "&#287;")
    .replace(/Ç/g, "&#199;")
    .replace(/ç/g, "&#231;")
    .replace(/İ/g, "&#304;")
    .replace(/ı/g, "&#305;")
    .replace(/Ü/g, "&#220;")
    .replace(/ü/g, "&#252;")
    .replace(/Ö/g, "&#214;")
    .replace(/ö/g, "&#246;");

  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.

0

There are 0 best solutions below