Pdf viewer html script

How to Display PDF in HTML Page using Javascript PDF.JS Library

Mozilla’s PDF.JS is PDF viewer made with HTML5 technologies. It can help your application in custom rendering of PDF files — showing a PDF file in a in your HTML page and browsing through its pages using Javascript.

Please note that PDF.JS is just a PDF viewer and not a PDF editor. It is not a library to create PDF files.

PDF.JS is used by Firefox internally to display PDF files. In fact PDF.JS is so good that even Opera decided to use it.

Example — Displaying PDF in a div Container

Click on the below button to display this PDF file.

Download Example Codes

PDF.JS APIs Used in This Tutorial

When you include the PDF.JS script files, you get a pdfjsLib global object. This object provides a number of APIs that you can call in your Javscript code.

    pdfjsLib.getDocument(< url: pdf_url >) This asynchonous method loads the PDF file. The return value is a Promise which resolves with a PDFDocumentProxy object. In simple words, PDFDocumentProxy is the handle of the current PDF file. pdf_url is the url to a PDF file in your server. Cross Domain PDFs are allowed but CORS headers need to be set in the server. In case you would like to display the PDF during upload, a local url of the PDF can be generated through URL.createObjectURL() function. You can also pass binary data as a parameter. If you have a base-64 encoded data, you can convert it to a binary string through atob function.

// normal url to a PDF or a local object url created while uploading PDF // pdf_doc holds the handle to the PDF document pdf_doc = await pdfjsLib.getDocument(< url: 'http://yourserver.com/sample.pdf' >); // binary data pdf_doc = pdfjsLib.getDocument(< data: binary_data >); 
var total_pages = pdf_doc.numPages;
// page holds the handle of the given PDF page number page = await pdf_doc.getPage(page_no); 
// get viewport at scale = 1 var viewport = page.getViewport(1); // height of the page var height = viewport.height; // width of the page var width = viewport.width; 
// get viewport at scale=1 var viewport = page.getViewport(1); // holds viewport properties where page will be rendered var render_context = < canvasContext: document.querySelector('#pdf-canvas').getContext('2d'), viewport: viewport >; // wait for the page to render await page.render(render_context); 

Writing Code, Step 1 : Including PDF.JS Script Files

  • Go to PDF.JS Home Page and download the files. There will be 2 files in the «build» directory. Include them in your HTML. In this tutorial, version 2.2 of PDF.JS has been used.
Читайте также:  Функция list в python примеры

Step 2 : Preparing HTML

 
Loading document .
Page of
Loading page .
  • #show-pdf-button button will start loading the PDF.
  • #pdf-loader is the container where a «PDF Loading» message would be shown while the PDF is being loaded.
  • #pdf-prev & #pdf-next are buttons that will go the Previous & Next page of the PDF.
  • #pdf-current-page will hold the current page no of the PDF.
  • #pdf-total-pages will hold the total number pages in the PDF.
  • #pdf-canvas is the canvas element where the PDF will be rendered.
  • #page-loader will show a «Page Loading» message while a page is being rendered.

Step 3 : Defining some Javascript variables

We need a few global variables that will hold properties used throughout the code.

var _PDF_DOC, _CURRENT_PAGE, _TOTAL_PAGES, _PAGE_RENDERING_IN_PROGRESS = 0, _CANVAS = document.querySelector('#pdf-canvas'); 
  • _PDF_DOC will hold the PDFDocumentProxy object that is resolved on the getDocument() Promise.
  • _CURRENT_PAGE will hold the current page number. _TOTAL_PAGES will hold the total no of pages in the PDF.
  • _PAGE_RENDERING_IN_PROGRESS is a flag that will hold whether a currently being rendered or not. If rendering of a page is in progress, then UI should not start rendering of another page. This is to prevent a page-content mismatch. Remember page rendering is asynchronous, it will take at least a few milliseconds to render a page.
  • _CANVAS will hold the canvas element.

Step 4 : Rendering the PDF with Javascript

Two custom functions shown below handle most of the code.

showPDF loads the PDF. It accepts the url of the PDF as parameter. On successful loading it calls the showPage function that will show the first page of the PDF.

showPage loads and renders a specified page of the PDF. While a page is being rendered, Previous and Next buttons are disbaled. A very important point is to note that we have to change the scale of the rendered page as per the width of the canvas element. In the current case, the width of the canvas element is less than the actual width of the PDF, so when PDF is rendered in the canvas it has to be scaled down.

Event handlers on the Previous / Next buttons simple decrement / increment the current page shown and call the showPage function.

var _PDF_DOC, _CURRENT_PAGE, _TOTAL_PAGES, _PAGE_RENDERING_IN_PROGRESS = 0, _CANVAS = document.querySelector('#pdf-canvas'); // initialize and load the PDF async function showPDF(pdf_url) < document.querySelector("#pdf-loader").style.display = 'block'; // get handle of pdf document try < _PDF_DOC = await pdfjsLib.getDocument(< url: pdf_url >); > catch(error) < alert(error.message); >// total pages in pdf _TOTAL_PAGES = _PDF_DOC.numPages; // Hide the pdf loader and show pdf container document.querySelector("#pdf-loader").style.display = 'none'; document.querySelector("#pdf-contents").style.display = 'block'; document.querySelector("#pdf-total-pages").innerHTML = _TOTAL_PAGES; // show the first page showPage(1); > // load and render specific page of the PDF async function showPage(page_no) < _PAGE_RENDERING_IN_PROGRESS = 1; _CURRENT_PAGE = page_no; // disable Previous & Next buttons while page is being loaded document.querySelector("#pdf-next").disabled = true; document.querySelector("#pdf-prev").disabled = true; // while page is being rendered hide the canvas and show a loading message document.querySelector("#pdf-canvas").style.display = 'none'; document.querySelector("#page-loader").style.display = 'block'; // update current page document.querySelector("#pdf-current-page").innerHTML = page_no; // get handle of page try < var page = await _PDF_DOC.getPage(page_no); >catch(error) < alert(error.message); >// original width of the pdf page at scale 1 var pdf_original_width = page.getViewport(1).width; // as the canvas is of a fixed width we need to adjust the scale of the viewport where page is rendered var scale_required = _CANVAS.width / pdf_original_width; // get viewport to render the page at required scale var viewport = page.getViewport(scale_required); // set canvas height same as viewport height _CANVAS.height = viewport.height; // setting page loader height for smooth experience document.querySelector("#page-loader").style.height = _CANVAS.height + 'px'; document.querySelector("#page-loader").style.lineHeight = _CANVAS.height + 'px'; var render_context = < canvasContext: _CANVAS.getContext('2d'), viewport: viewport >; // render the page contents in the canvas try < await page.render(render_context); >catch(error) < alert(error.message); >_PAGE_RENDERING_IN_PROGRESS = 0; // re-enable Previous & Next buttons document.querySelector("#pdf-next").disabled = false; document.querySelector("#pdf-prev").disabled = false; // show the canvas and hide the page loader document.querySelector("#pdf-canvas").style.display = 'block'; document.querySelector("#page-loader").style.display = 'none'; > // click on "Show PDF" buuton document.querySelector("#show-pdf-button").addEventListener('click', function() < this.style.display = 'none'; showPDF('https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf'); >); // click on the "Previous" page button document.querySelector("#pdf-prev").addEventListener('click', function() < if(_CURRENT_PAGE != 1) showPage(--_CURRENT_PAGE); >); // click on the "Next" page button document.querySelector("#pdf-next").addEventListener('click', function() < if(_CURRENT_PAGE != _TOTAL_PAGES) showPage(++_CURRENT_PAGE); >); 

Browser Compatibility

The above code will work good in all major browsers, including IE 10+.

Читайте также:  Java boolean wrapper if

Enabling Text Selection ?

To enable text selection, some extra steps need to be followed. See How to Enable Text Selection in PDF.JS for more.

PDF Viewer Javascript Plugin

A premium responsive PDF Viewer plugin is also available. It has some advanced features like embedding multiple PDF files in a single page, viewing PDF files when a link is clicked, modal & full-screen mode, finding out whether user has fully viewed the PDF etc.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

mozilla/pdf.js

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Update Stylelint to the latest version

Git stats

Files

Failed to load latest commit information.

Читайте также:  Javascript ввод данных пользователем

README.md

PDF.js is a Portable Document Format (PDF) viewer that is built with HTML5.

PDF.js is community-driven and supported by Mozilla. Our goal is to create a general-purpose, web standards-based platform for parsing and rendering PDFs.

PDF.js is an open source project and always looking for more contributors. To get involved, visit:

Feel free to stop by our Matrix room for questions or guidance.

Please note that the «Modern browsers» version assumes native support for the latest JavaScript features; please also see this wiki page.

PDF.js is built into version 19+ of Firefox.

  • The official extension for Chrome can be installed from the Chrome Web Store. This extension is maintained by @Rob—W.
  • Build Your Own — Get the code as explained below and issue gulp chromium . Then open Chrome, go to Tools > Extension and load the (unpackaged) extension from the directory build/chromium .

To get a local copy of the current code, clone it using git:

$ git clone https://github.com/mozilla/pdf.js.git $ cd pdf.js 

Next, install Node.js via the official package or via nvm. You need to install the gulp package globally (see also gulp’s getting started):

If everything worked out, install all dependencies for PDF.js:

Finally, you need to start a local web server as some browsers do not allow opening PDF files using a file:// URL. Run:

Please keep in mind that this assumes the latest version of Mozilla Firefox; refer to Building PDF.js for non-development usage of the PDF.js library.

It is also possible to view all test PDF files on the right side by opening:

In order to bundle all src/ files into two production scripts and build the generic viewer, run:

If you need to support older browsers, run:

This will generate pdf.js and pdf.worker.js in the build/generic/build/ directory (respectively build/generic-legacy/build/ ). Both scripts are needed but only pdf.js needs to be included since pdf.worker.js will be loaded by pdf.js . The PDF.js files are large and should be minified for production.

Using PDF.js in a web application

To use PDF.js in a web application you can choose to use a pre-built version of the library or to build it from source. We supply pre-built versions for usage with NPM and Bower under the pdfjs-dist name. For more information and examples please refer to the wiki page on this subject.

PDF.js is hosted on several free CDNs:

You can play with the PDF.js API directly from your browser using the live demos below:

More examples can be found in the examples folder. Some of them are using the pdfjs-dist package, which can be built and installed in this repo directory via gulp dist-install command.

For an introduction to the PDF.js code, check out the presentation by our contributor Julian Viereck:

More learning resources can be found at:

The API documentation can be found at:

Check out our FAQs and get answers to common questions:

Источник

Оцените статью