ScreenshotNeo

BlogHTML to image & PDF

How to Convert Word Documents to PDF With an API

Convert DOC and DOCX files to PDF with Adobe PDF Services, Aspose.Words Cloud, or Microsoft Graph, including code, permissions, errors, and production guidance.

By the ScreenshotNeo team1 October 20267 min read

To convert a Word document to PDF with an API, send the DOC or DOCX file to a documented conversion endpoint and save the returned PDF bytes. Adobe PDF Services and Aspose.Words Cloud provide direct document-conversion APIs. Microsoft Graph can return PDF content for supported Word files already stored as a Graph-accessible driveItem.

The right route depends on where the file lives, how you authenticate, whether you need the PDF returned immediately or saved to cloud storage, and which document operations your application already uses.

Choose the conversion route

Route Best fit Input model Key implementation detail
Adobe PDF Services Applications already using Adobe document services or needing several PDF operations Upload an asset, then call the Create PDF operation REST flow uses an API key, bearer token, and asset identifier
Aspose.Words Cloud Direct Word conversion with a REST or SDK workflow Multipart document content, or a file in cloud storage Documented operation is PUT /v4.0/words/convert?format=pdf
Microsoft Graph The DOC or DOCX already lives in OneDrive or SharePoint Address a Graph driveItem Request the driveItem content in PDF format with the required Graph permissions

Documentation: Adobe Create PDF, Aspose Word to PDF, and Microsoft Graph format conversion.

Implementation checklist

  1. Confirm the source is actually DOC or DOCX and record its size, page count, fonts, images, and layout features.
  2. Choose whether to upload bytes to a conversion service or address a file already stored in Graph.
  3. Create credentials and grant only the permissions documented for that service.
  4. Keep API keys, client secrets, and bearer tokens on your server; never embed them in browser JavaScript.
  5. Send the conversion request and treat the response as binary PDF data unless the endpoint documents a saved-file response.
  6. Validate the response status and content type before writing the file.
  7. Test representative documents: plain text, tables, headers and footers, page breaks, embedded fonts, images, and unusual layouts.
  8. Before production, verify current pricing, quotas, maximum file size and page count, regions, retention terms, and API version in the provider’s live documentation.

Aspose.Words Cloud: direct DOCX-to-PDF request

Aspose documents a multipart Word-to-PDF operation using bearer authorization. The following example sends a local file and writes the response as a PDF.

cURL

curl -X PUT "https://api.aspose.cloud/v4.0/words/convert?format=pdf" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: multipart/form-data" \
  -F "document=@./input.docx" \
  -o output.pdf

Python

import requests

with open("input.docx", "rb") as source:
    response = requests.put(
        "https://api.aspose.cloud/v4.0/words/convert",
        params={"format": "pdf"},
        headers={"Authorization": "Bearer YOUR_ACCESS_TOKEN"},
        files={"document": ("input.docx", source, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")},
        timeout=120,
    )
response.raise_for_status()
with open("output.pdf", "wb") as target:
    target.write(response.content)

Node.js

import fs from "node:fs";

const form = new FormData();
form.append("document", new Blob([fs.readFileSync("input.docx")]), "input.docx");
const response = await fetch("https://api.aspose.cloud/v4.0/words/convert?format=pdf", {
  method: "PUT",
  headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN" },
  body: form
});
if (!response.ok) throw new Error(`Conversion failed: ${response.status}`);
fs.writeFileSync("output.pdf", Buffer.from(await response.arrayBuffer()));

Adobe PDF Services: asset-based conversion

Adobe’s documented REST flow creates an input asset, then invokes the Create PDF operation with the asset identifier. Authentication uses an API key and bearer token. Follow Adobe’s current asset-upload and job-response schema rather than assuming a response shape.

# The exact upload and job URLs depend on Adobe's current REST reference.
# Conceptual request shape:
curl -X POST "ADOBE_CREATE_PDF_ENDPOINT" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"assetID":"YOUR_UPLOADED_ASSET_ID"}'

After the operation completes, retrieve the PDF asset URL or binary response documented for your API version. Store the resulting bytes using a Content-Type of application/pdf.

Microsoft Graph: convert a stored driveItem

Graph is useful when the source already resides in OneDrive or SharePoint. The v1.0 driveItem content endpoint supports requesting PDF output for DOC and DOCX among other source extensions. The application and, where applicable, the container must have the required Graph permissions.

cURL

curl -L "https://graph.microsoft.com/v1.0/drives/DRIVE_ID/items/ITEM_ID/content?format=pdf" \
  -H "Authorization: Bearer YOUR_GRAPH_ACCESS_TOKEN" \
  -o output.pdf

Python

import requests

url = "https://graph.microsoft.com/v1.0/drives/DRIVE_ID/items/ITEM_ID/content"
r = requests.get(
    url,
    params={"format": "pdf"},
    headers={"Authorization": "Bearer YOUR_GRAPH_ACCESS_TOKEN"},
    timeout=120,
)
r.raise_for_status()
with open("output.pdf", "wb") as f:
    f.write(r.content)

Node.js

import fs from "node:fs";

const q = new URLSearchParams({ format: "pdf" });
const response = await fetch(
  `https://graph.microsoft.com/v1.0/drives/DRIVE_ID/items/ITEM_ID/content?${q}`,
  { headers: { Authorization: `Bearer ${process.env.GRAPH_ACCESS_TOKEN}` } }
);
if (!response.ok) throw new Error(`Graph conversion failed: ${response.status}`);
fs.writeFileSync("output.pdf", Buffer.from(await response.arrayBuffer()));

Handling input and output safely

  • Determine the format from the trusted upload metadata and file signature; do not rely only on a user-supplied extension.
  • Use streaming uploads and downloads for large documents where the SDK or endpoint supports them.
  • Use a unique output name and write to a temporary location before moving the completed PDF into durable storage.
  • Check the HTTP status before saving bytes. An API error body can otherwise be written to a file named .pdf.
  • Check the returned media type and, when practical, verify the PDF header begins with %PDF-.
  • Delete temporary source and output files according to your retention policy.
  • Log request identifiers, duration, source size, and status without logging document contents or secrets.

Layout fidelity and validation

Successful HTTP status does not prove that a PDF matches your business requirements. Compare representative outputs for fonts, line wrapping, tables, headers, footers, images, hyperlinks, page breaks, tracked changes, and fields. Documents that depend on unavailable fonts or unusual Word features deserve explicit acceptance tests. The provider documentation establishes supported operations and formats; it does not provide a universal fidelity ranking.

Performance, reliability, and cost

  • Performance: conversion time varies with file size, embedded media, page count, and service load. Measure your own representative files.
  • Retries: retry transient network failures and documented 5xx responses with exponential backoff and a bounded attempt count. Do not blindly retry authentication or validation errors.
  • Idempotency: assign an internal job ID and record the source hash so a client retry does not create duplicate business records.
  • Timeouts: set a client timeout long enough for large files, then move long-running work to a queue when synchronous requests are unreliable.
  • Cost: check current provider pricing, quotas, file limits, regions, and retention terms before committing. Those values can change and were not established by this documentation review.
  • Security: use TLS, least-privilege permissions, secret storage, malware scanning where required by your workflow, and access-controlled output URLs.

Troubleshooting

Symptom Likely cause Fix
401 or 403 Expired token, wrong API key, or missing permission Refresh credentials, confirm the endpoint’s auth headers, and grant only the documented permission set.
400 or validation error Wrong multipart field, unsupported extension, malformed JSON, or missing parameter Compare the request byte-for-byte with the provider’s current example and confirm the source format.
HTML or JSON saved as a PDF Error response was written without checking status Call raise_for_status() or inspect response.ok before writing bytes.
Graph item not found Incorrect drive or item ID, or the app cannot access the container Resolve the item through Graph first and verify tenant, drive, and container permissions.
Missing fonts or shifted layout Conversion environment lacks a font or does not reproduce a Word-specific feature Embed permitted fonts, simplify unsupported features, and validate with representative files.
Timeouts on large files Synchronous request is too long or client timeout is too short Increase the bounded timeout, stream data, or submit work through a queue if the provider offers an asynchronous workflow.
Duplicate conversions after retry Client retried after an unknown network outcome Use a job key or source hash and reconcile completed outputs before creating another job.

Or skip the browser setup

If your next step is turning the resulting PDF or its source pages into screenshots, ScreenshotNeo provides a single screenshot API call. See the ScreenshotNeo documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Before capture, cookie and consent banners, newsletter popups, and chat widgets are removed. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the page verdict and billing status. ScreenshotNeo also has an MCP server for AI agents such as Claude and Cursor. The free plan includes 1,000 screenshots each month with no card, and paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account.

FAQ

Can an API convert both DOC and DOCX?

Yes. The documented Adobe, Aspose, and Microsoft Graph routes support Word formats, but verify the exact extension and limits in the current provider reference.

Should I upload the file or use a storage reference?

Upload bytes when your application owns the file and needs an immediate result. Use a storage reference when the document already lives in Graph or the provider’s cloud storage.

Does a successful response guarantee visual fidelity?

No. Run acceptance tests with real documents, especially when fonts, tables, fields, or page layout are important.

Where should conversion run?

Run it on a trusted backend or worker so credentials stay private and large conversions do not block a browser request.