Return generated PDF bytes with Content-Type: application/pdf. To display the file in a browser, use Content-Disposition: inline; filename="report.pdf"; to prompt a download, use Content-Disposition: attachment; filename="report.pdf". For a straightforward web preview, point an <iframe> at the PDF and put an ordinary open or download link beside it.
Return the PDF with the right HTTP headers
Your server should send the PDF bytes as the response body, not wrap them in JSON or return a base64 string unless your client specifically needs that format. Set the media type to application/pdf and choose a content disposition that matches the intended behavior:
Content-Disposition: inline; filename="report.pdf"asks the browser to display the PDF if it supports inline viewing.Content-Disposition: attachment; filename="report.pdf"asks the browser to download it.
The filename is useful when the browser downloads the file or offers it to the user. The disposition header communicates the intended handling; it does not guarantee every browser or client will behave identically. See MDN’s Content-Disposition reference.
Example: return generated bytes from an endpoint
Framework APIs differ, but the response should have this shape:
Recommended Free Tools
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: inline; filename="report.pdf"
<PDF bytes>
If users should download the report instead, change inline to attachment. Ensure the endpoint returns the completed PDF bytes and an appropriate status code; an error page or JSON error body served with a PDF content type will not render as a valid document.
Preview a URL-backed PDF with an iframe
For a PDF available at a URL, an iframe is usually the simplest native preview. Include a separate link because the embedded viewer may be unavailable, blocked, or inconvenient to use:
<iframe src="/reports/123.pdf" title="Generated report" width="100%" height="720"></iframe>
<p><a href="/reports/123.pdf">Open the PDF</a> ·
<a href="/reports/123.pdf" download>Download the PDF</a></p>
The download attribute expresses a download preference, but browser behavior can vary, especially for cross-origin URLs. The endpoint’s response headers also influence whether the browser displays or downloads the file. MDN notes that an iframe can display a PDF through the browser’s built-in PDF viewer and recommends iframe for previews; object can be useful when fallback content is needed, while embed offers no particular advantage for this use. See MDN’s embedding overview and the iframe reference.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Do not sandbox the viewer without a reason
An iframe’s sandbox attribute restricts embedded content. Applying it casually can prevent the browser’s built-in PDF viewer from loading or functioning, so test the exact browser and viewer behavior before adding it. Keep the separate PDF link outside the iframe; iframe fallback content is not a dependable way to tell users that a built-in viewer failed.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Preview bytes created in the browser with a Blob URL
If an API generates the PDF in response to a browser request, fetch the response as a Blob, create an object URL, and assign it to the iframe. This avoids requiring a permanent public file URL:
const response = await fetch('/api/report', { method: 'POST' });
if (!response.ok) {
throw new Error(`Report request failed: ${response.status}`);
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
const frame = document.querySelector('#viewer');
frame.src = objectUrl;
// When the preview is no longer needed:
URL.revokeObjectURL(objectUrl);
Use a corresponding element in the page, plus a normal link if users should be able to open or save the generated file:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
<iframe id="viewer" title="Generated report" width="100%" height="720"></iframe>
Do not revoke the object URL immediately after assigning it: the viewer still needs it. Revoke it when the preview is being replaced or removed, such as when the user closes the report. MDN documents the Blob-to-object-URL pattern in Using files from web applications.
Choose between a native viewer, PDF.js, and a managed viewer
| Approach | Best fit | Customization and control | Cross-origin and operational considerations |
|---|---|---|---|
| Native iframe | Basic in-page preview with the browser’s PDF viewer | Low; the browser supplies the viewer UI and rendering | Simple when the PDF is reachable and framing is allowed. Include a separate link because the embedded viewer may not work. |
| PDF.js | Custom viewer UI, page-level rendering, or a more consistent product experience | High; Mozilla provides core parsing, display APIs, and viewer UI | URL loading follows same-origin rules; cross-origin access needs CORS or a proxy. Your application must manage the PDF.js assets and their versions. |
| Adobe PDF Embed API | A maintained viewer with options such as inline, lightbox, sized-container, and full-sized modes, plus analytics and collaboration features | Managed feature set rather than a viewer you build entirely yourself | Review Adobe’s current documentation and requirements for your use case at PDF Embed API. |
Accessibility and fallback behavior depend partly on the document and the viewer. A native preview should not be the only way to reach the file: retain a conventional link. A custom PDF.js viewer gives you more control over the interface and page rendering, but means taking responsibility for implementing and maintaining that interface. No material pricing comparison is established here, so check the relevant provider’s current terms rather than assuming a particular operational cost.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Use PDF.js when you need a controlled viewer
Mozilla’s PDF.js has three main layers: core parsing, display APIs, and viewer UI. You can use its display API to load a same-origin PDF URL and render a page into a canvas. This minimal example assumes pdfjsLib and a canvas are already available:
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
const loadingTask = pdfjsLib.getDocument({ url: '/reports/123.pdf' });
const pdf = await loadingTask.promise;
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 1.25 });
const canvas = document.querySelector('canvas');
canvas.width = viewport.width;
canvas.height = viewport.height;
await page.render({
canvasContext: canvas.getContext('2d'),
viewport
}).promise;
The loading task’s promise resolves to a PDF document; then the example gets page 1, calculates a viewport, sizes the canvas, and renders that page. The official PDF.js examples show this loading-task pattern. For an application, also implement the controls your users need, such as page navigation, zoom, loading state, and errors; the minimal rendering snippet is not a complete viewer.
Load bytes instead of a URL
If your application already has the PDF bytes, PDF.js can work with binary data such as a Uint8Array rather than fetching a URL. Mozilla’s FAQ documents using raw binary data with Uint8Array in its viewer application: PDF.js FAQ. This can be useful when your own authenticated request retrieves the file, but you still need to handle authorization and memory use in the application.
Handle cross-origin access and framing policies
Cross-origin problems depend on how the PDF is loaded. A browser may be able to navigate to a PDF URL that a script is not allowed to fetch and inspect. PDF.js URL loading and JavaScript fetches are governed by browser origin rules; for a PDF served from another origin, configure that server’s CORS policy or proxy the file through your own origin. Mozilla’s PDF.js FAQ explains that cross-origin loading is not enabled by default and requires CORS or a server proxy.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
- For a PDF.js fetch or typed-array workflow: allow the requesting origin with appropriate CORS response headers, or fetch through a server-side proxy that you control.
- For an iframe that stays blank or refuses to load: inspect the PDF host’s framing policy, including
X-Frame-Optionsand relevant Content Security Policy directives such asframe-srcandobject-src. - For your own page’s Content Security Policy: ensure the policy allows the PDF source in the directive used by your embedding method.
- For private reports: use an authenticated endpoint or a short-lived authorized URL. Avoid putting bearer tokens in a viewer query string, where URLs can be exposed through browser history, logs, or copied links.
Same-origin policy restricts how documents and scripts from different origins interact; it does not mean that every cross-origin navigation or embed behaves identically. See MDN’s same-origin policy guidance and check the actual response headers in the browser’s network tools.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance, reliability, and cost decisions
A native browser viewer avoids building your own rendering interface, but its appearance and controls are browser-dependent. PDF.js enables page-level rendering and custom UI; Mozilla also documents automatic HTTP Range Requests when the server supports them, so a viewer can request portions of a PDF instead of downloading the entire file before displaying visible content. Confirm that your server or storage layer supports range requests if you depend on this behavior.
For either approach, test the actual generated output, not just a sample PDF. Check that the response is a valid PDF, that the endpoint handles the expected authorization flow, and that the browser can reach the file under your production CORS, CSP, and framing policies. Large documents and repeated previews can consume browser memory; replacing or closing a Blob-backed preview is a good time to revoke its object URL. A managed viewer can reduce the amount of viewer UI you build, while PDF.js gives you more implementation responsibility and control. Compare current licensing, service terms, and hosting needs for your deployment; the documentation cited here does not establish a general cost figure.
Troubleshoot common PDF preview failures
| Symptom | Likely cause | What to check or change |
|---|---|---|
| The browser downloads the PDF rather than showing it | The response uses Content-Disposition: attachment, or the browser does not provide inline viewing in that context |
For a preview, return Content-Disposition: inline and Content-Type: application/pdf. Keep a download link for users who want a file. |
| The iframe is empty or reports that it cannot display the file | The URL is inaccessible, the response is not a valid PDF, or a framing policy blocks it | Open the URL directly; inspect status, response headers, and body in the network panel; review CSP and X-Frame-Options. |
| PDF.js reports a network or CORS error | The PDF is on another origin and the server does not permit the script’s request | Configure CORS on the PDF server or fetch through a server-side proxy on your origin. |
| PDF.js loads the document but the page does not render | The canvas setup or page-rendering code is incomplete, or the document/page request failed | Await the loading task and render promise, verify the page number exists, and size the canvas from the page viewport. |
| A Blob-backed preview works briefly, then fails | The object URL was revoked while the viewer still needed it | Revoke it only after the preview has been replaced or removed. |
Adding iframe sandbox breaks the viewer |
The sandbox restrictions interfere with the built-in PDF viewer | Remove the attribute unless it is required for a tested security design; use a separate link as a fallback. |
Or skip the browser setup
If what you need is a screenshot or PDF capture of a web page rather than delivery of a PDF your application generated, ScreenshotNeo can return a screenshot or PDF with one GET request. For example, this cURL request saves a PDF capture:
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →curl -G "https://api.screenshotneo.com/v1/shot"
-d access_key=YOUR_API_KEY
--data-urlencode url=https://stripe.com
-d format=pdf
-o page.pdf
See the ScreenshotNeo API documentation for authentication and PDF options. It removes cookie and consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server lets AI agents use screenshot and PDF tools. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. This captures a web page as a PDF; it does not replace an endpoint for returning your application’s own generated report. Sign up free and get 1,000 screenshots a month with no card.
Frequently Asked Questions
Why does an iframe show a PDF for one user but not another?
The users may have different browser PDF support, authentication state, or network access. Check the PDF URL and response headers in each environment and keep an ordinary link available.
Can I embed a PDF that requires login?
Yes, if the browser can access it through an authenticated session or authorized URL and the site’s framing policies permit embedding. For custom PDF.js loading, the request must also satisfy same-origin or CORS requirements.
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.

