On this page
  1. How to embed PDF in HTML?
  2. Example code
  3. Workable example

Is your site slow?

Discover performance bottlenecks to provide a better customer experience and meet your company’s revenue targets.

Multiple, the same icon PDF

How to embed a PDF in HTML without downloading it

Embed a PDF in HTML without downloading it

There are several HTML elements that can be used to view Portable Document Format (PDF) files in HTML. The <embed>, <object> and <iframe> elements can all display a PDF file within the web page. Each works in a very similar way, but which one to choose? Let’s find out.

How to embed PDF in HTML?

After experimenting with many options we’ve seen that combination of <object> with fallback to an <iframe> that points to Google Docs Viewer works most optimal.

Desktop browsers support embedding PDF in HTML quite well. However, mobile devices may not always render as we expect therefore we recommend to include also a link to the original document so it can be downloaded.

Example code

Important: the code will use the Google Docs Viewer as a fallback. If this is something that can’t be used, you may skip the iframe code.
<a href="https://www.example.com/file.pdf" download>Example PDF</a>

<object data="https://www.example.com/file.pdf" type="application/pdf" style="height: 800px; max-width: 56rem; width: 100%;">
  <iframe src="https://docs.google.com/viewer?url=https%3A%2F%2Fwww.example.com%2Ffile.pdf&embedded=true" style="height: 800px; max-width: 56rem; width: 100%;" frameborder="0"></iframe>
</object>

Note that the URL param must be encoded. Example window.encodeURIComponent('filename=file.pdf') where output becomes filename%3Dfile.pdf.

Workable example

Important: when you get an error This content is blocked. Contact the site owner to fix the issue. your Content Security Policy may highly likely needs to be updated. The error might be:

Refused to frame 'https://docs.google.com/' because it violates the following Content Security Policy directive: "frame-src 'self'".

Refused to load plugin data from 'https://www.sitelint.com/lab/embedded-pdf/WebBrowser-Wikipedia.pdf' because it violates the following Content Security Policy directive: "object-src 'none'".

You may also download document Web Browser – Wikipedia in PDF format.

Related posts

Comments

Leave a Reply

SiteLint Audits: Monitoring in real-time Accessibility, Performance, Privacy, Security, SEO, Runtime Errors and Console Logs