Daniel Silveira
Daniel Silveira

Reputation: 42553

Recommended way to embed PDF in HTML?

What is the recommended way to embed PDF in HTML?

What does Adobe say itself about it?

In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.

Upvotes: 1398

Views: 1967419

Answers (24)

Adam Davis
Adam Davis

Reputation: 93625

[Update] Flash is no longer allowed to run in modern devices. (Dead redirected link removed)

FORMER FDView combined PDF2SWF (which itself was based on xpdf) with an SWF viewer so you can convert and embed PDF documents on the fly on your server.

xpdf is not a perfect PDF converter. If you needed better results in the past then Older GhostGum unsupported GhostView 5 spinoff was a possibility, currently Ghostscript 10 is an interpreter, not a viewer. As such it offers almost no UI. But can view PDF etc offline.

GhostScript does have multiple abilities to convert PDF documents into other formats which you may be able to more easily build a Flash HTML viewer for. [NOTE PDF.js is based on similar convert pages into images of a PDF.]

But for simple PDF documents, FDView [at the time] did work reasonably well.

Upvotes: 11

George Pligoropoulos
George Pligoropoulos

Reputation: 2939

[Update] seems to have been Branched into different payable apps (many tagged Kami) the google Play store version of Notable PDF is here https://play.google.com/store/apps/details?id=com.albankurti.notablepdf&hl=en_US

One of the options you should consider is Notable PDF
It has a free plan unless you are planning on doing real-time online collaboration on pdfs

Embed the following iframe to any html and enjoy the results:

<iframe width='1000' height='800' src='https://play.google.com/store/apps/details?id=com.albankurti.notablepdf&hl=en_US' frameborder='0' allowfullscreen></iframe>

Upvotes: 1

Zui
Zui

Reputation: 26

Workaround in Firefox for the Toolbar.

I little preface …

I need to have a couple of SVG's for the Layout to accomplish a Document in DIN-5008.

So I got me a copy of the Wikipedia SVG, that shows the Dimensions and the Placements. Additionally, I made some SVG's for the Logo and some drawings as a Watermark.

I then made a HTML5 File and in it, I placed one div to hold the SVG's and the PDF. All of them are placed into a separate div each.

Then I used CSS-Styles (classes) to align them over each other. I made a class Transparent_025.

.Transparent_025 { opacity: 0.25; }

With that, I can Stack the SVG's and the PDF to see all align properly.

But Firefox doesn't use the toolbar=1|0.

<div class="SVGStack_A Transparent_025" style="position: absolute; top: -32px;">
    <object
        data="thePath/theFilename.pdf?#zoom=100%&scrollbar=0&toolbar=0&navpanes=0"
        type="image/svg+xml" width="793.7px" height="1122.52px" />
</div>

This is my Workaround.

So the Height of the Toolbar in Firefox is 32px. And keep the PDF Scale to 100%.

PS: The Documents are in DIN-A4, so I used this:

<meta name="viewport" content="width=210mm, initial-scale=1.0">

With that, a needed to set the Width and Height.

width="793.7px" height="1122.52px"

Also, all div are placed absolutely on the Lop-Left-Corner.

Be aware that the PDF-Viewer in Firefox can get the Focus and a Scroll or Zoom can happen.

Upvotes: -1

alekswebnet
alekswebnet

Reputation: 46

PDF.js is still the best for me. I use pdfjs-viewer-element to simplify PDF.js setup:

<script type="module" src="https://cdn.skypack.dev/pdfjs-viewer-element"></script>

Specify the PDF.js release directory with viewer-path and path to PDF file with src attributes:

<pdfjs-viewer-element
  id="viewer"
  src="/file.pdf"
  viewer-path="/pdfjs-4.0.379-dist"
  style="height: 600px">
</pdfjs-viewer-element>

More samples for embedding PDF.js https://github.com/alekswebnet/pdfjs-viewer-element/tree/master/demo

Upvotes: 0

Batfan
Batfan

Reputation: 8266

This is quick, easy, to the point and doesn't require any third-party script:

<embed src="http://example.com/the.pdf" width="500" height="375" 
 type="application/pdf">

UPDATE (2/3/2021)

Adobe now offers its own PDF Embed API.
(That requires registering at Adobe and get clientID to use within js)

https://www.adobe.io/apis/documentcloud/dcsdk/pdf-embed.html

UPDATE (1/2018):

The Chrome browser on Android no longer supports PDF embeds. You can get around this by using the Google Drive PDF viewer

<embed src="https://drive.google.com/viewerng/
viewer?embedded=true&url=http://example.com/the.pdf" width="500" height="375">

Upvotes: 705

Lukasz
Lukasz

Reputation: 6767

You can also use Google PDF viewer for this purpose. As far as I know it's not an official Google feature (am I wrong on this?), but it works for me very nicely and smoothly. You need to upload your PDF somewhere before and just use its URL:

<iframe src="https://docs.google.com/gview?url=http://example.com/mypdf.pdf&embedded=true" style="width:718px; height:700px;" frameborder="0"></iframe>

What is important is that it doesn't need a Flash player, it uses JavaScript.

Upvotes: 384

Dan Mantyla
Dan Mantyla

Reputation: 1870

Convert it to PNG via ImageMagick, and display the PNG (quick and dirty).

<?php
  $dir = '/absolute/path/to/my/directory/';
  $name = 'myPDF.pdf';
  exec("/bin/convert $dir$name $dir$name.png");
  print '<img src="$dir$name.png" />';
?>

This is a good option if you need a quick solution, want to avoid cross-browser PDF viewing problems, and if the PDF is only a page or two. Of course, you need ImageMagick installed (which in turn needs Ghostscript) on your web server, an option that might not be available in shared hosting environments. There is also a PHP plugin (called imagick) that works like this but it has its own special requirements.

Upvotes: 21

Astrophage
Astrophage

Reputation: 1439

Our problem is that for legal reasons we are not allowed to temporarily store a PDF on the hard disk. In addition, the entire page should not be reloaded when displaying a PDF as Preview in the Browser.

First we tried PDF.jS. It worked with Base64 in the viewer for Firefox and Chrome. However, it was unacceptably slow for our PDF. IE/Edge didn't work at all.

We therefore tried it with a Base64 string in an HTML object tag. This again didn't work for IE/Edge (maybe the same problem as with PDF.js). In Chrome/Firefox/Safari again no problem. That's why we chose a hybrid solution. Edge we use an IFrame and for all other browsers the object-tag.

The IFrame solution would of course also work for Chrome and co. The reason why we didn't use this solution for Chrome is that although the PDF is displayed correctly, Chrome makes a new request to the server as soon as you click on "download" in the preview. The required hidden-field pdfHelperTransferData (for sending our form data needed for PDF generation) is no longer set because the PDF is displayed in an IFrame. For this feature/bug see Chrome sends two requests when downloading a PDF (and cancels one of them).

Now the problem children IE9 and IE10 remain. For these we gave up a preview solution and simply send the document by clicking the preview button as a download to the user (instead of the preview). We have tried a lot but even if we had found a solution the extra effort for this tiny part of users would not have been worth the effort. You can find our solution for the download here: Download PDF without refresh with IFrame.

Our Javascript:

var transferData = getFormAsJson()
if (isMicrosoftBrowser()) {
        // Case IE / Edge (because doesn't recoginzie Pdf-Base64 use Iframe)
        var form = document.getElementById('pdf-helper-form');
        $("#pdfHelperTransferData").val(transferData);
        form.target = "iframe-pdf-shower";
        form.action = "serverSideFunctonWhichWritesPdfinResponse";
        form.submit();
 } else {
        // Case non IE use Object tag instead of iframe
        $.ajax({
            url: "serverSideFunctonWhichRetrivesPdfAsBase64",
            type: "post",
            data: { downloadHelperTransferData: transferData },
            success: function (result) {
                $("#object-pdf-shower").attr("data", result);
            }
        })
 }

Our HTML:

<div id="pdf-helper-hidden-container" style="display:none">
   <form id="pdf-helper-form" method="post">
        <input type="hidden" name="pdfHelperTransferData" id="pdfHelperTransferData" />
   </form>
</div>

<div id="pdf-wrapper" class="modal-content">
    <iframe id="iframe-pdf-shower" name="iframe-pdf-shower"></iframe>
    <object id="object-pdf-shower" type="application/pdf"></object>
</div>

To check the browser type for IE/Edge see here: How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? I hope these findings will save someone else the time.

Upvotes: 12

NeNaD
NeNaD

Reputation: 20354

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 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>

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>

Upvotes: 5

amIT
amIT

Reputation: 1

Have a look for this code- To embed the PDF in HTML

<!-- Embed PDF File -->
<object src="YourFile.pdf" type="application/pdf" title="SamplePdf" width="500" height="720">
    <a href="YourFile.pdf">shree</a> 
</object>

Upvotes: 25

lubos hasko
lubos hasko

Reputation: 25052

Probably the best approach is to use the PDF.JS library. It's a pure HTML5/JavaScript renderer for PDF documents without any third-party plugins.

Online demo: https://mozilla.github.io/pdf.js/web/viewer.html

GitHub: https://github.com/mozilla/pdf.js

Upvotes: 611

Bob Singor
Bob Singor

Reputation: 578

If you don't want to host the PDFs yourself or want to customize your PDF viewer with additional security features like preventing users to download the PDF file. I recommend using CloudPDF. https://cloudpdf.io

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CloudPDF Viewer</title>
  <style>
    body, html {
      height: 100%;
      margin: 0px;
    }
  </style>
</head>
<body style="height: 100%">
  <div id="viewer" style="width: 800px; height: 500px; margin: 80px auto;"></div>
  <script type="text/javascript" src="https://cloudpdf.io/viewer.min.js?version=0.1.0-beta.11"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function(){
      const config = { 
        documentId: 'eee2079d-b0b6-4267-9812-b6b9eadb9c60',
        darkMode: true,
      };
      CloudPDF(config, document.getElementById('viewer')).then((instance) => {

      });
    });
  </script>
 </body>
</html>

Upvotes: -2

Ahmedakhtar11
Ahmedakhtar11

Reputation: 1470

You can use the relative location of the saved pdf like this:

Example1

<embed src="example.pdf" width="1000" height="800" frameborder="0" allowfullscreen>

Example2

<iframe src="example.pdf" style="width:1000px; height:800px;" frameborder="0" allowfullscreen></iframe>

Upvotes: 14

Tony Bui
Tony Bui

Reputation: 1299

Before I got a problem with embeding base64 encoded with PDF because the URI limitation, so any files over 2MB won't render properly on Chrome.

My solution is:

  1. Convert uri encoded to Blob:

  2. Generate the temporary DOM String base on Blob.

    const blob = dataURItoBlob(this.dataUrl);

    var temp_url = window.URL.createObjectURL(blob);

  3. Decide where you want to attach the iframe to DOM:

    const target = document.querySelector(targetID);

    target.innerHTML = `<iframe src='${temp_url}' type="application/pdf"></iframe>

Upvotes: -1

Marc Partensky
Marc Partensky

Reputation: 49

I found that the best way to embed a pdf for my case was by using bootstrap because not only does it show the pdf but it also fill available space and you can specify the ratio as you wish. Here's an example of what i made with it:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<div class="embed-responsive embed-responsive-1by1">
  <iframe class="embed-responsive-item" src="http://example.com/the.pdf" type="application/pdf" allowfullscreen></iframe>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

Upvotes: -1

Pecata
Pecata

Reputation: 1063

I had to preview a PDF with React so after trying several libraries my optimal solution was to fetch the data and ebmed it.

const pdfBase64 = //fetched from url or generated with jspdf or other library

  <embed
    src={pdfBase64}
    width="500"
    height="375"
    type="application/pdf"
  ></embed>

Upvotes: 3

Said Bouigherdaine
Said Bouigherdaine

Reputation: 647

  1. Create a container to hold your PDF

    <div id="example1"></div>
    
  2. Tell PDFObject which PDF to embed, and where to embed it

    <script src="/js/pdfobject.js"></script>
    <script>PDFObject.embed("/pdf/sample-3pp.pdf", "#example1");</script>
    
  3. You can optionally use CSS to specify visual styling, including dimensions, border, margins, etc.

    <style>
    .pdfobject-container { height: 500px;}
    .pdfobject { border: 1px solid #666; }
    </style>
    

source : https://pdfobject.com/

Upvotes: 12

Gayle
Gayle

Reputation: 3092

You do have some control over how the PDF appears in the browser by passing some options in the query string. I was happy to this working, until I realized it does not work in IE8. :(

It works in Chrome 9 and Firefox 3.6, but in IE8 it shows the message "Insert your error message here, if the PDF cannot be displayed."

I haven't yet tested older versions of any of the above browsers, though. But here's the code I have anyway in case it helps anyone. This sets the zoom to 85%, removes scrollbars, toolbars and nav panes. I'll update my post if I do come across something that works in IE as well.

<object width="400" height="500" type="application/pdf" data="/my_pdf.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0">
    <p>Insert your error message here, if the PDF cannot be displayed.</p>
</object>

Upvotes: 145

fartwhif
fartwhif

Reputation: 359

  1. Construct a blob of the input PDF bytes
  2. Use an iframe and PDF.js patched with this cross browser workaround

The URI for the iframe should look something like this:

/viewer.html?file=blob:19B579EA-5217-41C6-96E4-5D8DF5A5C70B

Now FF, Chrome, IE 11, and Edge all display the PDF in a viewer in the iframe passed via standard blob URI in the URL.

Upvotes: 1

Despertaweb
Despertaweb

Reputation: 1820

This is the way I did with AXIOS and Vue.js:

        axios({
            url: `urltoPDFfile.pdf`,
            method: 'GET',
            headers: headers,
            responseType: 'blob'
        })
        .then((response) => {
            this.urlPdf = URL.createObjectURL(response.data)
        })
        .catch((error) => {
            console.log('ERROR   ', error)
        })

add urlPDF dynamically to HTML:

<object width='100%' height='600px' :data='urlPdf' type='application/pdf'></object>

Upvotes: 5

Suneel Kumar
Suneel Kumar

Reputation: 5831

Using both <object> and <embed> will give you a wider breadth of browser compatibility.

<object data="http://yoursite.com/the.pdf" type="application/pdf" width="750px" height="750px">
    <embed src="http://yoursite.com/the.pdf" type="application/pdf">
        <p>This browser does not support PDFs. Please download the PDF to view it: <a href="http://yoursite.com/the.pdf">Download PDF</a>.</p>
    </embed>
</object>

Upvotes: 75

PLA
PLA

Reputation: 369

PdfToImageServlet using ImageMagick's convert command.

Usage example: <img src='/webAppDirectory/PdfToImageServlet?pdfFile=/usr/share/cups/data/default-testpage.pdf'>

Upvotes: 3

Daryl H
Daryl H

Reputation: 634

<object width="400" height="400" data="helloworld.pdf"></object>

Upvotes: 1

GalacticCowboy
GalacticCowboy

Reputation: 11759

To stream the file to the browser, see Stack Overflow question How to stream a PDF file as binary to the browser using .NET 2.0 - note that, with minor variations, this should work whether you're serving up a file from the file system or dynamically generated.

With that said, the referenced MSDN article takes a rather simplistic view of the world, so you may want to read Successfully Stream a PDF to browser through HTTPS as well for some of the headers you may need to supply.

Using that approach, an iframe is probably the best way to go. Have one webform that streams the file, and then put the iframe on another page with its src attribute set to the first form.

Upvotes: -1

Related Questions