Getting unauthorized error while converting html to pdf with newly generated token

Getting following error while uploading html file.
{
“requestId”: “3b35fba3-cbfd-40a2-8ddb-e9f6549c5db9”,
“error”: {
“code”: “authorizationError”,
“message”: “Unauthorized”,
“description”: “Operation Failed. The authorization data is incorrect.”,
“dateTime”: “2025-04-10T18:03:07.1366997Z”,
“innerError”: null
}
}

Even for other apis also it is giving the same error.

I am able to generate new token with the token api and using that.
But still it is giving error.

Hi @Deepali11 it can be as it says. Please check this page Local File Conversion – Aspose.HTML Cloud . It has examples in C# and Javascript on how to upload file and run conversion of programatically uploaded file . Also it has a link to the page with guidance for authorisation that might be an issue in your case.

Hi @andrey.gubal

It is intermittent issue on your side.
I have not made any changes in my code.
But it starts failing some times.
right now it is failing in my code and also in postman for same error.

It will be a big problem for us if it keeps on happening intermittently in production environment.
Can you please look into this and fix this.
image.png (277.8 KB)

res: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: ‘1.1’,
complete: false,
rawHeaders: [Array],
rawTrailers: [],
joinDuplicateHeaders: undefined,
aborted: true,
upgrade: false,
url: ‘’,
method: null,
statusCode: 401,
statusMessage: ‘Unauthorized’,
client: [TLSSocket],
_consuming: true,
_dumped: false,
req: [Circular *1],
responseUrl: ‘https://api.aspose.cloud/v4.0/html/file?path=/htmlfolder’,
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 12,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0
},

Hi @andrey.gubal

Can you please check this we are blocked in prod env since yesterday.
Html to pdf conversion is not working at all.

Hi @Deepali11 please check if it works now for you. Also just for future testing there is an alternative way for conversion without uploading a file but just by passing content of the file to conversion api - HTML Content to PDF – Aspose.HTML Cloud

Hi @andrey.gubal

It is working now
What was the issue and will it be frequent.
We have added html to pdf functionality in prod env and facing lot of difficulties due to these errors.

It has happened lot of time in last 2 days.
Please update

@Deepali11 There was some instability with storage where you upload files to. Not directly connected to conversion functionality. As for now it is adjusted and it didn’t happen before with the storage, so we don’t expect it can be back.

Okay
But I was getting unauthorized error in logs.

Is there any difference in latency when we directly pass content to conversion api as write now it is taking approx 3 sec to convert.

Hi @Deepali11 there are several factors. I sent you simplified “sync” version of the api. It means that it includes not only conversion but also status check every second. So it does 3 things: 1) start conversion, 2) Check status until completed, 3) Download result for you. Each step may have own latency. There is also async version where you do those steps yourself. Please check this article https://docs.aspose.cloud/html/convert-html-to-pdf/ It starts from describing “sync” and “async” conversions in API. In general latency more depends on the document, size and complexity, than on the approach in conversion.

Hi @andrey.gubal,

We are still seeing unauthorized errors in the logs. Could you please share an ETA for when this issue will be resolved?

Hi @irpachidpw we would need more details please. Do you get it in REST api or you use SDK? If in REST then does generating a new token help? Also could you please give us a sequence of calls that you do to API to convert HTML to PDF. Which approach you use - sync or async API; you upload file to storage first or you convert by URL or as HTML content or as base64? We could not replicate your problem but if you share details we can try to do the same.

Hi @andrey.gubal

Latency is very high.For very simple and small html file.
This sync api is taking 7 seconds time.

Handlebars Test

Handlebars Iteration Test

<ul>
    <li>
        <strong>First Item:</strong> 
        
        <strong>Index 0:</strong> abc
    </li>
    <li>
        
        
        <strong>Index 1:</strong> xyz
    </li>
    <li>
        
        <strong>Last Item:</strong> 
        <strong>Index 2:</strong> 123
    </li>
</ul>

Adding my code for ur reference
const api = require(‘@asposecloud/aspose-html-cloud’);
const path = require(“path”);
const fs = require(“fs”);

// Auth Configuration
const conf = {
basePath: “https://api.aspose.cloud/v4.0”,
authPath: “https://api.aspose.cloud/connect/token”,
apiKey: “xxxxxxxxxxxxxxx”,
appSID: “xxxxxxxxxxxxxxxxxxx”,
defaultUserAgent: “NodeJsWebkit”
};

// Create Conversion API object
const conversionApi = new api.ConversionApi(conf);

// Define input and output paths
const inputHtmlPath = path.join(__dirname, “outputhtml/outputtest7req4.html”);
const outputPdfPath = path.join(__dirname, “outputpdf/asposecloud_testreq41df.pdf”);

// Optional options
const opts = null;

// Latency Logging Start
const startTime = Date.now();

conversionApi.convertLocalToLocal(inputHtmlPath, outputPdfPath, opts, function (error, data, response) {
const endTime = Date.now();
const latencyMs = endTime - startTime;
console.log(‘dat==’, data);
console.log(‘response==’, response);
if (error) {
console.error(" Conversion failed:“, error.message);
} else {
console.log(” Conversion succeeded!“);
console.log(” Output file saved to:", outputPdfPath);
}

console.log(`Latency: ${latencyMs} ms`);

});
Can you please suggest if any changes are required or how to improve this

Hi @Deepali11 Ok, let us check this. Maybe we will give your alternative recommendations because api that you are using involves many calls under the hood and most likely it’s not the conversion that takes most of the time. From the other hand conversion process is not supposed to be instant. Usually our clients either display progress bar giving some time for the file to generate, especially for bigger documents or use previously pregenrated files. Anyway, we will take a look and I’ll get back to you.

Hi @Deepali11 so regarding latency. You use sdk that incapsulates all the code. Here is an example that uses our REST API https://docs.aspose.cloud/html/rest-api-overview/:

const axios = require('axios');
const fs = require('fs');
const path = require('path');
const FormData = require('form-data');

// === CONFIGURATION ===
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const apiUrl = 'https://api.aspose.cloud';
const inputHtmlPath = path.join(__dirname, "outputhtml/outputtest7req4.html");
const outputPdfPath = path.join(__dirname, "outputpdf/asposecloud_testreq41df.pdf");

async function processHtmlToPdf() {
    try {
        // === STEP 1: Get Bearer Token ===
        console.log('Getting bearer token...');
        const tokenResponse = await axios.post(`${apiUrl}/connect/token`, 
            new URLSearchParams({
                grant_type: 'client_credentials',
                client_id: clientId,
                client_secret: clientSecret
            }),
            {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }
        );
        const token = tokenResponse.data.access_token;
        console.log('Token received.');

        // === STEP 2: Upload HTML File ===
        console.log('Uploading HTML file...');
        const form = new FormData();
        form.append('file', fs.createReadStream(inputHtmlPath), path.basename(inputHtmlPath));

        const uploadResponse = await axios.post(`${apiUrl}/v4.0/html/file`, form, {
            headers: {
                Authorization: `Bearer ${token}`,
                ...form.getHeaders()
            }
        });

        const uploadedPath = uploadResponse.data.path;
        console.log('File uploaded. Path on server:', uploadedPath);

        // === STEP 3: Convert Uploaded HTML to PDF ===
        console.log('Converting HTML to PDF...');
        const conversionResponse = await axios.post(`${apiUrl}/v4.0/html/conversion/html-pdf/sync`, 
            {
                InputPath: uploadedPath
            },
            {
                headers: {
                    Authorization: `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                responseType: 'arraybuffer' // So we can write the binary data to file
            }
        );

        fs.writeFileSync(outputPdfPath, conversionResponse.data);
        console.log('PDF saved at:', outputPdfPath);

    } catch (error) {
        console.error('Error occurred:', error.response ? error.response.data : error.message);
    }
}

processHtmlToPdf();

So we split getting API token, uploading file to storage, running conversion. We could split conversion to even more steps (start, status, getting result), but let’s keep it like this for simplicity.
In this example we get:
Token fetched in 3380 ms.
File upload took 500 ms.
HTML to PDF conversion completed in 525 ms.

So conversion itself takes not that long. Getting token takes most of the time. It can’t be changed unfortunately, but token can be reused until it is expired Authorization – Aspose.HTML Cloud.

Main point - conversion is not supposed to be instant. It may take time. Of course it depends on the document size and complexity. So depending on your use case it make sense consider implementing progress for conversion.

Hi @andrey.gubal

Thanks for your clarification.
Right now I am facing lot of intermittent Auth issue while converting html to pdf.
Previously you told - There was some instability with storage where you upload files to.

Is this issue still there?
As out of 5 calls 2 of them are failing for me with Auth error.

Hi @andrey.gubal,

Html to pdf conversion api is giving 504 status code.
Also This issue is not logged on https://status.aspose.cloud/

Please check

image.png (217.7 KB)

Sharing the curl for my request.
curl --location ‘https://api.aspose.cloud/v4.0/html/conversion/HTML-PDF/sync
–header ‘Accept: application/json’
–header ‘authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE3NDYxODU1MDksImV4cCI6MTc0NjE4OTEwOSwiaXNzIjoiaHR0cHM6Ly9h’
–header ‘Content-Type: application/json’
–data ‘{
“inputPath”: “/testfolder/testsmall.html”,
“outputFile”: “/testfolder/test-templatesmall.pdf”
}’

This file is already present in my storage account.
Apart from this when I am directly passing html tring to this api that is also not working.
Please check

Hi @Deepali11 it was fixed. Must be ok now

Hi @andrey.gubal
It is working now.
can you please share RCA for this issue.
Why it was not working since last 3 days
Also this issue was not logged in https://status.aspose.cloud/.

Hi, this is internal thing, not directly related to your account. Status shows general api status. Here it had certain conditions which are not visible for status unfortunately