In recent Using Google Docs Viewer to preview documents online article we reviewed the use of Google Docs Viewer for document preview purposes. While this is a viable approach two main concerns arise:
- dependency on third party service
- security issues
For those who is looking for another solution there is a brilliant Javascript library named ViewerJS that supports PDF files as well as Open Office formats (.odp, .odt, .ods). This library can display documents right in the web browser, no need to install any additional software. Documents can be displayed either in full page mode or embedded into other pages. See some examples.
In this article we'll show how you can use ViewerJS library in your PHPRunner projects. Before you do that feel free to check the live demo.
Here are integration steps:
1. Download ViewerJS library (use first download link). Unzip ViewerJS folder to source folder of your project. This is how it supposed to look if installed properly.
2. Setup one of fields as document upload. You can use either basic upload or multiple-files upload. Set 'View as' type of this field to 'Custom' and use the following code.
Basic upload
- $mftable = "carscars";
- $mfield = "descr";
- $ext=strtoupper(substr($value,strlen($value)-4));
- if($ext == ".PDF")
- $value='<a target="_blank" href="ViewerJS/#../mfhandler.php?file='.$value.'&table='.$mftable.'&field='.$mfield.'&pageType=list&key1='.$data[" id"].'"="">'.$value.'</a>';
- else
- $value='<a target="_blank" href="mfhandler.php?file='.$value.'&table='.$mftable.'&field='.$mfield.'&pageType=list&key1='.$data[" id"].'"="" dir="LTR">'.$value.'</a>';
In this code $mftable is the name of the table, $mfield is the name of the field that stores documents.
Multiple-files upload
- $arrfile = my_json_decode($value);
- $value="";
- $mftable = "carscars";
- $mfield = "descr";
- for($i=0;$i < count($arrfile);$i++){
- if($value)
- $value.=", ";
- if($arrfile[$i]["type"] == "application/pdf")
- $value.='<a target="_blank" href="ViewerJS/#../mfhandler.php?file='.$arrfile[$i][" usrname"].'&table=".$mftable." &field=".$mfield." &pagetype="list&key1='.$data["id"].'"">'.$arrfile[$i]["usrName"].'</a>';
- else
- $value.='<a href="mfhandler.php?file='.$arrfile[$i][" usrname"].'&table=".$mftable." &field=".$mfield." &pagetype="list&key1='.$data["id"].'"" dir="LTR">'.$arrfile[$i]["usrName"].'</a>';
- }
Some additional bits of info. This sample code will display PDF files only, other files simply be downloaded to the end user device. This code is designed to open document preview in new window. If you like to open it in the same window remove target=_blank from the code.