When generating a docx file with html-docx-js, it lacks the capability to incorporate external CSS class styles into the document

I have been utilizing the html-docx-js module to convert html content into docx format. However, I am facing an issue where most of my CSS is externally loaded and html-docx-js does not apply any styles.

Here is a simplified code sample:

const html = '<html><head><link rel="stylesheet" type="text/css" href="/styles/page.css"></head><body><div className={bold}>I am bold!</div></body></html>'
saveAs(htmlDocx.asBlob(html), 'bold.docx');

I was advised to try using the juice library, but that solution did not work either.

Does anyone happen to know of a workaround to enable html-docx-js to load external CSS when generating a docx file?

Answer №1

Upon conducting thorough research, I successfully discovered a viable solution to address my issues:

There exists a module known as juice, designed to enable the application of specific CSS inline.

To utilize Juice, it was imperative to have a duplicate copy of the CSS file that needed to be separately loaded.

In addition, due to the limitation of html-docx-js only being able to read the first CSS style definition within an element, I had to make slight adjustments to both the CSS and HTML for compatibility.

The final code snippet showcases the implementation:


import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
const juice = require('juice');

let getIndex = new Promise((resolve, reject) => {
  this.requests('GET', '/styles/index.css')
    .then(data =>
      data.text().then(css => {
        resolve(css);
      })
    )
    .catch(error => reject(error));
});

getIndex
  .then(css => {
    let html =
      '<!DOCTYPE html><html><head lang="en"><style></style>' +
      '<meta charset="UTF-8"><title>Report</title></head><body>' +
      this.report.innerHTML +
      '</body></html>';

    html = juice.inlineContent(html, css);
    let docx = htmlDocx.asBlob(html);
    saveAs(docx, 'report.docx');
  })
  .catch(error => {
    console.log(error);
  });

Answer №2

You have the option to apply a CSS class within the head section, but it is essential to combine both the element tag and the classname.

The setup would resemble something like this:

<head>
...
<style type="text/css">
    div.MyCustomClass {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
    }
</style>
</head>
<body>
...
<div class="MyCustomClass">
...
</div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the data set in stone, or is it just the API data that can

Recently, I embarked on the journey of creating a blog using nextjs, MongoDB, and express. Taking advantage of getStaticProps and getStaticPaths, I was able to dynamically generate pages for each blog post and display them individually. However, I encoun ...

Behat automates the process of populating form fields that are dynamically displayed as 'visible'

I'm facing an issue with a form that has hidden fields. When a user selects a checkbox, some of the hidden form fields are supposed to be revealed using the jQuery function slideToggle(). The code itself is pretty simple and you can see an example her ...

Integrate Arduino's capabilities with Johnny-Five within an HTML JavaScript document

As a beginner in the world of JavaScript, I set out to embark on a project involving turning on a connected LED on an Arduino board by simply pressing a button on an HTML page. After doing some research, I came across a JavaScript library called "johnny- ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...

Ways to modify the .MuiSelect-nativeInput element within Material-UI

const styles = makeStyles((theme) => ({ root: { margin: "0px 20px" }, textStyle: { fontFamily: "Comfortaa", }, container: {}, textField: { fontFamily: "Comfortaa", }, dropDownFormSize: { width: &qu ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...

Having trouble notifying a json object following an ajax request

My project involves using a PHP file that contains an array with multiple values. Additionally, I have an HTML page that features a single input field. A listener is set up to detect changes in the input field. Once a change occurs, an AJAX call is trigge ...

Formatting in Cx framework: Configuring right alignment and decimal precision on NumberField

Currently, I am involved in a project that involves UI development using Cx, a new FrontEnd framework based on React. You can find more information about Cx at One of the tasks in my project involves creating a Grid with filter fields located at the top ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

ngRepeat does not iterate through an array

Presented below is an object: { "_id" : ObjectId("5454e173cf8472d44e7df161"), "questionType" : 0, "question" : "question1", "answers" : [ { "content" : "answer1" }, { "is_true" : "true", ...

What is the best way to display a button only when a different element is in focus?

I am working on a feature where each row consists of two text inputs and a button. The goal is to show the button when a user focuses on one of the input fields, and hide it again when they lose focus. I have come up with this solution: const Input = ({inp ...

React's back button is experiencing functionality issues

I'm having an issue with my quiz page where the previous button is not functioning properly. The user should be able to change their answer before submitting, but after 5-6 clicks on the previous button, they are redirected to the next page without co ...

"Utilizing FabricJs with Multiple Canvases to Display the Same Image Repeatedly

Within a loop ranging from 1 to 2, I have created two canvases on the screen and stored them in an object. However, when I load the same two images onto each canvas, only the last canvas displays the images. Why is it not loading on both canvases? Interest ...

Textarea with integrated checkbox

Can checkboxes be incorporated within a textarea using basic HTML and CSS? I'm aware that this can be achieved with tables, but I'm curious if it's possible within a textarea itself. ...

Issues with JQuery `.click()` event

Check out this snippet of code I'm working with: $(".item").click(function () { alert("clicked!"); }); I also have (hypothetically; in reality it's more complex) the following HTML on my page: <a href="#" class="item"> ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

What is the process of utilizing multiple npm registries within Yarn?

Currently, I am facing a challenge while setting up Yarn 0.17.9 in our environment due to issues with our registry setup. Our environment involves two registries - the official npmjs registry and our own internal network registry (Sinopia). The main issue ...