112

How can I display a pdf within a web browser on an .html page?

21 Answers 21

133

I use Google Docs embeddable PDF viewer. The docs don't have to be uploaded to Google Docs, but they do have to be available online.

<iframe src="http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>
Sign up to request clarification or add additional context in comments.

7 Comments

With this solution some users do not see the PDF file, but are asked by google to log in first.
I have a question about this solution. Will google store a copy of my pdf file in its servers? Will privacy of my content preserve?
@Alex to know for sure, try... I would try - ://docs.google.com/gview?url=://path.com/to/your/pdf.pdf&embedded=true as the iframe src
@hd. Yes, Google just displays the PDF through its embedded display. I don't think they keep a copy, although they'll have to translate it into page by page display, so at some point I expect they convert to PNG on a page-by-page basis. For anyone using this answer, please note that Google has a bandwidth limit for non-Google Document documents. Once exhausted, the PDF does not display, just a message that bandwidth has been exceeded and to try again later.
if it's public then g00g1e already has a copy of it. if you want to see PDF without internet connection you can get a friend to download it. the object element is a much better solution for viewing see @BAKARISHEGHEMBE s answer
|
45

instead of using iframe and depending on the third party`think about using flexpaper, or pdf.js.

I used PDF.js, it works fine for me. Here is the demo.

3 Comments

How is it not a third party?
It's third party code rather than a third party service.
Better solution for application for VPN environment.
40

preffered using the object tag

<object data='http://website.com/nameoffolder/documentname.pdf#toolbar=1' 
        type='application/pdf' 
        width='100%' height='700px'>
</object>

note that you can change the width and height to any value you please visit http://www.w3schools.com/tags/tag_object.asp

6 Comments

The like you posted doesn't provide any more insight to the answer.
the question was How can I display a pdf within a web browser on an .html page? using the html 5 object tag will help ...<object width="400" height="400" data="helloworld.swf"></object> Use this element to embed multimedia (like audio, video, Java applets, ActiveX, PDF, and Flash) in your web pages.
You are completely right, however the link to w3schools doesn't give any more information to complement the answer as you wrote it.
This would not work if you don't have any pdf viewer in your browser
Yes that is true. A good thing about the object tag is that it can detect that. And it allows you to put further options for the visitors to view the page through either gdrive, onedrive and etc. <object data='example.com/path.pdf#toolbar=1'type='application/pdf' width='100%' height='700px'> <p>It appears your Web browser is not configured to display PDF files. No worries, just <a href='example.com/path.pdf'>click here to download the PDF file.</a> or <a href="drive.google.com/[drive path]/view?usp=sharing"> click here to view</a></p> </object>
|
21

The simplest way is to create an iframe and set the source to the URL of the PDF.

(ducks mad HTML designers) Done it myself, works fine, cross browser (crawls into bunker).

4 Comments

doesn't work if you don't have the pdf plugin installed on IE
How is that obvious? Seems like a useful addendum to "cross-browser".
this was so much easier to set up than all the other 3rd party ones. I don't know how it performed in 2011 but in 2016 it is very fast and full of useful features. Also seems to work great across Chrome, FF and IE
It doesn't work for me in Chrome on Android phone: it downloads pdf and opens it in separate app (if you have one). And I can't scroll to other pages in Safari on iOS. I just see the first page of pdf.
10

The browser's plugin controls those settings, so you can't force it. However, you can do a simple <a href="whatver.pdf"> instead of <a href="whatever.pdf" target="_blank">.

Comments

9

I did a careful evaluation of providers on this space:

free solutions

  • iframe: Just use an iframe, however, this is not what most people search here.
  • Pdf.js is the open source solution without external dependencies
  • Adobe offers a 'free' PDF Embed API

Commercial Providers

  • Pdf.js Express is commercialized extension to Pdf.js
  • Nutrient - Provder from Austria with rather good business support
  • Foxit - Chinese company providing a PDF web solton as well.enter link description here
  • Apryse - US-based competitor to PSDPDFkit - more costly but also mot advanced.
  • ComPDF - Compare to Apryse and Nutrient, ComPDF is cost-effective.

Hope this helps. I might publish more detailed information in a blogpost, if this is helping people (let me know in comments).

Comments

6

As long as you host the PDF the target attribute is the way to go. In other words, for relative files, using the target attribute with _blank value will work just fine.

<e>
  <a target="_blank" alt="StackExchange Handbook" title="StackExchange Handbook"
     href="pdfs/StackExchange_Handbook.pdf">StackExchange Handbook</a>

For absolute paths engines will go to the Unified Resource Locator and open it their. So, suppress the target attribute.

<e>
  <a alt="StackExchange Handbook" title="StackExchange Handbook"
     href="protocol://url/StackExchange_Handbook.pdf">StackExchange Handbook</a>

Browsers will make a rely good job in both cases.

1 Comment

This solution worked way better for me than the accepted answer. It should also be noted I work with some sensitive information, so not having my documents publicly available was important to me.
5

If you don't want to use some third party, you can use the <embed> tag with the source of the file in the src attribute. This uses the native browser PDF viewer, and offers more browser support than the object tag.

<embed src="your_pdf_src" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">

Live example:

<embed src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">

Loading the PDF inside a snippet won't work, since the frame into which the plugin is loading is sandboxed.

Tested in Chrome and Firefox. See it in action.

3 Comments

object tag is standard in ES2015 and replaced embed tag
@manikanta embed is part of the HTML5 specification. See: html.spec.whatwg.org/#embedded-content-2
@manikanta—Since embed is part of the HTML5 specification, I see no issue with using it.
3

You can use this code:

<embed src="http://domain.com/your_pdf.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

Or use Google Docs embeddable PDF viewer:

<iframe src="http://docs.google.com/gview?url=http://domain.com/your_pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Comments

2

You can also embed using JavaScript through a third-party solution like PDFObject.

Comments

2

The important moment: you need to define Content-Type in the HTTP response (on the server), for example: Content-Type: application/pdf. In html, you need to define

<embed src="url/to/your/file.pdf" width="100%"/>

Checked on:

  • Chrome
  • Firefox

3 Comments

I need to searchable my contents of pdf, Can I do it?
@PersianGulf, firefox has build-in search field for pdf. On chrome you can use ctrl + F, it will include results from pdf as well
I want to another user in the web can search in my web server and my pdf.
1

The simple solution is to put it in an iframe and hope that the user has a plug-in that supports it.

(I don't, the Acrobat plugin has been such a resource hog and source of instability that I make a point to remove it from any browser that it touches).

The complicated, but relative popular solution is to display it in a flash applet.

Comments

1

Update - Adobe PDF Embed API

Adobe released their Adobe PDF Embed API which is completely free. Since they created the PDF format itself, their API is probably the best for this.

  • It delivers the highest quality PDF rendering available.
  • You can fully customize user experience and choose how to display a PDF.
  • You will also have analytics on PDF usage so you can understand how users interact with PDFs, including time spent on a page and searches.

All you have to do is create an api_key and use it in the code snippet.

Displaying PDF as buffer

Here is the example of the code snippet that you can just add to your HTML and take advantage of their API for displaying PDF if you have the buffer (local file for example). You would have to add { promise: <FILE_PROMISE> } config.

<div id="adobe-dc-view"></div>

<script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>

<script type="text/javascript">
  document.addEventListener("adobe_dc_view_sdk.ready", function(){
    var adobeDCView = new AdobeDC.View({clientId: "api_key", divId: "adobe-dc-view"});
    adobeDCView.previewFile({
      content: { promise: <FILE_PROMISE> }
      metaData: { fileName: "file_name_to_display" }
    }, {});
  });
</script>

Displaying PDF by file_url

Here is the example of the code snippet that you can just add to your HTML and take advantage of their API for displaying PDF by file_url. You would have to add { location: { url: "url_of_the_pdf" } } config.

<div id="adobe-dc-view"></div>

<script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>

<script type="text/javascript">
  document.addEventListener("adobe_dc_view_sdk.ready", function(){
    var adobeDCView = new AdobeDC.View({clientId: "api_key", divId: "adobe-dc-view"});
    adobeDCView.previewFile({
      content: { location: { url: "url_of_the_pdf" } },
      metaData: { fileName: "file_name_to_display" }
    }, {});
  });
</script>

1 Comment

One should mention however, that this very nice library comes with a lot of Third-party cookies, which Chrome is stating 215 of them will be blocked "Reading cookie in cross-site context will be blocked in future Chrome versions"
0

You can also have this simple GoogleDoc approach.

<a  style="color: green;" href="http://docs.google.com/gview?url=http://domain//docs/<?php echo $row['docname'] ;?>" target="_blank">View</a>

This would create a new page for you to view the doc without distorting your flow.

2 Comments

This works fine, thanks. But what about in the case of, if the user want to see the pdf without internet connection?
you can use JQuery library such as pdf.js github.com/mozilla/pdf.js .. 2. Check out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.
0

I have been using object element to display PDF. But I am also using IDM extension. And when I reload the page, it tries to download the pdf. So I am creating a route in my laravel projects like this

Route::get('/pdf/{filename}', function ($filename) {
    $path = storage_path('app/public/pdfs/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    $headers = [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="' . $filename . '"'
    ];

    return response()->file($path, $headers);
});

After this I am calling url from object element. And I can finally see pdf displayed in the browser even I have third party extensions.

<object data="{{ url('/pdf/' . $product->pdf) }}" type="application/pdf" width="100%" height="250">
    <p>Cannot view PDF ?. <a href="{{ url('/pdf/' . $product->pdf) }}" download title="Download PDF">Download PDF</a>.</p>
</object>

Comments

0

By far the simplest method to avoid cross site and or server load Issues is include the cover icons in the page and provide a DownLink. It is minimal demand rendering a page of several covers / icons. The second best method is show a single iFrame with your adjoining commentary.

However many modern browser users a weary of exploits may have turned PDF display OFF and blocked any attempts to pop-up or window.open inline runnable embedment objects like SWF or PDF.

Note the snippet is a small icon but you can use larger front cover like Amazon Books (within the browser datauri limits)

<center>  

<h4>Click on the below icon to download pdf file :<br>If blocked by Security Refresh to show Cover and Right Click to Download</h5>  

<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAABBVBMVEUAAABTwd7O7PUAAAC35PEAAAAAAABTwd5Twd5Swd5Twd5Swd5RwN7A6POw4fBUwd5Xwt9bxOCS1+pTwd5Vwt9Wwt9dxeCC0ecAAABXw99bxOBcxOAAAABUwd4AAABWwt8AAABkx+Juy+MAAABUwd5Uwd5Vwt9Wwt9Yw99gxuFryeJoyeN/0OeZ2utXwt9Wwt9Wwt9bxOBWwt9Yw99gxuEAAABNv91Uwd5Uwd5Vwd5Yw98AAABaw+BbxOBYxOAAAAByzeVVwt9Vwt9Zw+BfxeBKvt1oyeIAAAAAAABVwt9Yw98AAABTwd5bxOBaxOBpyOKC0eYAAACN1emD0OZUwd5RwN4AAADkCLpdAAAAVHRSTlMA/QK/BICP+fby7fv4CgbjjlAK58KhPg7PgF5JQMevnmAiFxDf0rWxfDkwKBIIrqmUiIZ3WlDz6NvLpZ9oQzQwHNe/dGI6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arzMv1LoPlypR9FeMjT1wL8JPNGBZlGSdiP0FJJlJr2azfJJLr4ZsOvYuQ9Mkk7NP3CxDIjbJoXSe5zN3CFmVf+BZjuTl3q3yHH9JE+M4tOJZEpHZFZuJcV/vkNinB/QuT76Z9NCFxNDjA8fzHHnyLJqlh4/8d4UhLjmccXn+kaeFDdkkHUPpTIZ/zAxZsjiZRvkZN0T/l30D1xyHzxgRNCEAAAAASUVORK5CYII=" alt="react">
<br><b> Download Dummy.pdf</b></a>  

enter image description here

Since the core format of PDF (used to be) plain text many systems still use a blob to transfer inline pdf code and at its simplest this is a real emulation.

The HTML carrier is sent to the client with the instruction to inline the PDF sources data. You can copy and paste this proof of working code.

<!DOCTYPE html>
<html>
<head><title>DownStream Inline PDF</title></head>
<body>
 <h1>Hello from PDF Stream</h1>
 <iframe id="pdfFrame" width="100%" height="600px"></iframe>
 <script>
const pdfBytes =`%PDF-1.3
1 0 obj <</Type/Catalog/Pages 2 0 R>> endobj
2 0 obj <</Type/Pages/Kids [3 0 R]/Count 1>> endobj
3 0 obj <</Type/Page/Parent 2 0 R/MediaBox [0 0 595 842]/Contents 4 0 R/Resources<</XObject<</QR 5 0 R>>>>>> endobj
4 0 obj <</Length 74>>
stream
BT /F1 24 Tf 100 750 Td (Hello QR!) Tj ET
q 144 0 0 144 80 600 cm /QR Do Q
endstream
endobj
5 0 obj
<</Length 320/Type/XObject/Subtype/Image/Width 27/Height 27/BitsPerComponent 8/ColorSpace/DeviceRGB/Filter[/ASCIIHexDecode/FlateDecode]>>
stream
789ce5924b1280300843bdffa5ebcee9e447ecb62c1cace491826bdd1b8f8aef 
d39e844a00ca1387cd5aee1e08a1b2291b2f7ee0d0356a80bf3c07ed2e84ddc9 
67b3e51c0742e90d38c1760364491e0b0365c2afcc6fae0fb96c976972747002 
0ea581d2ad9c55e68481bba93ac3ae9d5bee520b0a576395ac194d0620cbc715 
8f4070cb8903ba167cbbd1a4d8b1ff2d4b9397c40bdffcd373> 
endstream
endobj
xref
0 6
0000000000 65535 f 
0000000009 00000 n 
0000000054 00000 n 
0000000106 00000 n 
0000000222 00000 n 
0000000344 00000 n 
trailer
<</Root 1 0 R/Size 6 >>
startxref
831
%%EOF
`;
  const blob = new Blob([pdfBytes], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  document.getElementById('pdfFrame').src = url;
 </script>
</body>
</html>

enter image description here

Comments

-1

I recently needed to provide a more mobile-friendly, responsive version of a .pdf document, because narrow phone screens required scrolling right and left a lot. To allow just vertical scrolling and avoid horizontal scrolling, the following steps worked for me:

  • Open the .pdf in Chrome browser
  • Click Open with Google Docs
  • Click File > Download > Web Page
  • Click on the downloaded document to unzip it
  • Click on the unzipped HTML document to open it in Chrome browser
  • Press fn F12 to open Chrome Dev Tools
  • Paste copy(document.documentElement.outerHTML.replace(/padding:72pt 72pt 72pt 72pt;/, '').replace(/margin-right:.*?pt/g, '')) into the Console, and press Enter to copy the tweaked document to the clipboard
  • Open a text editor (e.g., Notepad), or in my case VSCode, paste, and save with a .html extension.

The result looked good and was usable in both desktop and mobile environments.

Comments

-1

[this is a very old answer, from when other options mentioned now didn't exist]

Back in 2011, we used to render the PDF file pages as PNG files on the server using JPedal (a java library). That, combined with some javascript, gave us high control over visualization and navigation.

2 Comments

I think this is great , but needs a lot of resources.
But users can't copy/paste text from PNG.
-1

I think the object HTML can be the right choice for this kind of operations

Comments

-2

Displaying content saved in PDF/DOC/DOCX file format is ideal for displaying the pdf/doc/docx file on your web page

Comments

-6

Have you tried using a simple img tag?

This can work in Safari, but as you can see by the negative score, it is not a useful solution.

You could use something like ImageMagick to create a JPEG from a PDF and use that as a preview/thumbnail.

2 Comments

Does anybody know how this is supported?
This is impossible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.