HTML File with External CSS Reference is not adding css to the converted pdf file

Hi Team,

I am trying following simple html file with external css to convert it to pdf.
It is getting converted but css is not getting loaded.

This is my conversion script.
var api = require(‘@asposecloud/aspose-html-cloud’);

// Create Conversion Api object
var conversionApi = new api.ConversionApi(conf);

var src = “./htmlstyle.html”; // {String} Source document.
var dst = “./teststyle.pdf”; // {String} Result document.
var opts = null;

var callback = function (error, data, response) {
if (error) {
console.error(error);
} else {
console.log(data);
}
};

conversionApi.convertLocalToLocal(src, dst, opts, callback);

Following is the html I am trying
var api = require(‘@asposecloud/aspose-html-cloud’);

// Create Conversion Api object
var conversionApi = new api.ConversionApi(conf);

var src = “./htmlstyle.html”; // {String} Source document.
var dst = “./teststyle.pdf”; // {String} Result document.
var opts = null;

var callback = function (error, data, response) {
if (error) {
console.error(error);
} else {
console.log(data);
}
};

conversionApi.convertLocalToLocal(src, dst, opts, callback);

CSS file:
/* General styling for the entire document */
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
color: #333;
background-color: #f9f9f9;
}

/* Styling the header */
header h1 {
text-align: center;
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}

/* Invoice details section */
.invoice-details {
background-color: #ecf0f1;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}

/* Styling the table */
.styled-table {
width: 100%;
border-collapse: collapse;
}

.styled-table th,
.styled-table td {
border: 1px solid #3498db;
padding: 10px;
text-align: left;
}

.styled-table th {
background-color: #3498db;
color: #fff;
}

.styled-table tbody tr:nth-child(even) {
background-color: #f2f2f2;
}

/* Footer styling */
footer {
text-align: center;
margin-top: 30px;
font-weight: bold;
color: #27ae60;
}

@Deepali11

It seems that the issue you’re facing with the CSS not being applied during the HTML to PDF conversion may be related to the use of external fonts or styles. Here are a few suggestions to help you resolve this:

  1. Use of Custom Fonts: If your CSS references custom fonts, ensure that these fonts are accessible. Commercial fonts require a license and cannot be used directly without proper setup. You can host the fonts on your own server (like AWS S3) and link them in your CSS using the @font-face rule. For example:

    @font-face {
        font-family: 'MyCustomFont';
        src: url('https://yourserver.com/path/to/font.woff');
    }
    body {
        font-family: 'MyCustomFont', Arial, sans-serif;
    }
    
  2. Using Web Fonts: Alternatively, you can use web fonts from a CDN, such as Google Fonts. This is a straightforward way to ensure that the fonts are loaded correctly. For example:

    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400&display=swap" rel="stylesheet">
    

    Then, in your CSS, you can specify:

    body {
        font-family: 'Roboto', sans-serif;
    }
    
  3. Check CSS File Path: Ensure that the path to your external CSS file is correct and accessible. If the CSS file is not found, the styles will not be applied.

  4. Debugging: You can also try converting a simpler HTML file with inline styles to see if the issue persists. This can help determine if the problem is with the CSS file or the conversion process itself.

By following these steps, you should be able to troubleshoot the CSS loading issue during the conversion process. If the problem continues, consider checking the Aspose documentation for any specific requirements regarding CSS and font usage in HTML to PDF conversions.

Sources:
[1]: CSS font-family not being respected, only default system font working

I have checked the html and for now I have also removed the fonts for testing.
My html file is working correctly on browser with css.
But when converting with aspose I am getting following file.
htmltopdfbyaspose.pdf (11.7 KB)

When converting with some other library I am getting following result.
pupeter.pdf (71.3 KB)

Can you please reply to this query?

Hi @Deepali11 Than you for waiting. We had to check a few things. It looks like you send only html file to cloud server and don’t send file with styles. Conversion on server doesn’t see you local styles file. So there are 3 possible solutions:

  1. Include styles to html file.
  2. Make a call to upload file to server using FileApi: aspose-html-cloud-nodejs/docs/FileApi.md at master · aspose-html-cloud/aspose-html-cloud-nodejs · GitHub Please follow the same folder structure as you have locally, So for example if locally file is located in assets/styles/main.css you would need to upload file to the same folders on server. Just set upload destination path assets/styles/main.css and api will recreate this structure for you.
  3. Upload styles file to your own cloud or CDN and then profile full path to styles file in your HTML file
    SO the idea is to make styles visible for server. Please let us know if you need more details.

This script is not working when I am trying to convert a file.
I have tried with multiple files.
var conf = {
“basePath”: “https://api.aspose.cloud/v4.0”,
“authPath”: “https://api.aspose.cloud/connect/token”,
“apiKey”: “dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxd”,
“appSID”: “4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxc”,
“defaultUserAgent”: “NodeJsWebkit”
};

var api = require(‘@asposecloud/aspose-html-cloud’);

// Create Conversion Api object
var conversionApi = new api.ConversionApi(conf);

var src = “./output.html”; // {String} Source document.
var dst = “./output1.pdf”; // {String} Result document.
var opts = null;

var callback = function (error, data, response) {
console.log(‘Raw Response:’, response);
if (error) {
console.error(‘API Error:’, error);
} else if (!data) {
console.error(‘API Response is null or undefined’);
} else {
console.log(‘API Response:’, data);
}
if (error) {
console.error(error);
} else {
console.log(data);
}
};

conversionApi.convertLocalToLocal(src, dst, opts, callback);

Getting following error
throw new Error(“Unable to upload file”);
^

Error: Unable to upload file

Also Swagger UI swagger file is not working as it gives 401 for all api calls due to missing authnetication.

@Deepali11 We released some adjustments based on your case. Please try how it works for you now and let us know

@andrey.gubal
I have attached a screenshot of response I am getting on swagger.
Please add authorization there.
And my script is also giving me same response as it was showing in the last message.
Please check

Hello @Deepali11 We don’t plan adding authorisation to swagger. Mainly due to security limitations. Please use swagger only as a documentation. All endpoints must be called with your bearer token. You can call them from your postman or another similar tool. Please use this url to export Swagger spec in json: https://api.aspose.cloud/v4.0/html/swagger/spec SO that you could import it to postaman and get the full list of endpoints threre.

Hi @andrey.gubal

API is working now in postman.
But I have same issue as of now.
Styling is not getting implemented with aspose.
Let me share my html file and the ouput file I am getting form aspose and Puppeteer package.
pupeteerconvertedfile.pdf (332.1 KB)

aspose_converted_file.pdf (45.9 KB)

And for styling I am using public link
https://docserqablobs.blob.core.windows.net/dtlp-file-storage-qa/datachain/12/styles2.css?st=2025-02-06T00%3A57%3A33Z&se=2027-11-03T00%3A57%3A33Z&sp=r&spr=https&sv=2018-03-28&sr=b&sig=aDq8on%2BpSf6TgJxpl74FYkAYuOmrxJOVkHI0Akwg844%3D

can you please check

@andrey.gubal
this is my html file link
https://docserqablobs.blob.core.windows.net/dtlp-file-storage-qa/datachain/12/testhtml.html?st=2025-02-06T01%3A06%3A52Z&se=2027-11-03T01%3A06%3A52Z&sp=r&spr=https&sv=2018-03-28&sr=b&sig=cXYz4%2BnkUNUajAyy2l7cOVIbDsk2cJ5Ce4TmGcKwrUM%3D

@andrey.gubal
Can you please reply to this query?

Hi @Deepali11 we took some time to check. Styles are working in the documents. If you scroll down you can see that there are backgrounds etc. There are 2 things in the document that make it look as if styles were not applied:

  1. We don’t yet support display: grid; So layout of the document looks broken. We will schedule work to add support for this feature but will take some time. Realistically middle-end of Q2 2025. For now please use alternative styles for the layout.
  2. Fonts. Since this is cloud approach and conversion happens on our servers we can’t use Windows or licensed fonts, like Arial in the document. We can only work with web fonts, like free fonts provided by Google. So if you’d like to use some specific licenced font you would need to provide it by link in styles. SOmething like that:
@font-face {
    font-family: 'Arial';
    src: url('https://example.com/fonts/arial.woff2') format('woff2'),
         url('https://example.com/fonts/arial.woff') format('woff'),
         url('https://example.com/fonts/arial.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

Hi @andrey.gubal

Thanks for your reply.
Now when I am trying some to use script tag to do some calculation. it is not working as expected.
is there any work around for this?
I have attached the pdf I am getting after conversion and the zip
test7req4.html.zip (2.6 KB)

of htmlfile for this.

testfolder-outputtest7req4.pdf (28.6 KB)

Hi @andrey.gubal
can you please check this above template

Hi @Deepali11 it’s hard to evaluate because probably some parts of the template are missing. We can’t run it. It looks as on screenshot:
image.png (35.9 KB)
On the first check, without debugging, we would expect that this JS code must have been executed. Please try to isolate the problem - create smaller document, maybe without template syntax but with similar JS code and try if conversion works for you. If it doesn’t please send us the document. If works please add template syntax, but perhaps simple one and try again. Alternatively please describe how we can run this template with data and we can try on our end.

Hi @andrey.gubal

testfolder.zip (85.2 KB)

I have attached a zip file. It contains 3 files

  1. input.html file. — It contains a short html script
  2. convertedByAspose.pdf. ------ This is a pdf I generated using aspose from the above html.
  3. expectedOutput -------- This is a screenshot showing what data I expect in the converted pdf.

Can you please check it again

Hi @andrey.gubal
Can you please look into this above query?

Hi @Deepali11 it always takes some time to investigate. Your code doesn’t work because forEach function is not yet supported. If I change to classic for loop it works fine:

<script>
        function initializeCalculations() {
            function calculateCost(basePrice, quantity, weight) {
                return (parseFloat(basePrice) * parseInt(quantity) * parseFloat(weight)).toFixed(2);
            }

            function calculateTotal(cost, tax) {
                return (parseFloat(cost) + parseFloat(tax)).toFixed(2);
            }

            function updateShippingTable() {
                var rows = document.querySelectorAll('.shipping-table tbody tr');
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    var basePrice = row.querySelector('.base-price').textContent.replace('$', '');
                    var quantity = row.querySelector('td:nth-child(2)').textContent;
                    var weight = row.querySelector('.weight').textContent;
                    var tax = row.querySelector('.tax').textContent.replace('$', '');

                    // Calculate and update cost
                    var cost = calculateCost(basePrice, quantity, weight);
                    row.querySelector('.cost-value').textContent = cost;

                    // Calculate and update total
                    var total = calculateTotal(cost, tax);
                    row.querySelector('.total-value').textContent = total;
                }
            }

            updateShippingTable(); // Call function to update table values
        }
    </script>

Hi @andrey.gubal,

Thanks for resolving this query! It’s working now.

I want to run this HTML module docker image in my on-premise Node.js project. Could you please share the details for setting it up?