Rails 5 with PDF.js

Opening PDFs directly on the web page was one of the requirements for my recent project. The obvious choice was to use the PDF.js library but using it directly is not as easy as I expect. You have to ensure separate page for PDF viewing and a lot of additional assets. Fortunately, there is a gem (as usually) which does all of this for you. A pdfjs_viewer-rails works as a mountable rails engine so you don't need to worry about anything. Here is the setup process.

Add gem to the project

Modify your Gemfile file, add the following line:

gem 'pdfjs_viewer-rails'

Then add necessary routes inside config/routes.rb:

mount PdfjsViewer::Rails::Engine => "/pdfjs", as: 'pdfjs'

Put that line anywhere between

Rails.application.routes.draw do
  # e.g. here
end

lines.

If you want to have an <iframe> with PDF.js preview just add the following lines to one of you view files e.g. app/views/layouts/application.html.erb:

<body>
  <iframe src="<%= link_to "display using the full viewer", pdfjs.full_path(file: "/sample.pdf") %>"></iframe>
</body>