Sie sind auf Seite 1von 11

BECOME A MEMBER QUICK WINS COURSE LIBRARY PREVIEW

JOIN THE
IONIC
How to Open PDF Files with Ionic 4 on Android and iOS
Posted on January 4th, 2019 ACADEMY
IN-DEPTH COU
TUTORIALS

SEARCH EXCLUSIVE HA
PROJECTS & RE

ACTIVE, SUPPO
COMMUNITY

SEARCH
CLICK HERE TO
STARTED

When you want to open les inside your Ionic app


you’ll most likely have to interact with the local RECENT QUICK
WINS
lesystem in some way – something that’s not
always easy and obvious from the outside.
Creating a

In this Quick Win we will build an app to open both a Pinterest

PDF that we supply with our app and one that we Layout with

rst download and then display. In contrast to the Ionic [v4]

previous
We use cookiesversion
to ensure for
that Ionic
we give3you
wethewill
bestnow How
haveonaour website. If you continue
experience tothis site we will
to use
assume that you are happy with it. Read and
OK READ MORE
Create QR
switch between iOS and Android to handle things Codes with
di erently. Ionic [v4]
Ionic Native
Contact
Management
(Call, SMS)
[v4]

JOIN THE
Building an
Ionic
IONIC
Theme
ACADEMY
Switcher &
Dynamic
CSS IN-DEPTH COU
TUTORIALS
Variables
[v4]
EXCLUSIVE HA
How To
PROJECTS & RE
Scroll Ionic
4 List ACTIVE, SUPPO
COMMUNITY
Manually
From Code
CLICK HERE TO
[v4] STARTED

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.

OK READ MORE
With the previous Document Viewer plugin we had
to use a speci c app on Android, so this time we are
rolling with a more general plugin that will
automatically use your preferred reader.

Setting up our App with all


Packages
Although the functionality of this example is quite JOIN THE
limited we need a bunch of plugins. Here’s why: IONIC
File: Copy les around to make them available
ACADEMY
for opening
File Opener: Open les, our fallback for Android IN-DEPTH COU
TUTORIALS
File Transfer: Download les without CORS
issues EXCLUSIVE HA
Document Viewer: Preferred way to display les PROJECTS & RE

on iOS, looks better than the File opener


ACTIVE, SUPPO
COMMUNITY
So on iOS we continue to use the plugin from the
last Quick Win, and for Android we implement the
CLICK HERE TO
File Opener. Let’s start by running all of the STARTED
commands below:

Start our PDF App and install all needed packages


1 ionic start pdfOpen blank --type=angular
2 cd pdfOpen
3  
4 # Ionic Native Packages
5 npm i @ionic-native/file@beta
6 npm i @ionic-native/file-opener@beta
7 npm i @ionic-native/file-transfer@beta
8 npm i @ionic-native/document-viewer@beta
9  
10 # Cordova Plugins
11 ionic cordova plugin add cordova-plugin-file
12 ionic cordova plugin add cordova-plugin-file-opener2
13 ionic cordova plugin add cordova-plugin-file-transfer
We14
useionic
cookiescordova
to ensure that we
plugin givecordova-plugin-document-viewer
add you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.

OK READ MORE
Next we need to add all of them to our
app/app.module.ts just like we are used to, so go
ahead and insert:

Import all package to our module


1 import { NgModule } from '@angular/core';
2 import { BrowserModule } from '@angular/platform-browser'
3 import { RouteReuseStrategy } from '@angular/router';
4  
5 import { IonicModule, IonicRouteStrategy } from '@ionic/a

JOIN THE
6 import { SplashScreen } from '@ionic-native/splash-screen
7 import { StatusBar } from '@ionic-native/status-bar/ngx';
8  
9
10
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module'; IONIC
11
12
13
 
import { File } from '@ionic-native/File/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx
ACADEMY
14 import { FileTransfer } from '@ionic-native/file-transfer
15 import { DocumentViewer } from '@ionic-native/document-vi
16  
17 @NgModule({ IN-DEPTH COU
18   declarations: [AppComponent], TUTORIALS
19   entryComponents: [],
20   imports: [BrowserModule, IonicModule.forRoot(), AppRout
21   providers: [ EXCLUSIVE HA
22     StatusBar,
23     SplashScreen, PROJECTS & RE
24     { provide: RouteReuseStrategy, useClass: IonicRouteSt
25     File,
26     FileOpener, ACTIVE, SUPPO
27     FileTransfer, COMMUNITY
28     DocumentViewer
29   ],
30   bootstrap: [AppComponent]
31 })
32 export class AppModule {} CLICK HERE TO
STARTED

Because we don’t really need any view we’ll also


cover that part by now so we can focus on the
important functions afterwards. Just add two
buttons and we are good to go, so change your
app/home/home.page.html to:

Most advanced view example


1 <ion-header>
2   <ion-toolbar>
3     <ion-title>
4       Ionic PDFs
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
5     </ion-title>
6   </ion-toolbar> assume that you are happy with it.
7 </ion-header>
8   OK READ MORE
9 <ion-content padding>
10   <ion-button expand="full" (click)="openLocalPdf()">Open
11   <ion-button expand="full" (click)="downloadAndOpenPdf()
12 </ion-content>

Now we are ready to perform some magic!

Open Local PDF


First of all you need a PDF le to test things out.
Actually you could also open di erent les but then JOIN THE
you’ll have to change the mimetype as well.
IONIC
I’ve added a le called 5-tools.pdf into the assets ACADEMY
folder of my app so copy some to that place as well
now. IN-DEPTH COU
TUTORIALS

For Android, the File Opener was not able to open


EXCLUSIVE HA
that le directly (at least in my tests) and we have to PROJECTS & RE
copy that le to a directory where we can open it. If
you don’t want to pile up your stack of old les you ACTIVE, SUPPO
COMMUNITY
should also add a removeFile function once you are
done with the le!
CLICK HERE TO
STARTED
Once to copy operation is nished we can easily
access the correct URL and pass it to the le opener.

For iOS, we don’t need the extra step (although it


would work as well, just like the le opener would)
so we can directly pass in the path to our local le.

The path to the le we added to our assets folder is


actually constructed using the le plugin again and
then adding www/assets so it’s exactly like the
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
folder you see in your IDE when using
assume live
that you arereload!
happy with it.

OK READ MORE
Now go ahead and change your
app/home/home.page.ts to:

Open a local PDF file for iOS and Android


1 import { Platform } from '@ionic/angular';
2 import { File } from '@ionic-native/File/ngx';
3 import { Component } from '@angular/core';
4 import { FileOpener } from '@ionic-native/file-opener/ngx
5 import { DocumentViewer, DocumentViewerOptions } from '@i
6 import { FileTransfer } from '@ionic-native/file-transfer
7  

JOIN THE
8 @Component({
9   selector: 'app-home',
10   templateUrl: 'home.page.html',
11
12
  styleUrls: ['home.page.scss'],
}) IONIC
13
14
15
export class HomePage {
 
  constructor(private platform: Platform, private file: F
ACADEMY
16     private fileOpener: FileOpener, private document: Doc
17  
18   }
19   IN-DEPTH COU
20   openLocalPdf() { TUTORIALS
21     let filePath = this.file.applicationDirectory + 'www/
22  
23     if (this.platform.is('android')) { EXCLUSIVE HA
24       let fakeName = Date.now();
25       this.file.copyFile(filePath, '5-tools.pdf', this.fi PROJECTS & RE
26         this.fileOpener.open(result.nativeURL, 'applicati
27           .then(() => console.log('File is opened'))
28           .catch(e => console.log('Error opening file', e ACTIVE, SUPPO
29       }) COMMUNITY
30     } else {
31       // Use Document viewer for iOS for a better UI
32       const options: DocumentViewerOptions = {
33         title: 'My PDF'
34       } CLICK HERE TO
35       this.document.viewDocument(`${filePath}/5-tools.pdf STARTED
36     }
37   }
38 }

We could also leave out the switch and perform the


same steps for iOS, however the view is really a lot
better with the document viewer so try to stick with
that.

Download and Open PDF


We use cookies
Now that weto ensure that we give
can open lesyou the best
from ourexperience on our website.
app bundle, we If you continue to use this site we will
assume that you are happy with it.
might also need to download and display les from
OK READ MORE
time to time. While the File Transfer plugin in
general is deprecated, we can still use it like always
as it works great and overcomes any CORS issues
that we would get otherwise if we were to use the
standard HTTP client.

If you don’t want to go with the File Transfer plugin


you can also use the native HTTP package and make
the calls through that plugin but you’ll then also
JOIN THE
have to implement saving the le data inside the IONIC
system yourself. ACADEMY
In this example we can now pass our download URL
IN-DEPTH COU
to the le transfer package and download the le to TUTORIALS
our apps data directory. Afterwards we can use the
toURL() function on the le entry to receive the EXCLUSIVE HA
PROJECTS & RE
right URL to the le.
ACTIVE, SUPPO
This URL can be used for both iOS and Android, but COMMUNITY

just like before we will use the document viewer for


iOS and the standard le opener for Android. CLICK HERE TO
STARTED
Go ahead and add the function inside your
HomePage class below the previous function:

Download a file first and open it then


1 downloadAndOpenPdf() {
2   let downloadUrl = 'https://devdactic.com/html/5-simple-
3   let path = this.file.dataDirectory;
4   const transfer = this.ft.create();
5  
6   transfer.download(downloadUrl, path + 'myfile.pdf').the
7     let url = entry.toURL();
8  
9     if (this.platform.is('ios')) {
10       this.document.viewDocument(url, 'application/pdf',
We11 cookieselse
use    } {
to ensure that we give you the best experience on our website. If you continue to use this site we will
12       this.fileOpener.open(url, 'application/pdf')
assume that you are happy with it.
13         .then(() => console.log('File is opened'))
14         .catch(e => console.log('Error OK opening file', e))
READ MORE
15     }
16   });
17 }

Now you can test out your app on a device,


remember Cordova plugins don’t work inside your
browser.

Android Quirks
Not completely related to the content but the JOIN THE
Android build failed for me when using these plugins IONIC
so I wanted to add a little note.
ACADEMY
First, I had to downgrade my platform because
Cordova 7 didn’t work out well so I ran: IN-DEPTH COU
TUTORIALS

1 ionic cordova platform rm android EXCLUSIVE HA


2 ionic cordova platform add android@6.4 PROJECTS & RE

But that’s not enough, due to some libraries being ACTIVE, SUPPO
COMMUNITY
included by our File plugin we need to make a little
hack as well. I found this hack inside this Github
issue and the change you need to apply is adding CLICK HERE TO
STARTED
the below snippet at the end of your
platforms/android/build.gradle:

Add to the end of your gradle script if Android build is failing


1 configurations.all {
2     resolutionStrategy {
3         force 'com.android.support:support-v4:27.1.0'
4     }
5 }

This is not a great way because that folder is most


likely not under version control for your team and
also
We not synced
use cookies with
to ensure your
that we give other
you the machines – but
best experience atwebsite. If you continue to use this site we will
on our
assume that you are happy with it.
least you can build an APK afterwards again!
OK READ MORE
This might be xed at some point in the future when
Cordova Android 7 works and the plugins have been
updated.

Conclusion
If you understand the general behaviour behind the
le system and how the URL works you can easily
open or copy all kind of local information and pass JOIN THE
the information to other plugins. IONIC
In our case we used a PDF le but other les would
ACADEMY
work as well, just make sure you get the path,
ending and letype right and you shouldn’t run into IN-DEPTH COU
TUTORIALS
any trouble.

EXCLUSIVE HA
You can also nd a video version of this Quick Win PROJECTS & RE
below.
ACTIVE, SUPPO
COMMUNITY
How to Open PDF Files with Ionic 4 on Andr…
Andr…

CLICK HERE TO
STARTED

Comments Community 
1 Login
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will

Recommend t Tweet f Share Sort
by
Best
assume that you are happy with it.

OK READ MORE
Join the discussion…
Join the discussion…

LOG
IN
WITH OR
SIGN
UP
WITH
DISQUS ?

Name

Ida • 6 months ago


I followed the guide and got this error: ERROR TypeError:
Object(...) is not a function
Do you know what could be the problem? Thanks :)

JOIN THE
3△ ▽ • Reply • Share ›

Himesh • 5 months ago


I am facing code: 1, file not found error. Can anyone
IONIC
please help me
1△
ACADEMY
▽ • Reply • Share ›

sandrymend • 23 days ago


IN-DEPTH COU
I followed this tutorial but I got this error on TUTORIALS
openLocalPdf() for ios simulator: When I tried to open the
file:
EXCLUSIVE HA
ERROR: Error in
PROJECTS & RE
SitewaertsDocumentViewer.viewDocument(): [object
Object]
ACTIVE, SUPPO
Any help with this error? Thanks COMMUNITY

The downloadAndOpenPdf() works pretty well.


△ ▽ • Reply • Share ›
CLICK HERE TO
STARTED
Mostafa
Mansour • a month ago
use this plugin to open the pdf file
https://github.com/mostafa-...
△ ▽ • Reply • Share ›

Sampath
Lokuge • a month ago
Hi, This is working perfectly fine on iOS. But I have a
problem with Android 9. It doesn't open the pdf. But it
works nicely with Android 7 and 8 devices. Any clue?
△ ▽ • Reply • Share ›

Thomas
Pinna • 4 months ago
This didn't work for me, since some apis used seem
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
deprecated. assume that you are happy with it.

OK for the
However, what did work for me was READ MORE
"Download
and Open PDF" usecase was simply window open(url);
and Open PDF usecase was simply window.open(url);

this solution also works in the browser, I didn't test iOS


however
△ ▽ • Reply • Share ›

Luís
Cunha • 8 months ago
Is there any good solution on Android that doesn't
require the user to have an external PDF opener
application installed?
△ ▽ • Reply • Share ›

Mudasir
Bhutto > Luís Cunha • 7 months ago
JOIN THE
Yes, use docs.google.com and it's best solution IONIC
for not only pdf, but also .doc, .docx, .ppt, .pptx,
.xls, .xlsx etc ACADEMY
△ ▽ • Reply • Share ›

IN-DEPTH COU
ALSO
ON
IONIC
ACADEMY TUTORIALS
Building
an
Ionic
Theme How
to
Use
Font
Awesome
Switcher
&
Dynamic
CSS With
Ionic
4 EXCLUSIVE HA
1 comment • 2 months ago 2 comments • a year ago PROJECTS & RE

ACTIVE, SUPPO
COMMUNITY

CLICK HERE TO
© Ionic Academy - 2019 DISCLAIMER STARTED
PRIVACY

SUPPORT

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.

OK READ MORE

Das könnte Ihnen auch gefallen