pdf.js is a great cross platform pdf viewer solution, here I explain how to use it
Install PDF.js viewer on your server
Instructions 1 to 7 are to install node as a webserver for the PDFViewer, they not necessary if you are already running a webserver (i.e. Apache).
1) install git
sudo yum install git
2) make or use a pdf.js install directory on your server
mkdir libs/ cd libs
3) Now you have a server directory /home/user/public_html/libs, for example. Clone the git project into this directory
git clone git://github.com/mozilla/pdf.js.git pdfjs
4) there will be a new directory created called pdfjs which is the project directory, cd into this directory. Then we have to install the node server
sudo yum install nodejs
5) then run the server (in the background so we can carry on), to do this robustly I am using forever its runs the server in the background robustly, to install this we first have to install the node package manager (npm) then use npm to install forever
sudo yum install npm;
sudo npm install forever --global
6) then we can start the pdf server
forever start make.js server
7) you can check that it is running with
forever list
8) then we can display the pdf with the following html code
<iframe style="width:100%;height:500px" src="https://www.mydomain.com/libs/pdfjs/web/viewer.html?file=http://www.mydomain.com/mypdf.pdf"></iframe>
You now have a nice pdf viewer for your website guests that doesn’t depend on any plugins.
You can see the finished pdfs on the bottom of these webpages image analysis of crystals and steerable filters for detecting crystals
Using PDF.js as a fallback for native pdf viewer plugin
PDF.js is at the moment a bit buggy, (ie. printing support is not available – hopefully this will change in the future!).
In order to provide the best experience for all users we shall: use the native pdf viewer plugin (i.e. adobe) and if not available use pdf.js as a fallback.
9) Download pdfobject.min.js from the pdfobject Github site , save to lib directory
10) Add the following code to the header region of your webpage (change the width, height in the style to suit)
<script>
var pdf_url="http://www.mydomain.com/mypdf.pdf";
window.onload = function (){
var myPDF = new PDFObject({ url: pdf_url }).embed("pdfdoc")
if(!myPDF){
document.getElementById('pdfdoc').innerHTML += '<iframe style="width:100%;height:500px" src="https://www.mydomain.com/libs/pdfjs/web/viewer.html?file='+pdf_url+'"></iframe>';
}
};
11) Then in the body section of your html page replace the iframe html code (from section 8) with the following html code
<div id="pdfdoc" style="width:100%;height:500px"></div>
then you are good to go!
* Code conversion to HTML friendly display format was done using the Code2HTML converter
2 thoughts on “how to use pdf.js to display pdf documents”