Have you ever had the need to view PDF documents within web pages? If the answer is yes then don’t miss this article.

Anyone who develops internet or intranet portals, especially in the industrial field, sooner or later faced the problem of how to easily view PDF with HTML5 within internet pages.

The main problem is that PDF documents have always been seen and treated as foreign objects to the HTML page. To view them correctly, they are usually either downloaded and opened later with a viewer (eg Acrobar Reader), or opened in a separate browser window where the browser renders it full screen.

These two methods are inelegant, because they force the user to interact with a second window, and then with a third, and a fourth, and so on for each PDF document he wants to open. Imagine having to constantly consult different PDFs each time. You would be inundated with windows to close. Furthermore, the user is forced to abandon the starting navigation page, in favor of the one that displays the PDF in full screen.

This way of opening PDFs becomes unmanageable in case I need to view them inside a Multimedia Kiosk.

Totem multimediale
Esempio di chiosco multimediale

The initial scope

In this article I want to share my experience with you, hoping it will be useful for you.

My specific need was to create a Web Multimedia Kiosk with a touch interface for searching and consulting technical drawings in PDF format in the various production departments of a factory.

In the previous article I explained what a multimedia kiosk is and how to make a web kiosk with Raspberry Pi 4.

In this article I want to share the second part of the project with you explaining how I made the software part that displays PDF documents.

The library that works magic

The whole project is based on the PDF.js library which within the web page is able to load a document and PDF and display it in pure HTML5 format.

Basically PDF.js “unmounts” the PDF and remounts it displaying native HTML5 objects. What is displayed is nothing more than HTML5 and no longer a PDF. simply magical!

This library is the result of an Open Source project of the “Mozilla Foundation” and is freely downloadable from his Official GitHub repository and usable under the Apache 2.0 license.

I also made it all usable from a touch screen, therefore usable from a multimedia kiosk.

Try the DEMO ONLINE or on your computer

If you do not have time or desire to continue with the installation of the software, or you want to quickly realize how it works, try the demo un my website: click here.

Once the demo is open, type LANDSCAPE or PORTRAIT in the search bar at the top and then click on the VIEW PDF button. A PDF document will appear for you to consult.

Otherwise, continue reading this article, I will explain how to try it on your PC.

1. The LAMP server

First we need to prepare a LAMP server (Linux Apache MySql Php).

In my case I have set up a LAMP Linux machine but if you are not familiar with Linux you can safely download the XAMPP package for your operating system on your PC and everything will work the same.

Download XAMPP on your PC and launch the setup.exe.

When he asks you only these packages check: Apache, MySQL, PHP e phpMyAdmin

From here on I assume an installation on a Windows machine, so that most readers can test it on their PC.

If you have Mac OS the procedure described here is similar, so don’t worry.

Then install XAMPP in the default folder C:\xampp

With Windows Explorer located in that folder and double click on the file xampp-control.exe which opens the XAMPP control panel.

Pannello di controllo di XAMPP
Pannello di controllo di XAMPP

Start the Apache server by clicking the first “Start” button in the top center of the window, the one corresponding to the line of the Apache module “. If all goes well, the word Apache is highlighted in green and the” Start “button changes to” Stop “as you can see from the image below.

Apache avviato nel pannello di controllo di XAMPP

as a further check, open your browser and open the page: http://localhost

you should see the welcome page in xampp like this one below.

Benvenuti in XAMPP
pagina di benevenuto di XAMPP

2. Download the “demo” software from my GitHub repository

Download the project software from my GitHub repository Web Kiosk PDF Viewer and unzip it in the folder C:\xampp\htdocs

The zip file of the project already contains a “web-kiosk-pdf-viewer-main” folder, so in the end you will have all the files in the folder C:\xampp\htdocs\web-kiosk-pdf-viewer-main .

Inside this folder you find a file “config.php”.

Inside you will find the address of the DEMO script. if you have followed the previous steps exactly as I explained them then you will not have to change it, otherwise change line number 3 by setting the correct url according to the installation folder you used.

<?php
// BASE URL OF THE SITE
define('CONFIG_BASE_URL', 'http://localhost/web-kiosk-pdf-viewer-main');
$HOME=CONFIG_BASE_URL;
?>

3. Run the demo

To view the demo open with a browser the url set in point 2, if you have not changed it, it is: http://localhost/web-kiosk-pdf-viewer-main

A search engine appears with the focus on a text field. In that field type LANDSCAPE or PORTAIT and click on the “VIEW PDF” button.

As the project was designed for a multimedia kiosk with a touch screen interface only and no keyboard, the main page automatically shows a virtual javascript keyboard every time you focus on the file name search field.

The keyboard used is a virtual keyboard that you can find at this link. Having tried several, I highly recommend this one here. It is very versatile and configurable, you can choose which keys to display, the style, the behavior. really worth trying!

The names LANDSCAPE and PORTAIT are also just the names of two example PDF documents that I have placed in the “PDF_FILES” folder: “PDF_FILES”.

tastiera virtuale
tastiera virtuale

There are a few possible commands you can perform on the PDF. I mention them a few.

Zoom:

lo zoom si può regolthe zoom can be adjusted simply with the pinch to Zoom IN and OUT gesture as you normally do on a mobile phone, obviously provided you open the page from a touch screen device.

alternatively you can click on the + and – buttons to increase or decrease the zoom factor, or you can select one of the preset items from a drop-down menu which are predefined zoom levels (50%, 75%, 100%, 125% , etc …) or choose to fit the zoom to the whole page or to the width only

selezione dello zoom in PDF.js

Rotating the document:

It is possible to rotate the document clockwise or counterclockwise 90 ° at a time by using the “Rotate clockwise” and “Rotate counterclockwise” buttons which are found by expanding the toolbar on the right.

barra degli strumenti

Drag and drop the document

The “Hand tool” is used if you are NOT using a touch device and you want to “grab” the PDF with the mouse to drag it in various directions, useful when the zoom level is high and you want to move to another area of the document. Otherwise, if you are using a touch device, just keep placing a finger while moving it in the desired direction.

To be able to drag and zoom on the document this I installed at the end of the file “pdf_viewer.php” (the page that contains the PDF viewer) of the javascript code to enable the gestures.

<script>
    let pinchZoomEnabled = false;
    function enablePinchZoom(pdfViewer) {
        let startX = 0, startY = 0;
        let initialPinchDistance = 0;        
        let pinchScale = 1;    
        const viewer = document.getElementById("viewer");
        const container = document.getElementById("viewerContainer");
        const reset = () => { startX = startY = initialPinchDistance = 0; pinchScale = 1; };
        // Prevent native iOS page zoom
        //document.addEventListener("touchmove", (e) => { if (e.scale !== 1) { e.preventDefault(); } }, { passive: false });
        document.addEventListener("touchstart", (e) => {
            if (e.touches.length > 1) {
                startX = (e.touches[0].pageX + e.touches[1].pageX) / 2;
                startY = (e.touches[0].pageY + e.touches[1].pageY) / 2;
                initialPinchDistance = Math.hypot((e.touches[1].pageX - e.touches[0].pageX), (e.touches[1].pageY - e.touches[0].pageY));
            } else {
                initialPinchDistance = 0;
            }
        });
        document.addEventListener("touchmove", (e) => {
            if (initialPinchDistance <= 0 || e.touches.length < 2) { return; }
            if (e.scale !== 1) { e.preventDefault(); }
            const pinchDistance = Math.hypot((e.touches[1].pageX - e.touches[0].pageX), (e.touches[1].pageY - e.touches[0].pageY));
            const originX = startX + container.scrollLeft;
            const originY = startY + container.scrollTop;
            pinchScale = pinchDistance / initialPinchDistance;
            viewer.style.transform = `scale(${pinchScale})`;
            viewer.style.transformOrigin = `${originX}px ${originY}px`;
        }, { passive: false });
        document.addEventListener("touchend", (e) => {
            if (initialPinchDistance <= 0) { return; }
            viewer.style.transform = `none`;
            viewer.style.transformOrigin = `unset`;
            PDFViewerApplication.pdfViewer.currentScale *= pinchScale;
            const rect = container.getBoundingClientRect();
            const dx = startX - rect.left;
            const dy = startY - rect.top;
            container.scrollLeft += dx * (pinchScale - 1);
            container.scrollTop += dy * (pinchScale - 1);
            reset();
        });
    }
    document.addEventListener('webviewerloaded', () => {
        if (!pinchZoomEnabled) {
            pinchZoomEnabled = true;
            enablePinchZoom();
        }
    });
</script>

Full screen presentation (powerpoint style)

The toolbar on the right also allows you to run a full-screen presentation of the document, as if it were a PowerPoint projection

Print

It is possible to print the document by clicking on the printer symbol

Download PDF

It is possible to download the original PDF.

4. Customize the demo to view remote folders

To see how it works you can put all the PDF documents you need to view inside the folder “PDF_FILES”.

If, on the other hand, you work on Linux machines, you want to do something more sophisticated, you can do as I did: map a remote folder (perhaps residing on a file server) to a local folder on the linux machine.

For example in my file /etc/fstab there is a command to mount the remote folder DISEGNI_DI_PRODUZIONE_ which is in my Windows file server named “fs”, on the local folder PDF_FILES

the command to put in the /etc/fstab file is the following:

//fs/DISEGNI_DI_PRODUZIONE_PDF /srv/PDF_FILES cifs username=miousername@firex.local,password=miapassword,file_mode=0755,dir_mode=0755,gid=48,uid=48 0 0

5. Sending the PDF file to the browser

A note just to explain how the physical PDF file is sent to the browser, for the PDF.js library to view it.

The file /ajax/get_pdf_files.php takes care of it, which is called up by the interface from the main interface when the ENTER or VIEW PDF or VIEW keys of the virtual keyboard are pressed.

<?php
require_once "../config.php";

$filename=$_GET['filename'];

header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:inline;filename='".$filename."'");

 $filename_path="../PDF_FILES/".basename($filename).".pdf";
 $filename_path_not_fount="../PDF_FILES/PDF_NOT_FOUND.pdf";
 
 if(file_exists($filename_path))
 {
   // The PDF source is in original.pdf
   readfile($filename_path);	
 }
 else
 {
	//die("File not found: ".$filename_path);
	readfile($filename_path_not_fount);	
 }
?>

The file as seen from the above code only verifies that it exists. If it exists, it sends it to the browser with the instruction

readfile($filename_path);

If the file does not exist, however, a PDF file will be sent with a message inside saying that the file was not found.

readfile($filename_path_not_fount);

The rest of the magic will be done by the PDF.js library by rendering it in HTML 5.

Download and use the sources

I remind you that you can find the sources of this demo freely downloadable from my GitHub Repository named “web-kiosk-pdf-viewer”

Help me support this blog

If you want you can help me concretely to support this blog. You can do it with a free donation, by credit card or paypal. I will be grateful to you.