Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline PDF viewer

Tags:

html

ruby

pdf

Is there is PDF viewer which I can embed into my HTML and which I can style as I want.

Actually I need to show some page of PDF file and customize my own UI (few buttons to turn over the pages and commenting).

And if there is any Ruby solution (It's not actually about programming, as I understand) it will be great.

I want to show pdf because:

  • User can copy text
  • Text is in original layout

So I don't want to show it as images or as a converted text. But I want to show page in simple design. Without Flex or whatever.

like image 948
fl00r Avatar asked Nov 27 '22 22:11

fl00r


2 Answers

Yes, it is possible, with HTML5!

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

This is a pure-javascript library that uses HTML5 functions to open a PDF file and render it in the page. I successfully test the library in following browsers:

  • IE9 and current version of Google Chrome, Firefox, Safari
  • IE8 and lower do not support pdf.js (lacking HTML5 functions)

Usage

Include the javascript libraries in the HTML file and add an -element ( is HTML5 element, so it will work only in HTML5 browsers):

<body>
  <canvas id="the-canvas" style="border:1px solid black;"/>
</body>

Use a javascript call similar to this to render the PDF inside this canvas:

PDFJS.getDocument('your-file-goes-here.pdf').then(function(pdf) {
  pdf.getPage(1).then(function(page) {
    var scale = 1.5;
    var viewport = page.getViewport(scale);

    var canvas = document.getElementById('the-canvas');
    var context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    var renderContext = {
      canvasContext: context,
      viewport: viewport
    };
    page.render(renderContext);
  });
});
like image 175
Philipp Avatar answered Dec 05 '22 02:12

Philipp


Other than a few browsers that have PDF viewers built in (Chrome comes to mind), PDF display is handled by external plugins, over which you have no control. You can't embed a PDF into a page, other than via iframes, and even then it's a completely external app from the browser, and not subject to css styling rules.

I don't see what Ruby has to do with this, as that'd be a server-side operation, and you're talking about client-side preparing. You could use Ruby (or most any other language) to extract the PDF's text, but you explicitly say you don't want to do that.

like image 36
Marc B Avatar answered Dec 05 '22 01:12

Marc B