Display Image stored in a sharepoint Site, on a pdf that i want to export

Fetching Image from SharePoint URL for PDF Generation Results in 401 Error Despite Azure App Permissions

I am trying to fetch an image stored in SharePoint by its URL and embed it into a PDF that I generate using JavaScript. When I fetch the image in my browser (while logged into my Microsoft account), it works fine. However, when I attempt to export the PDF, the image does not display.

To resolve this, I tried using an Azure app for authentication. I granted the app Sites.Read.All and Files.Read.All permissions, but I am still getting a 401 Unauthorized error when trying to fetch the image.

Here’s what I’ve tried so far:

1. Fetching the image in the browser (works):

fetch('https://<sharepoint-site>/<image-url>')
  .then(response => response.blob())
  .then(blob => {
    // Process the image
  });

2. Using Azure app authentication (fails with 401):

const token = await getAccessToken(); // Function to get token using Azure AD
fetch('https://<sharepoint-site>/<image-url>', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
})
  .then(response => {
    if (!response.ok) throw new Error('Network response was not ok');
    return response.blob();
  })
  .then(blob => {
    // Process the image
  })
  .catch(error => console.error('Error fetching image:', error));

3. Azure App Permissions:

  • Sites.Read.All
  • Files.Read.All

Screenshot of API permissions for the Azure APP
Despite these permissions, I am still encountering a 401 Unauthorized error. Am I missing something in the authentication process or the permissions setup?

Additional Context:

  • I am using Microsoft Graph API for authentication.
  • The SharePoint site and image are accessible when I am logged in via the browser.
  • The PDF generation library I am using is html2pdf.

Any help or guidance on resolving this issue would be greatly appreciated!