Recommended way to embed PDF in HTML?
Asked Answered
A

30

1390

What is the recommended way to embed PDF in HTML?

  • iFrame?
  • Object?
  • Embed?

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.

Amazonas answered 14/11, 2008 at 23:55 Comment(3)
Try pdf2htmlEX: github.com/coolwanglu/pdf2htmlEXPhilomena
There's a great comparison not just of specific solutions but general strategies, on the pdf2htmlEX repo's wiki. Also, though I haven't tried it, this seems to be a maintained fork.Musselman
Try approach described in sitelint.com/blog/…Frydman
P
606

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

Probe answered 15/11, 2008 at 0:1 Comment(6)
As noted in another answer, scribd actually uses pdf2swf to convert pdf filesJaquiss
I highly recommend against using scribd - I have just performed an experiment on a particular document and in firefox 4 it only displays the first 3 pages, whereas in IE9 its rendering text wrong - its offset some sections of the page. So technically speaking it is buggy. Additionally they expect you to subscribe to print or download documents! Essentially they are taking previously free documents and erecting a paywall around them.Hebe
PDF.js library actually looks like a very good solution, although the linked demo doesn't show it embedded in a page (it takes up the whole page). But it uses HMTL5 canvas, so it should be easy to embed, and it's fast. On the down side, it takes some js to use, unlike <object>: github.com/mozilla/pdf.js/blob/master/examples/helloworld/…Charade
pdf.js works poorly on tablet browsers such as Chrome. I also find it to be very, very slow for larger pdf documents.Rhizogenic
@RoccoTheTaco any alternative with high performance?Preindicate
Worth mentioning that A lot of in-browser PDF viewers do not communicate with the host system accessibility API. But pdf.js generates a semantic DOM tree which can make the document accessible to screen readers and other assistive technologies. I think the default pdf viewer in the chromium browsers also does something like this, but with various imperfections. This is an important consideration for public-sector content.Mendelism
F
683

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">
Foti answered 12/8, 2011 at 17:29 Comment(7)
Better to use an <object> tag so that you can include a fall-back.Macdonald
if you want to get sure it will be shown instead of auto download the pdf (as it happend to me) add type='application/pdf' to the embed tagPeluso
Better to use <object> tag because it can display alternate content in browsers that can't display pdfs. Can even put an <embed> tag in an <object> tag if you want. Ref: https://mcmap.net/q/41992/-lt-embed-gt-vs-lt-object-gtBerhley
@batfan, is it correct if I suppose nearly all solutions offered here address the challenges of displaying PDF document perfectly on screens other than mobiles? I have a webpage where the PDF is embedded and this works fine on the computer screens, but doesn't on the android phones that use Chrome. Please advise some tips/solution to this issue.Bellyache
@PKTG I just tested this and it's working for me. See below jsfiddle.net/196fv04sFoti
Adobe's Embed API is the best solution for mobiles. Safari isn't the primary focus of development for PDF.js (Source github.com/mozilla/pdf.js/issues/14725#issuecomment-1081590315)Kramer
I wouldn't touch the Adobe API solution with a barge-pole. Embed works very well and there is no chance of waking up to your customers complaining about Adobe adverts on their sites.Nebiim
P
606

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

Probe answered 15/11, 2008 at 0:1 Comment(6)
As noted in another answer, scribd actually uses pdf2swf to convert pdf filesJaquiss
I highly recommend against using scribd - I have just performed an experiment on a particular document and in firefox 4 it only displays the first 3 pages, whereas in IE9 its rendering text wrong - its offset some sections of the page. So technically speaking it is buggy. Additionally they expect you to subscribe to print or download documents! Essentially they are taking previously free documents and erecting a paywall around them.Hebe
PDF.js library actually looks like a very good solution, although the linked demo doesn't show it embedded in a page (it takes up the whole page). But it uses HMTL5 canvas, so it should be easy to embed, and it's fast. On the down side, it takes some js to use, unlike <object>: github.com/mozilla/pdf.js/blob/master/examples/helloworld/…Charade
pdf.js works poorly on tablet browsers such as Chrome. I also find it to be very, very slow for larger pdf documents.Rhizogenic
@RoccoTheTaco any alternative with high performance?Preindicate
Worth mentioning that A lot of in-browser PDF viewers do not communicate with the host system accessibility API. But pdf.js generates a semantic DOM tree which can make the document accessible to screen readers and other assistive technologies. I think the default pdf viewer in the chromium browsers also does something like this, but with various imperfections. This is an important consideration for public-sector content.Mendelism
D
383

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.

Duer answered 10/3, 2010 at 13:38 Comment(5)
One thing that should be mentioned is that there's an upper limit to the size of the PDF that can be displayed. I think it's currently 10MB/100 pages. PS: I don't think the viewer is "unofficial"; they even have a how-to page that constructs the embed URL for you: docs.google.com/viewerClinometer
This option works great, but you have to make your PDFs publicly accessible, which for me is not always an option.Rhaetian
@riot_starter this solution no longer works, if you are fully logged out of google it loads fine, if you are fully logged in it loads fine, however if you are in between (whatever that means) it asks you for your password. And in the case of the iframe it just does not load.Attar
You are allowed to set the privacy of any Google Docs between public, sign-in required, and private. It is definitely an official feature, considering any document on Google Docs has an embed option.Tolidine
Another thing that should be mentioned is the "you have made too many requests recently" warning , which is a limitation.Goodyear
S
141

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>
Sapota answered 2/3, 2011 at 18:36 Comment(3)
That's the best solution because is using the browser capabilities and not a complicated third-party solution. In all modern browsers (IE9, FF or Chrome) PDF should embed nicely. Sorry for IE 6/7 users. They have to upgrade. We've stop supporting these browsers long time ago. :(Hunter
This solution works best. I have tried other solutions from stackoverflow but I could not get to display pdf. This is the best solution.Intercalary
I am trying to show pdf file form s3 presigned URL. My file types are set as pdf in S3. Unfortunately embed, ojbect, iframe all triggers download without showing the pdf.Laughable
D
74

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>
Disembroil answered 15/5, 2014 at 14:36 Comment(5)
This will not work in browsers if pdf addon in not installed or out of dateDirections
Also, this will not validate for those that are concerned with code validation.Freezedry
This worked great for me, whereas using the embed tag by itself was deemed unsafe by Chrome and Firefox.Pathology
For some reason on Android (chrome) it doesn't embed the PDF and instead offers to download it. On iPhone (safari) it shows only the first page of the PDF.Torture
@IvanRubinson Android on phones and on some tablets does not have the capability to display embedded pdfs.. also for some iOS mobile devices (iPhone, iPad).. on the other iOS devices (iPad Pro, ..) only the first page of the pdf will be shown.. this is a known issue on iOS which has been there for a very long time..Horny
D
26

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>
Dipole answered 14/11, 2008 at 23:55 Comment(4)
This doesn't seem to work. I always end up with a blank grey screen instead of the pdf. But switching src for data, as in @Gayle's answer, does work.Richrichara
I am using Chrome 44 and it won't work. I also tried switching data to src.Freezedry
type="application/pdf" fixes the problem. Works fine in chrome.Haleigh
Including type="application/x-pdf" will now actually prevent rendering on both Chrome and FireFox. It should be removed.Nitrogen
G
22

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.

Grefe answered 6/12, 2011 at 18:17 Comment(9)
Or convert the image to PNG using an application, such as Preview on Mac.Mandel
but can you do that programmatically?Grefe
what if the document has more than 1 page? I guess you will only show the first page thenVibrato
@Vibrato it's been a while but I was able to use it on 2 or 3 page-long PDFs. Wouldn't be wise to go much larger than that, I think mobile browsers have a hard time display images like that. This is why I called it the "quick and dirty" method, but it's a good one I think so long as the PDF is no more than a few pages.Grefe
If you open the PDF using the zend library then you can do a foreach($pdf->pages as $page) and create an image for each pageLatonya
In modern times, webp probably makes much more sense than png (much, much smaller for the same content size).Manometer
@CharlesDuffy I wrote this answer 12 years ago...Grefe
@DanMantyla That's why I qualified my comment with "in modern times", to make it clear that it wasn't a critique of the answer in the original context but a commentary on why someone might consider adjusting it today.Manometer
(though something that was true even twelve years ago is that there's security impact here: You wouldn't want a file named $(rm -rf ~).pdf -- and yes, that's a valid filename -- to be converted this way; it's much safer to use an exec form that takes a list/array of arguments rather than a string that requires shell parsing)Manometer
O
15

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>
Overlay answered 16/6, 2019 at 21:56 Comment(1)
Chrome understands that embed is like Flash and it automatically blocks it. iFrame with bootstrap is a good option.Isherwood
F
13
  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/

Fiord answered 19/8, 2016 at 0:30 Comment(3)
This was a very good solution and worked well in conjunction with bootstrap styling. It all went on top of other bootstrap elements.Uniat
Did you try with blob file? I used this with pdf.output('bloburl') from lib jspdf but it seems not working on IE11.Inflection
This is a good solution but it doesn't work even the latest iPhone safari browser :(Isherwood
C
13

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.

Colligan answered 20/10, 2017 at 5:51 Comment(2)
I'm sorry, but i don't understand, what kind of value does variable "transferData " have?Onomatopoeia
Hi @Kate, In our case, we generate the PDF based on a user's input in our web form. "transferData" contains the data which are sent as JSON to the PDF generation function in the web API. I've added a line more code for clarification.Colligan
Q
12

FDView combines PDF2SWF (which itself is 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 need better results then Ghostview has some ability to convert PDF documents into other formats which you may be able to more easily build a Flash viewer for.

But for simple PDF documents, FDView should work reasonably well.

Queridas answered 15/11, 2008 at 23:11 Comment(2)
Is FDView available anywhere else? code4net.com seems to have disappeared.Nutty
@Michael Not that I can easily find. I'll leave this answer up on the off chance that someone re-hosts fdview somewhere else.Queridas
M
7

Scribd no longer require you to host your documents on their server. If you create an account with them so you get a publisher ID. It only takes a few lines of JavaScript code to load up PDF files stored on your own server.

For more details, see Developer Tools.

Mover answered 15/11, 2010 at 23:50 Comment(4)
Could you post another link showing how this is done? It's not clear from the link you posted.Clinometer
Seems like they have updated their website and changed this page. I think this page has the content I was referring to in my original post: scribd.com/developers/api?method_name=Javascript+APIMover
I wish I could like this more than once, it works perfectly. Scroll to the bottom of the website and click API to see examples.Rhizogenic
Signups are now closed for scribd.Reticule
A
6

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>
Aloisius answered 17/5, 2018 at 9:26 Comment(0)
R
6

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>
Rental answered 17/1, 2022 at 11:30 Comment(0)
P
4

PdfToImageServlet using ImageMagick's convert command.

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

Pot answered 23/2, 2017 at 20:9 Comment(0)
S
4

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>
Spicy answered 18/12, 2019 at 21:37 Comment(0)
C
2

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='http://bit.ly/1JxrtjR' frameborder='0' allowfullscreen></iframe>
Casket answered 19/5, 2015 at 23:32 Comment(0)
J
2
<object width="400" height="400" data="helloworld.pdf"></object>
Jargon answered 3/2, 2016 at 14:36 Comment(0)
R
2
  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.

Reprise answered 18/7, 2018 at 13:10 Comment(0)
N
1

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.

Nevanevada answered 15/11, 2008 at 23:53 Comment(1)
@downvoter care to explain why you're anonymously downvoting a 10-year-old answer?Nevanevada
F
1

I answered this question already somewhere else, however, I did an evaluation between multiple solutions. Also if you are planning for commercial use, these might be helpful:

free solutions

  • iframe: Just use an iframe, however, this is not what most people search here.
  • [Google Docs Preview] Google docs has a preview (See other answer here)
  • Pdf.js is the open source solution without external dependencies
  • Adobe offers a 'free' PDF Embed API - recommended approach if you are okay with a cloud based solution.

Commercial Providers

  • Pdf.js Express is commercialized extension to Pdf.js (worst performing product, not expensive)
  • PSPDFKit - Provder from Austria with rather good business support (moderate pricing, good product)
  • Foxit - Chinese company providing a PDF web solton as well. (cheapest commercial offer)
  • PDFTron - US-based competitor to PSDPDFkit ( more costly but also mot advanced)

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

Fallible answered 23/9, 2022 at 16:15 Comment(0)
B
0

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>
Brawner answered 15/8, 2020 at 18:31 Comment(0)
S
0

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>

Seta answered 18/8, 2020 at 3:35 Comment(0)
S
0

Go with native solution if possible, it's always the best solution as it comes natively from browser (using embed or iframe), or you can use this tiny lib to support you on that: https://pdfobject.com

Most people recommend using PDF.JS which is famous. It has been working fine until I need to work with ShadowDOM. Some pages are in blank (white color), some in black color without any reason. Impossible for me to get to know what's happening, and it's in production :).

Stinky answered 27/10, 2022 at 11:30 Comment(0)
L
0

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

Lazarolazaruk answered 28/3 at 23:42 Comment(0)
D
-1

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>
Depository answered 2/1, 2021 at 23:36 Comment(0)
B
-1
<embed src="data:application/pdf;base64,..."/>
Bucksaw answered 6/2, 2021 at 5:54 Comment(1)
Good answers include some descriptionTreiber
T
-2

If you don't want to host PDF.JS on your own, you could try DocDroid. It is similar to the Google Drive PDF viewer but allows custom branding.

Thermoluminescence answered 18/9, 2017 at 16:3 Comment(0)
R
-2

Modern "full page screenshot" services or scripts nowadays are capable of producing long screenshots of full HTML and PDF pages and convert them into JPG or PNG files which can then be embedded as img element.

Reagan answered 2/6, 2022 at 10:55 Comment(0)
M
-11

I found this works just fine and the browser handles it in firefox. I have not checked IE...

<script>window.location='url'</script>
Mickel answered 13/10, 2017 at 13:44 Comment(3)
What is this supposed to achieve? I cannot see how it answers the question.Valedictorian
When I am embedding a PDF in my HTML, I find the best way is to have a link to this document. such as <a href="server1.network/trifold_JonesChiro.pdf" target='_blank'>Client Portal Trifold (sample)</a> it is sometimes a clean answer to open a page and show the pdf vs tring to place it in the html. It also allows the pdf to stay open in a tab.Mickel
So your recommendation is to link, not embed? That's fine, but as an answer this is quite unclear.Valedictorian

© 2022 - 2024 — McMap. All rights reserved.