Export Office 365 (SharePoint) Files as Images Programmatically
If your Office files (Word/Excel/PowerPoint) are hosted in SharePoint / OneDrive for Business (Office 365) and you want to export them as images (PNG/JPG) programmatically, the most reliable approach is:
✅ Use Microsoft Graph → Convert to PDF → Convert PDF to Image
Because:
Graph can convert Office docs to PDF reliably
Then Node/NestJS can render PDF pages into PNG/JPG with good quality
1) Architecture Overview (Simple Flow)
SharePoint file (docx/xlsx/pptx)
→ Microsoft Graph: download as PDF
→ NestJS: convert PDF pages → PNG/JPG
→ Store in S3/local/public folder and return URLs
2) Prerequisites (One-time Setup)
✅ Azure App Registration
Azure Portal → App registrations → New
Create a Client Secret
Add Microsoft Graph permissions (Application):
Sites.Read.All (or Files.Read.All)
Grant Admin Consent
You’ll need these environment variables:
AZURE_TENANT_ID=xxxxx
AZURE_CLIENT_ID=xxxxx
AZURE_CLIENT_SECRET=xxxxx3) Get App Token in NestJS (Client Credentials)
import { ConfidentialClientApplication } from "@azure/msal-node";
export class GraphAuthService {
private cca = new ConfidentialClientApplication({
auth: {
clientId: process.env.AZURE_CLIENT_ID!,
authority: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID!}`,
clientSecret: process.env.AZURE_CLIENT_SECRET!,
},
});
async getAppToken(): Promise<string> {
const result = await this.cca.acquireTokenByClientCredential({
scopes: ["https://graph.microsoft.com/.default"],
});
if (!result?.accessToken) throw new Error("No access token");
return result.accessToken;
}
}4) Download SharePoint File as PDF via Graph
This is the key endpoint:
GET /drives/{driveId}/items/{itemId}/content?format=pdf
import axios from "axios";
export class GraphFileService {
constructor(private auth: GraphAuthService) {}
async downloadAsPdf(driveId: string, itemId: string): Promise<Buffer> {
const token = await this.auth.getAppToken();
const url = `https://graph.microsoft.com/v1.0/drives/{itemId}/content?format=pdf`;
const res = await axios.get(url, {
headers: { Authorization: `Bearer ${token}` },
responseType: "arraybuffer",
maxRedirects: 5,
});
return Buffer.from(res.data);
}
}✅ Works for Word / Excel / PowerPoint
⚠️ Large Excel sheets may become multi-page PDFs depending on print layout.
5) Convert PDF → PNG/JPG in Node/NestJS
There are many ways. One stable approach is using Poppler (pdftocairo) on Linux servers.
Install (Ubuntu)
sudo apt-get update
sudo apt-get install -y poppler-utilsConvert PDF buffer to images (example)
You can write the PDF to a temp file, then run pdftocairo.
import { promises as fs } from "fs";
import path from "path";
import { execFile } from "child_process";
import { promisify } from "util";
const execFileAsync = promisify(execFile);
export class PdfToImageService {
async pdfToPngPages(pdfBuffer: Buffer, outDir: string) {
await fs.mkdir(outDir, { recursive: true });
const pdfPath = path.join(outDir, "source.pdf");
await fs.writeFile(pdfPath, pdfBuffer);
// outputs: page-1.png, page-2.png ...
await execFileAsync("pdftocairo", [
"-png",
"-r",
"200",
pdfPath,
path.join(outDir, "page"),
]);
// Return file list
const files = await fs.readdir(outDir);
return files.filter((f) => f.startsWith("page") && f.endsWith(".png"));
}
}You can then:
upload generated images to S3
or serve them from /public
6) Quick Alternative: Graph Thumbnails (Preview Images)
If you just want a quick preview image (not full quality):
GET /drives/{driveId}/items/{itemId}/thumbnails
Graph returns small/medium/large image URLs (if supported).
Final Notes:
✅ SharePoint এর Office file কে programmatically image বানাতে চাইলে—
সবচেয়ে safe method:
Graph → PDF → Image
কারণ Word/Excel/PPT সরাসরি image export সবসময় consistent না, কিন্তু PDF conversion বেশ reliable.
Comments (0)
Login to leave a comment.