How to embed a PDF viewer in a website (2026 guide)
Table of contents
Use an iframe and a direct PDF link for a simple preview. Choose a JavaScript viewer such as Nutrient Web SDK when your application needs to control the interface, or to capture annotations, form data, and signatures. Use Nutrient DWS Viewer API with DWS-managed documents when you want hosted storage and collaboration.
There are two real choices for putting a PDF on a webpage. An iframe hands the file to the browser’s own PDF viewer, which is enough for showing a document. A JavaScript viewer renders the PDF with its own engine, which is what you need when the document is part of a workflow rather than just something to read.
The embed and object elements also use the browser’s PDF handling. Their fallback content and security-policy rules differ, so changing the element can change how a preview behaves.
If you’d rather watch than read, the tutorial below walks through the native HTML options.
Embed a PDF in HTML with an iframe
An iframe displays a PDF within your page without a JavaScript library. MDN recommends it as the top choice(opens in a new tab) for a PDF preview, whether you’re writing plain HTML or working in a framework such as React or Vue.
Save the following as index.html, put document.pdf in the same directory, and serve both from a local web server. Replace the file name and document title for your own site:
<!doctype html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Product manual</title> <style> body { margin: 0; padding: 1rem; font-family: system-ui, sans-serif; line-height: 1.5; }
main { max-width: 60rem; margin-inline: auto; }
.pdf-preview { display: block; width: 100%; height: 75vh; max-height: 50rem; border: 0; } </style> </head> <body> <main> <h1>Product manual</h1> <p> <a href="document.pdf">Open the product manual PDF</a> </p> <iframe class="pdf-preview" src="document.pdf" title="Product manual PDF preview" ></iframe> </main> </body></html> 
The CSS fills the container’s width and sets an explicit height. Avoid height: 100% unless every ancestor has a definite height; otherwise, the iframe collapses.
Keep the link outside the iframe so it stays available if the preview fails. Text placed between the opening and closing iframe tags isn’t fallback content(opens in a new tab): Unlike the object element, an iframe doesn’t support child content as a fallback when the PDF can’t be displayed.
For a preview further down a long page, add loading="lazy" to defer the request until the iframe approaches the viewport.
Serve the PDF for inline viewing
On a server you control, return the PDF with these response headers:
Content-Type: application/pdfContent-Disposition: inline; filename="document.pdf"Content-Disposition: inline(opens in a new tab) asks the browser to display the file; attachment asks it to download. Browser settings and platform capabilities can still override inline viewing, so treat it as a request rather than a guarantee.
Protect the file, not just the page
For private documents, enforce authorization on the PDF endpoint as well as on the webpage that embeds it. Protecting only the page leaves the file readable by anyone who knows its URL.
Check the experience on mobile
A responsive iframe doesn’t reflow the PDF. A print-sized report still arrives as print-sized pages, so a phone user zooms and pans through it.
Test your actual documents in the browsers and in-app webviews your audience uses, comparing the embedded preview against opening the PDF directly. Where behavior differs, check browser versions and PDF viewing settings. If essential information is difficult to read in PDF form on a small screen, consider publishing an HTML version alongside it.
What about the object and embed elements?
Use the object element(opens in a new tab) when you want fallback content to appear inside the preview area. This example reuses the .pdf-preview CSS from above:
<object class="pdf-preview" data="document.pdf" type="application/pdf" title="Product manual PDF preview"> <p> The PDF preview is unavailable. <a href="document.pdf">Open the product manual PDF</a>. </p></object> 
Not every loading failure triggers that fallback, so test it and keep a visible link outside the preview as well.
The embed element(opens in a new tab) also hands off to the browser’s PDF handling, but it accepts no child content, so there’s no fallback at all. MDN puts it plainly: embed offers no advantage for a PDF preview. An iframe gives you options the other two don’t, including lazy loading and a referrer policy. Don’t rewrite working markup for that: If an existing object or embed implementation renders correctly, changing the tag buys you nothing.
The Content Security Policy (CSP) directive object-src 'none'(opens in a new tab) blocks object and embed elements. It doesn’t block an iframe, but frame-src(opens in a new tab) or its fallback directives can. The PDF response must also permit framing.
Nesting an iframe inside an object element is sometimes presented as a compatibility fix, but both elements depend on the same browser PDF handling, so a browser that fails to render one generally fails to render the other.
When a link is enough
If readers don’t need an inline preview, link to the file:
<a href="document.pdf">Read the annual report (PDF)</a>The browser opens or downloads it according to its own settings and your server’s response headers. Nothing is embedded, which — for a document people read start to finish — is often the better experience.
Use Nutrient Web SDK APIs to configure the viewer, save annotations, capture form data, and integrate signature workflows into your application.
When you need a JavaScript PDF viewer
Native browser viewers handle search, zoom, printing, and forms, and the feature set keeps growing. Firefox’s built-in viewer(opens in a new tab) supports form filling along with text, drawing, and highlight annotations.
Reach for a JavaScript viewer when you need application control. Pointing an iframe at a PDF URL gives your page no API: You can’t configure the toolbar, read back what the user annotated, or route filled form data into your own workflow.
Viewer controls aren’t document security
Two limits to know before you design around them:
- Hiding a download button doesn’t prevent saving. Once the document data reaches the browser, it can be extracted. A hidden control makes saving less convenient without making it impossible.
- URL parameters such as
#toolbar=0are viewer-specific. They’re honored by some built-in viewers and ignored by others, which makes them neither a portable way to configure a toolbar nor any form of protection.
When you need to configure a viewer’s tools, use its documented API. Nutrient’s download and print controls govern what’s available inside the viewer; sensitive documents also need server-side authorization and a deployment model that matches the requirement.
Add document workflows with Nutrient Web SDK
Nutrient Web SDK renders PDFs with its own engine and exposes the viewer to your application through APIs. It’s the right tool when you need to:
- Capture and save annotations as part of a review process.
- Let users complete PDF forms and extract the entered values.
- Customize the viewer interface and its mobile layout.
- Add a document-signing workflow.
A contract review screen is a typical case: It loads existing comments, saves new annotations as the reviewer works, and hands off to an approval step. With the standalone Web SDK, your application handles storage, identity, and authorization. The SDK renders the document and provides the UI for working with it.
Try it with your own file:
Upload a PDF and try drawing freehand, adding notes, or applying a digital signature.
Nutrient is a commercial SDK. Check your required features and licensing, and then start a free trial and work through the getting started guide.
Use a hosted viewer backend with DWS Viewer API
Nutrient DWS Viewer API pairs Nutrient Web SDK with a hosted service. For DWS-managed documents, Nutrient stores the files and persists annotations, form data, and comments, with real-time collaboration. For this setup, embed the Web SDK in the page and have your backend request session tokens. You don’t deploy Document Engine or operate viewer servers. Follow the Viewer API getting started guide to set it up.
The Web SDK can also run standalone in the browser with your application handling document storage and persistence. Add Document Engine if you need a backend you host. See the deployment guide for the hosted and self-hosted backend options.
Choose an approach
| What you need | Starting point | What to account for |
|---|---|---|
| Show a PDF within a webpage | An iframe plus a link | The browser controls viewer behavior |
| Show alternative content if the preview fails | The object element | Test the fallback; not every failure triggers it |
| Give readers the file without an inline preview | A direct link | The browser may open or download it |
| Connect document tools to an application workflow | Nutrient Web SDK | Commercial licensing and application integration |
| Add hosted document storage and collaborative review | Nutrient DWS Viewer API | Web SDK client; your backend requests session tokens |
Troubleshooting
Start by distinguishing native embedding from a JavaScript viewer that fetches PDF bytes. A working direct link doesn’t prove either will work inside your page.
Quick diagnostic checklist
| Symptom | Likely cause | Evidence |
|---|---|---|
| Gray frame with a sad-page icon | Document’s frame-ancestors or X-Frame-Options | Response headers; console names frame-ancestors |
Frame blocked, console names frame-src or object-src | Your page’s CSP | Console message; your page’s response headers |
| A sign-in form appears inside the frame | Authentication redirect; cookies not sent in a cross-site frame | 302 before the final response; HTML response type |
Failed to fetch in a JavaScript viewer | Missing cross-origin resource sharing (CORS) headers, or a redirect to a page without them | Console error naming CORS |
| Empty frame, no error | Content-Disposition: attachment, wrong Content-Type, or sandbox | Response headers; the iframe markup |
CORS governs JavaScript requests for PDF data; adding CORS headers doesn’t unblock an iframe. Check the console and response headers before changing policies. Also check that both the page and the PDF use HTTPS.
Reproduce a blocked PDF frame
A PDF on another origin may allow only same-origin framing. This example uses two local servers: an app on port 8080 and a document server on port 8081.
Local demo only. The original example was tested in Chrome 157. Firefox and Safari were not tested, and localhost ports don’t reproduce cross-site cookie restrictions. Production guidance follows the fix.
Create a folder with any PDF named sample.pdf, and add index.html:
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <title>Embed test</title> </head> <body> <iframe src="http://localhost:8081/sample.pdf" title="Sample PDF" style="width: 100%; height: 80vh; border: 0;" ></iframe> <p> <a href="http://localhost:8081/sample.pdf" target="_blank" rel="noopener"> Open the PDF in a new tab </a> </p> </body></html>Then add server.mjs. It needs Node.js and no dependencies:
// Local demo only. Run with `node server.mjs`, or `node server.mjs --fixed`.import { createServer } from "node:http";import { readFile } from "node:fs/promises";
const fixed = process.argv.includes("--fixed");const page = await readFile(new URL("./index.html", import.meta.url));const pdf = await readFile(new URL("./sample.pdf", import.meta.url));
// The app that embeds the PDF: http://localhost:8080createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(page);}).listen(8080);
// The document server: http://localhost:8081createServer((req, res) => { if (req.url !== "/sample.pdf") { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("Not found"); return; }
const headers = { "Content-Type": "application/pdf" }; if (fixed) { // Allow this server's own pages and the app origin to frame the PDF. headers["Content-Security-Policy"] = "frame-ancestors 'self' http://localhost:8080"; } else { // A common default: only same-origin pages may frame responses. headers["X-Frame-Options"] = "SAMEORIGIN"; headers["Content-Security-Policy"] = "frame-ancestors 'self'"; }
res.writeHead(200, headers); res.end(pdf);}).listen(8081);
console.log(`App: http://localhost:8080 (${fixed ? "fixed" : "broken"} mode)`);Run node server.mjs and open http://localhost:8080. In Chrome 157, the frame shows a gray sad-page icon, and the console reports:
Framing 'http://localhost:8081/' violates the following Content Security Policy directive: "frame-ancestors 'self'". The request has been blocked.The link below the frame opens the same PDF in Chrome’s viewer: Framing rules apply only when another page embeds the response.
Run node server.mjs --fixed, and the PDF renders in the frame. The fix is on the document server, not in your HTML: frame-ancestors(opens in a new tab) lists the pages allowed to embed the response, and now includes the app origin.
The fixed mode drops X-Frame-Options(opens in a new tab), which can’t list origins. In our Chrome test, an allowing frame-ancestors plus X-Frame-Options: SAMEORIGIN still rendered. We didn’t test other browsers.
In production, list your app’s HTTPS origins explicitly, apply the policy only to document routes, and don’t use a wildcard. If you don’t control the document server, ask its owner to allow your origin, or link to the PDF.
Read the evidence in DevTools
These steps use Chrome; Firefox and Safari have equivalent panels.
- In the Network tab, enable Preserve log and reload.
- Find the PDF request. In the reproduction, it showed
200even though the frame was blocked. - Check for a
302or303before it, which usually means a sign-in redirect. Follow the chain to the last request. - In Headers, check
Content-Type,Content-Disposition,X-Frame-Options,Content-Security-Policy, and, for fetches,Access-Control-Allow-Origin. - In Response, a PDF starts with
%PDF-. HTML means a sign-in or error page. - Read the Console. Chrome names the CSP directive that blocked a frame, or CORS for a blocked fetch.
Some blocks log nothing. With only X-Frame-Options: SAMEORIGIN, our test showed the same gray frame and 200, and our tooling captured no console message. The load event doesn’t prove success either: MDN’s iframe reference(opens in a new tab) notes it fires even when the content fails to load.
If the request returns a sign-in page, fix the authentication path rather than relaxing framing rules. If the server sends Content-Disposition: attachment, use inline on document routes intended for embedding. Retain the direct PDF link as a fallback; it doesn’t bypass authentication.
The preview is too small or overflows the page
Check the iframe’s height and its container’s width, and then look at the surrounding content. A fixed-width video, image, or table can stretch the whole page even when the iframe itself is responsive.
A large PDF loads slowly
Check file size, document complexity, and network conditions. Compressing images, subsetting fonts, and stripping unused metadata usually do more than any markup change; under 5 MB is a reasonable target for mobile networks. Where both the viewer and the server support them, HTTP range requests(opens in a new tab) let a viewer fetch portions of a PDF instead of waiting for the whole file to arrive.
Related reading
- Build a JavaScript PDF viewer with PDF.js — The open source route, if you plan to integrate and maintain a viewer yourself
- How to build a Word viewer using JavaScript — Render DOC and DOCX in the browser
- Open Excel files in the browser using JavaScript — Handle XLS and XLSX files
- How to build a PowerPoint viewer in JavaScript — Display PPT and PPTX presentations
- How to build a React file viewer — PDF, Office, and image formats in one component
FAQ
Use an iframe pointed at the PDF URL, and keep a direct link to the file next to it. No plugin or JavaScript library is required; the browser’s built-in PDF viewer renders it. Use the object element instead if you need fallback content to appear inside the preview area.
Not with HTML. Once the document data reaches the browser, it can be saved, so hiding a toolbar or a download button raises the effort rather than preventing it. Nutrient Web SDK lets you disable download and print controls in the viewer, but sensitive documents also need server-side authorization on the file endpoint.
Open the PDF URL on its own first. A missing file, a login redirect, or an HTML error response accounts for most cases. If the file loads fine directly, check the embedding page’s CSP frame-src, and then the document’s frame-ancestors or X-Frame-Options header. A mixed-content block (an HTTP PDF on an HTTPS page) is the other common cause. CORS governs JavaScript requests, not framing, so it’s rarely the answer here.
The #toolbar=0 URL fragment is honored by some built-in PDF viewers and ignored by others, so there’s no portable HTML-only way to do it. If you need reliable control over the interface, use a JavaScript viewer with a documented UI API, such as Nutrient Web SDK.
Mobile browsers and in-app webviews can handle embedded PDFs differently. A responsive iframe doesn’t reflow the document: A print-sized page stays print-sized. A JavaScript viewer gives your application control over the viewer interface and layout. Test its supported browsers and devices with your actual documents.
A cross-origin PDF can load in an iframe without CORS permission. Your page’s CSP must allow the source, and the PDF response must allow framing. If the host blocks framing, link to the PDF directly or ask its owner to enable embedding.
Add loading="lazy" to the iframe to defer the request until it approaches the viewport. With a JavaScript viewer, initialize it when the container enters the viewport using the Intersection Observer API.
A JavaScript viewer is worth the added complexity when your application needs to do something with the document rather than just show it. Embedding a PDF URL gives your page no API to configure the toolbar, read back annotations, or capture form data. If you need any of those, or a consistent interface across browsers, use a viewer such as Nutrient Web SDK.