A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Hello,
That's a limitation. Office COM automation is not supported under non-interactive contexts like Windows services on a server. In that scenario Word.Application and Excel.Application often fail with E_ACCESSDENIED even if you tweak DCOM and folder ACLs, and any workaround you get working will be brittle.
The official way to do server-side DOCX/XLSX-to-PDF is to stop using Microsoft.Office.Interop and call Microsoft Graph to fetch a PDF rendition from OneDrive or SharePoint, which uses the Office for the web renderer.
Put the file in OneDrive or a SharePoint document library, grant your app access (app-only via Entra ID with Sites.Selected or Files.Read.All as appropriate), and download the PDF stream from the Graph endpoint /drives/{driveId}/items/{itemId}/content?format=pdf.
Here is a minimal .NET 8 sample using MSAL and HttpClient with client-credentials. It works for both Word and Excel files and writes the PDF to disk:
using System.Net.Http.Headers;
using Microsoft.Identity.Client;
static async Task ConvertViaGraphAsync(
string tenantId,
string clientId,
string clientSecret,
string driveId, // OneDrive or SharePoint drive ID
string itemId, // The file item ID in that drive
string outputPdfPath) // Local path for the PDF
{
var app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithTenantId(tenantId)
.Build();
var token = await app
.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" })
.ExecuteAsync()
.ConfigureAwait(false);
using var http = new HttpClient();
var url = $"https://graph.microsoft.com/v1.0/drives/{driveId}/items/{itemId}/content?format=pdf";
using var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
using var res = await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
res.EnsureSuccessStatusCode();
await using var fs = File.Create(outputPdfPath);
await res.Content.CopyToAsync(fs).ConfigureAwait(false);
}
This avoids launching Office on the server and runs happily under a service account. You will need the file to live in OneDrive or SharePoint and the tenant must have licenses that include Office for the web so Graph can render the PDF.
If you want, tell me where your files live today and I will map that to the exact driveId and itemId you should call.