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

Currently experimenting with optimal strategies for implementing useReducer and context hooks

Currently exploring the most effective approach for utilizing useReducer + context hooks. Which method is considered more optimal? Implementing one useReducer in the provider with a large initial state and multiple combined reducers. Utilizing multiple ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

My ability to click() a button is working fine, but I am unable to view the innerHTML/length. What could be the issue? (NodeJS

Initially, my goal is to verify the existence of the modal and then proceed by clicking "continue". However, I am facing an issue where I can click continue without successfully determining if the modal exists in the first place. This occurs because when I ...

Vercel triggers a 500 error on the internal server (functions correctly on localhost)

I am currently in the process of developing a webpage that gives me a comprehensive overview of all my notes and summaries. The notes are stored as markdown files which are then converted into HTML for use in a dynamic file. The '/note' pa ...

Sending a null value to the state is necessary to ensure that the ImageField in React and Django is updated to null

What I want to achieve I am trying to set null in the ImageField. My goal is to make the value of the ImageField for a model null. Issue Upon sending a Patch request, I encountered the following error. The submitted data was not a file. Check the encodin ...

How can I position divs in a way that the top right corner of the child div touches the bottom left corner

I am currently working on implementing a message box feature on my website. When a user clicks on the inbox icon, I want a messages box to appear, similar to how stackoverflow handles it. Stackoverflow achieves this by placing a div outside the ordered lis ...

Efficiently processing multiple Ajax requests with a single callback function

I am currently facing a situation where I need to make multiple AJAX requests and only proceed if all of them are successful. The typical usage of $.when($.ajax(), [...]).then(function(results){},[...]); doesn't quite fit my needs because the number o ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

Using JSON to store the image URLs instead of encoding them in base64

I am currently utilizing Three.js to store and retrieve objects in a database. The objects are being inserted as JSON format. However, the issue I am facing is that when using JSON.stringify or toJSON(), it converts the image url (textures) into base64 fo ...

Step-by-step guide on how to display chosen values in a multi-select dropdown menu

How can I dynamically select values in a multi-select box based on an array using Vue.js? I've attempted a solution but it's not working as expected. Any suggestions or help would be greatly appreciated. <div id="app"> <select class="m ...

What is the best way to create stylish corners on my website?

I'm struggling with creating a corner like the one shown in the image. As a beginner in frontend development, I attempted to write the following code but now I'm stuck. The Snippet: * { margin: 0; padding: 0; } body { height: 100vh; ...

Error: The attempt to access the 'useContext' property of null has failed due to a TypeError

Nowhere in my React code am I using the useContext property. There is a compiled webpack file in an npm package with a component inside. When trying to use this component in my React app, it throws an error: Uncaught TypeError: Cannot read properties of nu ...

Issue with Angular Material Table: Dragged rows do not drop in the correct position when scrolling

I'm encountering issues with using Angular Material Table along with Drag and Drop CDK and scrolling. While dragging a row and then scrolling, the row does not drop where intended. Additionally, the animation does not follow the scroll correctly. I ...

What is the best way to display a collection of square Views in a FlatList in a react native application?

How can you create a scrollable square grid with two columns of squares in a FlatList using react-native and ensure it is responsive to different screen sizes? Which CSS properties in react-native are necessary to achieve square shapes for each <Item/& ...

Using pg-promise to insert a UUID into the database

I am in the process of setting up a new server and I want each customer to have a unique UUID identifier. My goal is to allow the customers name, parent company, and internal id to be input through a web interface, while the UUID is generated on the server ...

Angular JS form cloning feature

I'm facing a challenge in creating a dynamic form with multiple sections. At the end of the form, I want to include a "Add New Form" button which will duplicate the existing form below it, each with its own save button. What's the most effective ...

Experience the sleek transparency when black hues grace the interface on iOS 14 and above

When implementing the code snippet below, .packages > .ulWrapper::after { background: linear-gradient( to left, var(--edge-color) 5%, rgba(0, 0, 0, 0) 95% ); /* option 1 - red */ background: linear-gradient( to left, var(--edg ...

The initial transition in offcanvas on bootstrap 5 is not appearing when a placement is dynamically added

I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end class to the offcanvas element, as it does not transition smoothly the first time it is t ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...