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.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Check the HTTP response before giving its body to a PDF converter. Keep the HttpResponseMessage returned by GetAsync or SendAsync, test IsSuccessStatusCode, and only then read PDF bytes or a stream. On a non-2xx response, read a bounded error body, record the status, and return or throw a meaningful application error. This prevents an HTML error page, JSON problem document, CAPTCHA, or empty response from reaching PDF code.

The failure boundary: HTTP first, PDF second

HTTP status and PDF validity answer different questions. IsSuccessStatusCode is true for every status from 200 through 299, not just 200. A 201, 202, 204, or 205 can therefore be successful. However, a 204 normally has no document body, and a 2xx response can still contain malformed or incorrectly labelled content.

PDF processing should begin only after transport handling succeeds. In the success branch, check useful format signals such as the Content-Type value application/pdf and, when appropriate, the file signature. RFC 8118 specifies that PDF files start with the characters %PDF- followed by a version number. Neither a media type nor a filename is proof by itself: servers can mislabel content, so the parser remains the final format check.

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

Use an explicit status branch when you need control

This pattern preserves the response, distinguishes status codes, allows inspection of an error payload, and leaves room for retry or custom result handling.

#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
  • COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
  • ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
  • HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
using System.Net;
using System.Net.Http;

public static async Task<Stream> DownloadPdfAsync(
    HttpClient httpClient,
    Uri uri,
    CancellationToken cancellationToken = default)
{
    using HttpResponseMessage response = await httpClient.GetAsync(
        uri,
        HttpCompletionOption.ResponseHeadersRead,
        cancellationToken);

    if (!response.IsSuccessStatusCode)
    {
        string errorBody = await ReadBoundedTextAsync(
            response.Content,
            maxCharacters: 8_000,
            cancellationToken);

        throw new HttpRequestException(
            $"Document request failed: {(int)response.StatusCode} " +
            $"{response.ReasonPhrase}. {errorBody}",
            inner: null,
            statusCode: response.StatusCode);
    }

    if (response.StatusCode == HttpStatusCode.NoContent)
    {
        throw new InvalidDataException("The server returned 204 No Content; no PDF exists to convert.");
    }

    string? mediaType = response.Content.Headers.ContentType?.MediaType;
    if (!string.Equals(mediaType, "application/pdf", StringComparison.OrdinalIgnoreCase))
    {
        throw new InvalidDataException(
            $"Expected application/pdf but received {mediaType ?? "no Content-Type"}.");
    }

    Stream networkStream = await response.Content.ReadAsStreamAsync(cancellationToken);
    return await CopyAndValidatePdfAsync(networkStream, cancellationToken);
}

private static async Task<string> ReadBoundedTextAsync(
    HttpContent content,
    int maxCharacters,
    CancellationToken cancellationToken)
{
    string text = await content.ReadAsStringAsync(cancellationToken);
    return text.Length <= maxCharacters
        ? text
        : text[..maxCharacters] + "…";
}

private static async Task<Stream> CopyAndValidatePdfAsync(
    Stream source,
    CancellationToken cancellationToken)
{
    await using (source)
    {
        MemoryStream copy = new();
        await source.CopyToAsync(copy, cancellationToken);
        byte[] bytes = copy.ToArray();
        if (bytes.Length < 5 ||
            bytes[0] != (byte)'%' || bytes[1] != (byte)'P' ||
            bytes[2] != (byte)'D' || bytes[3] != (byte)'F' ||
            bytes[4] != (byte)'-')
        {
            copy.Dispose();
            throw new InvalidDataException("The successful response does not start with the PDF signature %PDF-.");
        }

        copy.Position = 0;
        return copy;
    }
}

The example uses ResponseHeadersRead so headers are returned without buffering the entire body. It copies the stream into a seekable MemoryStream because many PDF libraries need seeking. If your library accepts a forward-only stream, pass the response stream directly and dispose it after conversion instead.

Protect logs and exceptions

Error bodies can contain stack traces, account data, tokens, or markup supplied by an attacker. Bound their size, redact secrets, and avoid placing a complete body in a user-facing exception. For structured logging, record the numeric status, reason phrase, request correlation ID, and a safely truncated message.

Use EnsureSuccessStatusCode for exception-only policy

When every non-2xx response should become an exception and the caller does not need the error body, the shorter branch is appropriate:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using HttpResponseMessage response = await httpClient.GetAsync(
    uri,
    HttpCompletionOption.ResponseHeadersRead,
    cancellationToken);

response.EnsureSuccessStatusCode();

if (response.StatusCode == HttpStatusCode.NoContent)
    throw new InvalidDataException("Successful response has no PDF body.");

await using Stream pdfStream = await response.Content.ReadAsStreamAsync(cancellationToken);
// Pass pdfStream to your PDF parser or converter here.

EnsureSuccessStatusCode throws HttpRequestException when the status is outside 200–299. Inspect or copy the error content before calling it if that content is needed; after throwing, the response may no longer be available to your normal result path.

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
  • INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
  • PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
  • ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴

Do not accidentally select a convenience method

GetStringAsync, GetStreamAsync, and GetByteArrayAsync do not return an HttpResponseMessage. They implicitly enforce a successful status and throw for non-2xx responses. That behavior is useful when you want a simple exception policy, but it prevents custom handling of an error body and status unless you catch the exception and recover elsewhere. Choose GetAsync or SendAsync when status-aware handling is part of the design.

Validate the body after the status check

Media type

Read response.Content.Headers.ContentType?.MediaType and normally require application/pdf. Some legacy endpoints omit the header or send a vendor type, so make the policy explicit: strict rejection for a controlled API, or signature validation plus parser validation for an unreliable endpoint.

Signature and parser validation

For byte-oriented code, inspect the first five bytes for %PDF- before conversion. This catches common cases where a proxy returns HTML with a 200 status. It does not prove that the entire file is complete or structurally valid; let the PDF library validate cross-reference tables, trailers, encryption, and page objects.

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

Content length and empty success responses

An empty body is not a usable PDF even when the status is 200. Treat a known zero Content-Length, an empty stream, or a parser “no pages” error as a document failure. Chunked responses may not provide a length, so check the bytes actually read.

Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
  • INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
  • KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster
  • THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.

Network failures are not HTTP error statuses

DNS failures, connection refusal, TLS errors, cancellation, and timeouts can throw before an HTTP response exists. There is then no status code or error body to inspect. Catch HttpRequestException, TaskCanceledException (while distinguishing caller cancellation from a configured timeout), and PDF-specific exceptions separately so diagnostics identify the failing layer.

try
{
    await DownloadPdfAsync(client, uri, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
    // The caller cancelled; do not retry automatically.
    throw;
}
catch (HttpRequestException ex)
{
    // Transport failure or an HTTP status rejected by your branch.
    logger.LogWarning(ex, "Document HTTP request failed for {Uri}", uri);
    throw;
}
catch (InvalidDataException ex)
{
    // A successful HTTP response was not a usable PDF.
    logger.LogError(ex, "Document payload was not a valid PDF");
    throw;
}

Retries: only retry the right failures

Retry policy belongs around the HTTP operation, not around PDF conversion. A transient 408, 429, or selected 5xx response may be retryable according to the service contract; a 400, 401, 403, 404, or a deterministic malformed PDF generally is not. Honor Retry-After when supplied, cap attempts and total delay, use jitter, and ensure the request is safe to repeat. Do not retry caller cancellation. If the server returned a non-PDF 2xx body, fix the upstream contract or authentication rather than repeatedly parsing it.

Resource lifetime and buffering choices

  • Dispose every HttpResponseMessage. A using declaration keeps the connection lifecycle clear.
  • Dispose or asynchronously dispose response streams after the PDF library finishes.
  • Use ReadAsByteArrayAsync for small documents or APIs that require a byte array; use streaming for large files.
  • Set a maximum acceptable document size before buffering. A declared length is only a hint, so enforce limits while copying streamed data.
  • Reuse a configured HttpClient rather than creating one per request; configure its timeout, decompression, proxy, and handler policies centrally.

Common symptoms and fixes

Symptom Likely cause Fix
PDF parser reports invalid header HTML, JSON, or a login page was sent to it Keep the response, branch on status, inspect media type, and check %PDF-.
Only GetStreamAsync throws That convenience method enforces 2xx status Switch to GetAsync with ResponseHeadersRead for custom error handling.
Error details disappear EnsureSuccessStatusCode ran before reading content Read and safely bound the error body first, or return a structured failure.
200 response has no pages Empty, truncated, or non-PDF body despite a successful status Check bytes read, signature, content type, and parser diagnostics.
Requests hang or cancel Timeout, stalled server, or caller cancellation Set an explicit timeout, pass a cancellation token, and distinguish cancellation from retryable transport errors.
Works in a browser but not in code Missing cookies, authorization, user agent, or redirect assumptions Inspect redirects and response headers; configure authentication deliberately and never log credentials.

Testing the boundary

Unit-test the HTTP handling with a fake HttpMessageHandler that returns representative responses: 200 with valid PDF bytes, 200 with HTML, 204, 400 with JSON, 500 with a large body, and a thrown timeout. Assert that the converter is called only for an acceptable success payload, that error text is bounded, and that status codes are preserved. Integration tests should also cover redirects, authentication expiry, chunked transfer, cancellation, and a genuinely malformed PDF.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your broader workflow is capturing a web page rather than downloading a server-generated PDF, ScreenshotNeo provides a single HTTP request for PNG, JPEG, WebP, or PDF output. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to 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.webp

See the ScreenshotNeo API documentation for output and options. The service also supports full-page and selector captures, device and viewport settings, retina scale, PDF paper and page controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify migration.

Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is on every plan. Create a free ScreenshotNeo account to try it.

Recommended decision rule

Use an explicit IsSuccessStatusCode branch when status distinctions, error content, custom results, or retry decisions matter. Use EnsureSuccessStatusCode when non-2xx responses should simply become exceptions. In both cases, keep PDF conversion behind the success boundary and validate the returned bytes as a separate document check.

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

Frequently Asked Questions

Does a 2xx status guarantee that the body is a PDF?

No. It only reports HTTP success. Check the media type and, when useful, the %PDF- signature, then let the PDF parser validate the document structure.

Should I retry a PDF conversion exception?

Usually no. Retry the HTTP request only for failures your service identifies as transient; a malformed or non-PDF body normally requires correcting the request or upstream response.

When should I use ResponseHeadersRead?

Use it when you want to process large responses as streams and avoid buffering the complete body before your status and content checks.

Quick Recap

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.