3.1 KiB
title | description | type | page_title | slug | position | tags | teampulseid | ticketid | pitsid |
---|---|---|---|---|---|---|---|---|---|
How to Open PDF Files Inside Your App Using PDF.js | Open PDF files on iOS, Android and Windows Phone devices using PDF.js | how-to | Open PDF Files Inside Your App Using PDF.js | open-pdf-inside-app | pdf, pdf.js, custom |
Environment
Service | Code ({{site.ab}}), Third-party product |
Mobile development type | Hybrid (Cordova app) |
Description
Opening a PDF in a hybrid app is possible out of the box only on iOS devices. For Android and Windows Phone, the device needs to have an external PDF viewer. An alternative approach is to use a JavaScript library, like PDF.js, to parse and render the PDF file inside the WebView. This article provides basic steps and a sample for opening a PDF file inside your app using PDF.js.
Solution
-
Go to the PDF.js page and click Download.
-
On the download page, click Stable.
-
Extract the downloaded archive and copy the
pdf.js
andpdf.worker.js
files from thebuild
folder into ascripts/pdf.js/
folder in your project. -
Reference the
pdf.js
andpdf.worker.js
files in yourindex.html
.<script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8" src="scripts/pdf.js/pdf.js"></script> <script type="text/javascript" charset="utf-8" src="scripts/pdf.js/pdf.worker.js"></script>
-
Enable the File core plugin in your app.
-
(Windows Phone only) Explicitly set the path to the
pdf.worker.js
file in your code:PDFJS.workerSrc = "scripts/pdf.js/pdf.worker.js";
-
Use the File plugin to read the PDF file as a
Uint8Array
and pass it to thePDFJS.getDocument()
function. -
Render the parsed PDF content into a
canvas
element on the page.
A working example is available here: PDF Create/Open sample app.
Notes
Steps 7 and 8 describe logic that includes code snippets, which are too long to present in a concise way in this article. You can refer to the scripts\open.js
file in the PDF Create/Open sample app.
This example relies heavily on a third-party library. At the time of testing, it worked on all three operating systems supported by Telerik Platform. However, there is no guarantee that this code will continue to work seamlessly with future OS versions. It is recommended to test this functionality in your app with each release of a new OS version and each update of the PDF.js library that you decide to use.