To maintain issues easy, we’ll be rendering just one web page contained in the canvas at any given time. We’ll, nonetheless, enable customers to change to the earlier web page or the subsequent web page by urgent a button. Moreover, to show the present web page quantity, and to permit customers to leap to any web page they want, our interface may have an enter area.
To assist zoom operations, add two extra buttons to the interface: one to zoom in and one to zoom out.
1
id="zoom_controls">
2
3
4
On the finish of this part, the online web page code appears to be like like this.
Now {that a} bare-bones person interface for our JavaScript PDF viewer is prepared, let’s add PDF.js to our net web page. As a result of the most recent model of the library is accessible on CDNJS, we are able to achieve this by merely including the next traces in the direction of the top of the online web page.
Should you choose to make use of a neighborhood copy of the library, you possibly can obtain it from the pdfjs-dist repository.
3. Loading a PDF File
Earlier than we begin loading a PDF file, let’s create a easy JavaScript object to retailer the state of our PDF viewer in JS. Inside it, we’ll have three gadgets: a reference to the PDF file itself, the present web page index, and the present zoom degree.
1
2
varmyState={
3
pdf:null,
4
currentPage:1,
5
zoom:1
6
}
7
8
// more code here
9
At this point, we can load our PDF file by calling the getDocument() method of the pdfjsLib object, which runs asynchronously.
Note that the getDocument() method internally uses an XMLHttpRequest object to load the PDF file. This means that the file must be present either on your own web server or on a server that allows cross-origin requests.
If you don’t have a PDF file handy, you can get the one I’m using from Wikipedia.
Once the PDF file has been loaded successfully, we can update the pdf property of our state object.
Lastly, add a call to a function named render() so that our PDF viewer in JS automatically renders the first page of the PDF file. We’ll define the function in the next step.
4. Rendering a Page
By calling the getPage() method of the pdf object and passing a page number to it, we can get a reference to any page in the PDF file. For now, let’s pass the currentPage property of our state object to it. This method too returns a promise, so we’ll need a callback function to handle its result.
Accordingly, create a new function called render() containing the following code:
To actually render a page, we must call the render() method of the page object available inside the callback. As arguments, the method expects the 2D context of our canvas and a PageViewport object, which we can get by calling the getViewport() method. Because the getViewport() method expects the desired zoom level as an argument, we must pass the zoom property of our state object to it.
1
var canvas = document.getElementById("pdf_renderer");
2
var ctx = canvas.getContext('2d');
3
4
var viewport = page.getViewport(myState.zoom);
The dimensions of the viewport depend on the original size of the page and the zoom level. In order to make sure that the entire viewport is rendered on our canvas, we must now change the size of our canvas to match that of the viewport. Here’s how:
1
canvas.width = viewport.width;
2
canvas.height = viewport.height;
At this point, we can go ahead and render the page.
1
page.render({
2
canvasContext: ctx,
3
viewport: viewport
4
});
Putting it all together, the whole source code looks like this.
If you try opening the web page in a browser, you should now be able to see the first page of your PDF file.
You may have noticed that the size of our PDF viewer currently depends on the size of the page being rendered and the zoom level. This is not ideal because we don’t want the layout of our web page to be affected while users interact with the PDF viewer in JavaScript.
To fix this, all we need to do is give a fixed width and height to the
element encapsulating our canvas and set its overflow CSS property to auto. This property, when necessary, adds scroll bars to the
element, allowing users to scroll both horizontally and vertically.
Add the following code inside the tag of the web page:
1
2
#canvas_container{
3
width:800px;
4
height:450px;
5
overflow:auto;
6
}
7
You are, of course, free to change the width and height or even use media queries to make the
element match your requirements.
Optionally, you can include the following CSS rules to make the
element seem more distinct:
1
#canvas_container {
2
background: #333;
3
text-align: center;
4
border: solid 3px;
5
}
If you refresh the web page now, you should see something like this on your screen:
5. Changing the Current Page
Our JavaScript PDF viewer is currently capable of showing only the first page of any PDF file given to it. To allow users to change the page being rendered, we must now add click event listeners to the go_previous and go_next buttons we created earlier.
Inside the event listener of the go_previous button, we must decrement the currentPage property of our state object, making sure that it doesn't fall below 1. After we do so, we can simply call the render() function again to render the new page.
Additionally, we must update the value of the current_page text field so that it displays the new page number. The following code shows you how:
1
document.getElementById('go_previous')
2
.addEventListener('click', (e) => );
Similarly, inside the event listener of the go_next button, we must increment the currentPage property, while ensuring that it doesn’t exceed the number of pages present in the PDF file, which we can determine using the numPages property of the _pdfInfo object.
Lastly, we must add a key press event listener to the current_page text field so that users can directly jump to any page they desire by simply typing in a page number and hitting the Enter key. Inside the event listener, we need to make sure that the number the user has entered is both greater than zero and less than or equal to the numPages property.
1
document.getElementById('current_page')
2
.addEventListener('keypress', (e) => {
3
if(myState.pdf == null) return;
4
5
// Get key code
6
var code = (e.keyCode ? e.keyCode : e.which);
7
8
// If key code matches that of the Enter key
9
if(code == 13) {
10
var desiredPage = document.getElementById('current_page').valueAsNumber;
Our PDF viewer in JavaScript can now display any page of the PDF file.
6. Changing the Zoom Level
Because our render() function already uses the zoom property of the state object while rendering a page, adjusting the zoom level is as easy as incrementing or decrementing the property and calling the function.
Inside the on-click event listener of the zoom_in button, let’s increment the zoom property by 0.5.
1
document.getElementById('zoom_in')
2
.addEventListener('click', (e) => {
3
if(myState.pdf == null) return;
4
myState.zoom += 0.5;
5
6
render();
7
});
And inside the on-click event listener of the zoom_out button, let’s decrement the zoom property by 0.5.
1
document.getElementById('zoom_out')
2
.addEventListener('click', (e) => {
3
if(myState.pdf == null) return;
4
myState.zoom -= 0.5;
5
6
render();
7
});
You are free to add upper and lower bounds to the zoom property, but they are not required.
This is what it looks like when it’s all put together.
Our PDF viewer in JavaScript is prepared. Should you refresh the online web page once more, you need to be capable to view all of the pages current within the PDF doc in JavaScript and in addition zoom in to or zoom out of them.
Congratulations! You’ve Realized to Create a Viewer for PDF Paperwork in JavaScript!
You now know the best way to use PDF.js to create a customized JavaScript PDF viewer on your web site. Together with your new viewer for PDF paperwork in JavaScript, you possibly can confidently supply a seamless person expertise whereas displaying your group's brochures, white papers, types, and different paperwork usually meant to be distributed as arduous copies.