Convert PDF to Markdown in Node.js
Three calls and you are done: create a job, poll until it is ready, then download clean Markdown. The example below is plain Node 18+ with the global fetch – no dependencies, no GPU, just the REST API.
Check the output, then use it
Use the live OpenAPI contract. Check HTTP failures, queued/processing/ready/error, a polling deadline and truncated before downloading. Keep API keys server-side.
Server processing; temporary results. Review numbers and OCR mistakes against the original.
Create, poll, download
The PDF to Markdown API is a small job API. You POST a PDF (a URL or an uploaded file) to /api/v2/jobs with your API key, get back a job_id, poll /api/v2/jobs/{job_id} until the status is ready, then download the Markdown from /api/v2/jobs/{job_id}/download. OCR, tables and formulas are handled server-side, so there is nothing to install in your Node app.
The full example
Save as convert.mjs and run node convert.mjs. Replace the key and the PDF URL.
// Node 18+. Keep P2M_API_KEY in the server environment, never in a web page.
import { writeFile } from 'node:fs/promises';
const API = 'https://pdf2md.dev/api/v2';
const key = process.env.P2M_API_KEY;
if (!key) throw new Error('Set P2M_API_KEY');
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
async function request(path, options = {}) {
for (let attempt = 0; attempt < 4; attempt++) {
const r = await fetch(API + path, {
...options,
headers: { Authorization: 'Bearer ' + key, ...options.headers },
signal: AbortSignal.timeout(30000),
});
if (r.status === 429 && attempt < 3) {
const delay = Number(r.headers.get('Retry-After') || 3);
if (!Number.isFinite(delay) || delay > 60) throw new Error('Rate limited; retry later');
await pause(Math.max(1, delay) * 1000);
continue;
}
if (!r.ok) throw new Error('HTTP ' + r.status + ': ' + (await r.text()).slice(0, 300));
return r;
}
}
const created = await (await request('/jobs', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: process.env.PDF_URL || 'https://example.com/document.pdf',
options: { image_mode: 'placeholder', ocr_lang: 'en' } }),
})).json();
if (!created.job_id) throw new Error('Missing job_id');
const deadline = Date.now() + 20 * 60 * 1000;
let job;
while (true) {
job = await (await request('/jobs/' + created.job_id)).json();
if (job.status === 'ready') break;
if (['error', 'canceled', 'deleted'].includes(job.status)) throw new Error('Job ended: ' + job.status);
if (Date.now() >= deadline) throw new Error('Polling deadline reached; the job may still be running');
await pause(3000);
}
const md = await (await request('/jobs/' + created.job_id + '/download')).text();
if (job.truncated) console.warn('Partial result; verify missing pages');
await writeFile('document.md', md, 'utf8');
The Idempotency-Key makes a retried create safe: if the same key is sent twice, you get the same job back instead of a duplicate conversion.
What each call does
Create a job
POST /api/v2/jobs with the API key as a Bearer token and a JSON body of { "url": "..." }. To convert a local file instead, send multipart/form-data with a file field. The response gives a job_id.
Poll until ready
GET /api/v2/jobs/{job_id} returns a status of queued, processing, ready or error. Poll every few seconds until it settles.
Download the Markdown
GET /api/v2/jobs/{job_id}/download returns the Markdown text. Write it to a .md file, hand it to an LLM, or store it for a RAG pipeline.
Errors, retries and big files
Handle failures
processing_timeout, conversion_failed); error_message is safe to log.ready job means a partial result that hit the time budget on a very long document.Scale it up
To convert many PDFs, run the same three calls per file with a small concurrency limit, or switch from polling to webhooks so you are notified when each job is ready. The contract is identical in TypeScript; type the job response and you are set.
Prefer Python or the shell? See the Python tutorial and the cURL recipe.
Building an agent or pipeline?
The same conversion is available as a hosted MCP endpoint, so an AI agent can convert PDFs with no setup. See the developer hub for the full API reference and the OpenAPI spec.
Common questions
Do I need an API key to convert PDFs in Node.js?
Yes, for the REST API you pass an API key as a Bearer token. You can also convert anonymously in the browser or the web app without a key; the API key is for programmatic and automated use.
Which Node.js version do I need?
Node 18 or newer, which ships a global fetch, so the example needs no extra dependencies. On older versions, install a fetch polyfill or use a request library.
How do I convert a local PDF file instead of a URL?
Send a multipart/form-data POST to /api/v2/jobs with the file field set to the PDF, using FormData and a Blob, instead of a JSON body with a url. The rest of the flow (poll, download) is the same.
How do I handle errors and timeouts?
When status is error, read error_code (for example processing_timeout or conversion_failed) and error_message. A long document can finish ready with truncated set to true, meaning a partial result that hit the time budget.
Can I use webhooks instead of polling?
Yes. Polling is simplest to start, but the API also supports webhooks so you are notified when a job is ready instead of polling. See the developer hub for the webhook setup.