Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To download a PDF from a REST API, send the documented HTTP request, verify the response status and media type, then write the response body as binary bytes. Never decode a raw PDF as text or assume a .pdf URL proves that the response is a PDF. For large documents, stream chunks to disk instead of buffering the entire body in memory.

What a PDF download actually is

A REST endpoint can return a PDF as the complete HTTP response body. A typical successful response has a 2xx status and Content-Type: application/pdf. The body is binary data beginning with the PDF signature, commonly %PDF-. Your client should treat it as bytes from the first read through the final write.

Some APIs instead return JSON containing a URL or a base64-encoded field. That is a different contract: parse the JSON, obtain the designated field, and decode it only when the API documentation says to do so. Do not attempt base64 decoding on a response whose contract is raw PDF bytes.

Choose the right download method

Situation Recommended approach Why
Public endpoint, no custom headers Browser navigation or a normal link The server can control download behavior with response headers.
Bearer token, API key header, or other custom authentication Backend/script request, or browser Fetch A plain link cannot reliably add arbitrary authorization headers.
Small PDF Read the body and write binary data Simple, but memory use grows with file size.
Large or unpredictable PDF Stream chunks to a file Limits memory use and lets you consume the response progressively.
API returns JSON/base64 Parse JSON, then decode the documented field The response is not a raw PDF representation.

Headers that control type and filename

Content-Type

The server should label a known PDF representation with Content-Type: application/pdf. If the header is missing, a client may treat the data as generic binary (application/octet-stream) or inspect the bytes. Check the status and headers before saving; a response called report.pdf can still contain an HTML login page or a JSON error.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Epson Workforce ES-50 Compact & Lightweight Mobile Document Scanner
  • PORTABLE SCANNER FOR USE ON-THE-GO — The fastest and lightest mobile single-sheet-fed compact document scanner in its class¹
  • QUICK DOCUMENT SCANNING ― This Epson ultra-fast scanner scans a single page as quickly as 5.5 seconds²; Windows and Mac compatible
  • VERSATILE PAPER HANDLING ― Portable scanner scans documents up to 8.5 x 72 in; Also easily digitizes receipts and ID cards to make accounting, bookkeeping, and organizing simpler
  • INTUITIVE, HIGH-SPEED SOFTWARE — Epson ScanSmart Software³ is a smart tool allowing you to easily scan, review, and save; Stay organized easily with the help of this Epson scanner
  • EASY SETUP — USB-powered connect to your computer for quick and simple scanning; No batteries or external power supply required to operate portable document scanner; Standard Connectivity: USB 2.0

Content-Disposition

Content-Disposition: attachment; filename="report.pdf" asks a user agent to save the payload and suggests a filename. inline indicates normal in-browser processing instead. A filename* parameter supports encoded characters; when both filename* and filename are present, clients should prefer filename*.

Treat every server filename as advisory. Remove directory components, control characters, and platform-reserved names; choose a safe extension based on the verified media type. Never allow a header value to decide an unrestricted filesystem path.

Download with cURL

Use -f so HTTP errors fail, and -L to follow redirects when the API requires them. --output writes bytes without terminal encoding.

curl -fL 
  -H "Authorization: Bearer TOKEN" 
  -H "Accept: application/pdf" 
  "https://api.example.com/reports/123.pdf" 
  --output report-123.pdf

To inspect headers before committing to a file, use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Brother DS-640 Compact Mobile Document Scanner, (Model: DS640)
  • FAST SPEEDS - Scans color and black and white documents a blazing speed up to 16ppm (1). Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • ULTRA COMPACT – At less than 1 foot in length and only about 1. 5lbs in weight you can fit this device virtually anywhere (a bag, a purse, even a pocket).
  • READY WHENEVER YOU ARE – The DS-640 mobile scanner is powered via an included micro USB 3. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan.
  • WORKS YOUR WAY – Use the Brother free iPrint&Scan desktop app for scanning to multiple “Scan-to” destinations like PC, Network, cloud services, Email and OCR. (2) Supports Windows, Mac and Linux and TWAIN/WIA for PC/ICA for Mac/SANE drivers. (3)
  • OPTIMIZE IMAGES AND TEXT – Automatic color detection/adjustment, image rotation (PC only), bleed through prevention/background removal, text enhancement, color drop to enhance scans. Software suite includes document management and OCR software. (4)
curl -i 
  -H "Authorization: Bearer TOKEN" 
  "https://api.example.com/reports/123.pdf"

Look for a successful status, the final URL after redirects, Content-Type, and (if supplied) Content-Disposition. Avoid printing the PDF body to a terminal.

Download with Python Requests

Small response

import requests

url = "https://api.example.com/reports/123.pdf"
response = requests.get(
    url,
    headers={"Authorization": "Bearer TOKEN"},
    timeout=(5, 60),
)
response.raise_for_status()

content_type = response.headers.get("Content-Type", "")
if "application/pdf" not in content_type.lower():
    raise ValueError(f"Expected a PDF, received {content_type!r}")

with open("report-123.pdf", "wb") as output:
    output.write(response.content)

raise_for_status() must run before writing. Otherwise a 401, 404, or 500 body can be saved with a .pdf suffix.

Large response: stream in chunks

import requests

url = "https://api.example.com/reports/123.pdf"
with requests.get(
    url,
    headers={"Authorization": "Bearer TOKEN"},
    stream=True,
    timeout=(5, 60),
) as response:
    response.raise_for_status()
    content_type = response.headers.get("Content-Type", "")
    if "application/pdf" not in content_type.lower():
        preview = response.raw.read(200, decode_content=True)
        raise ValueError(f"Expected PDF, received {content_type!r}: {preview!r}")

    with open("report-123.pdf", "wb") as output:
        for chunk in response.iter_content(chunk_size=64 * 1024):
            if chunk:
                output.write(chunk)

stream=True delays body retrieval; iter_content writes each nonempty chunk. The context manager closes the response, allowing the connection to be reused or released even when an exception occurs.

Download with Node.js

In modern Node.js, Fetch exposes a Web stream. Convert each chunk to a Buffer and write it incrementally so a large PDF does not occupy one giant in-memory buffer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
  • STAY ORGANIZED – Easily convert your paper documents into digital formats like searchable PDF files, JPEGs, and more.Power Consumption : 2.5W or less (Energy Saving Mode: 0.7W). Suggested Daily Volume : 500 scans..Does it contain liquid: no
  • CONVENIENT AND PORTABLE –lightweight and small in size, you can take the scanner anywhere from home offices, classrooms, remote offices, and anywhere in between
  • HANDLES VARIOUS MEDIA TYPES – Digitize receipts, business cards, plastic or embossed cards, reports, legal documents, and more
  • FAST AND EFFICIENT – No technical hurdles or complicated setups here; easily scan both sides of a document at the same time, in color or black-and-white, at up to 12 pages-per-minute, and with a 20 sheet automatic feeder
  • BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer
import { createWriteStream } from "node:fs";
import { once } from "node:events";

const url = "https://api.example.com/reports/123.pdf";
const response = await fetch(url, {
  headers: { Authorization: "Bearer TOKEN", Accept: "application/pdf" },
  redirect: "follow"
});

if (!response.ok) {
  const errorText = await response.text();
  throw new Error(`HTTP ${response.status}: ${errorText.slice(0, 500)}`);
}
if (!(response.headers.get("content-type") || "").toLowerCase().includes("application/pdf")) {
  throw new Error(`Unexpected Content-Type: ${response.headers.get("content-type")}`);
}
if (!response.body) throw new Error("Response has no body");

const output = createWriteStream("report-123.pdf");
try {
  for await (const chunk of response.body) {
    if (!output.write(Buffer.from(chunk))) await once(output, "drain");
  }
  output.end();
  await once(output, "close");
} catch (error) {
  output.destroy();
  throw error;
}

For a small file, const bytes = Buffer.from(await response.arrayBuffer()); followed by writeFile is simpler, but it buffers the complete document.

Browser downloads

Direct navigation

If the endpoint is public (or the user is already authenticated through the site) and needs no custom request header, link directly to it:

<a href="https://api.example.com/reports/123.pdf">Download report</a>

The browser may display the PDF or download it depending on response headers, browser settings, and built-in PDF handling. Content-Disposition: attachment is the server-side signal for a download.

Fetch with authentication

async function downloadPdf() {
  const response = await fetch("https://api.example.com/reports/123.pdf", {
    headers: {
      Authorization: "Bearer TOKEN",
      Accept: "application/pdf"
    }
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);

  const type = (response.headers.get("Content-Type") || "").toLowerCase();
  if (!type.includes("application/pdf")) {
    throw new Error(`Expected PDF, received ${type}`);
  }

  const blob = await response.blob();
  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = objectUrl;
  link.download = "report-123.pdf";
  document.body.appendChild(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(objectUrl);
}

This approach requires the API’s CORS policy to permit the browser origin and request headers. Keep long-lived secrets out of frontend code; proxy the request through your backend when the credential must remain private.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
  • IRIScan Express, portable scanner : scans color and black and white documents a blazing speed up to 8ppm simplex. Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • IRIScan Express mobile scanner is powered via an included micro USB 2. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan. USB cable provided. AC Adapter not provided and not needed.
  • IRIScan flatbed scanner uses a simplex scanning mode allows for quick and straightforward scanning of single-sided documents. IRIScan with its full portable features is the ideal document scanners for computers.
  • IRIScan document scanner : Versatile scanning capabilities, including scanning to Word, PDF, and Excel formats with companion software provided Readiris OCR
  • Receipt scanner and card scanner with Additional features include scanning business cards directly to Outlook, photo scanning, and receipt scanning for efficient document management

Validation, retries, and safe filenames

  • Check the final status after redirects and authenticate exactly as the API specifies.
  • Check Content-Type; for high-assurance workflows, inspect the first bytes for the PDF signature.
  • Use a connect/read timeout appropriate to the document size. A timeout is not proof that the server failed; retry only when the operation is safe and the API permits it.
  • Write to a temporary file, then rename it after the transfer completes. This prevents consumers from opening a partial document.
  • For resumable downloads, use HTTP range requests only when the server advertises and correctly supports them; otherwise restart the transfer.
  • Sanitize names from Content-Disposition. Generate your own fallback such as report-123.pdf.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

The saved file is JSON or HTML

Inspect the status, final URL, Content-Type, and a short body preview. Common causes are an expired token (401/403), a missing route (404), rate limiting (429), an API error (5xx), or an HTML login page after a redirect. Call raise_for_status() or check response.ok before writing.

The PDF is empty or truncated

Ensure the streamed response is fully consumed and closed. Increase the read timeout for slow servers, check proxy limits, and write to a temporary path until completion. A process killed during transfer leaves a partial file.

The browser ignores the filename

Inspect Content-Disposition, including an encoded filename*. Browser behavior can also depend on built-in PDF viewers and user settings. A Fetch-based download lets your application provide a sanitized client-side name.

Authentication works in code but not in a link

A normal navigation cannot reliably attach an Authorization header. Use Fetch with an appropriate CORS policy or make the request on your server and return the resulting file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
  • Scanner type: Document
  • Connectivity technology: USB
  • With Auto Scan Mode, the scanner automatically detects what you're scanning
  • Digitize documents and images

The endpoint returns base64 in JSON

Parse the documented property, decode it, and write the resulting bytes. Do not treat the entire JSON document as PDF data. Base64 increases payload size and requires more memory unless your platform provides a streaming decoder.

Or skip the browser setup

If the PDF you need is a rendered webpage rather than an API-generated document, ScreenshotNeo returns a PDF from one API call. It accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server provides capture_pdf, take_screenshot, and get_page_info tools for Claude, Cursor, and other MCP clients.

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

See the ScreenshotNeo documentation for PDF paper size, margins, orientation, page ranges, authentication, waiting, cookies, and other options. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Operational checklist

  1. Read the endpoint contract: method, authentication, query parameters, and whether it returns raw PDF bytes or JSON.
  2. Send the request with an explicit timeout and the required headers.
  3. Verify status and media type before creating the final output.
  4. Stream large bodies and consume or close the response.
  5. Write in binary mode, preferably to a temporary file.
  6. Sanitize any server-provided filename and validate the completed file.
  7. Log status, size, timing, and a request identifier without logging access tokens or document contents.

Frequently Asked Questions

Can I use a PDF URL with a GET request?

Yes, if the API documents GET and the URL supplies all required authentication and parameters. A URL ending in .pdf alone does not guarantee a PDF response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I check the file extension or Content-Type?

Check the HTTP status and Content-Type first; for sensitive workflows, also inspect the PDF signature. Treat extensions as naming hints, not proof.

When should I stream a download?

Stream when the PDF is large, its size is unknown, or your service handles concurrent downloads. Buffering is acceptable only when memory limits and document sizes are predictable.

The Bottom Line

Request the documented endpoint, check the status and Content-Type, and save the response body as binary bytes. Stream large responses, sanitize filenames, and investigate the response whenever a supposed PDF contains JSON or HTML.

Quick Recap

Bestseller No. 3
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer; This product is not intended for scanning photographs on photo paper / photographic media
$184.00
Bestseller No. 4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
Find our Software here : irislink.com/start; IRIScan Express is only compatible Windows platform and not macintosh
$129.00
Bestseller No. 5
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Scanner type: Document; Connectivity technology: USB; With Auto Scan Mode, the scanner automatically detects what you're scanning
$75.00

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.