How to view PDF in Ionic, Capacitor, Angular ~ 6 selections ~

Hello. I’m “Nitta Iori”.

I’m Japanese and I’m still learning English, so I’m sorry if my English is wrong.

This time, I will introduce 6 ways to view PDF using Ionic, Capacitor and Angular.

This PDF app Github: https://github.com/NittaIori/IonicPdf

※Judging the appearance and usability of the content of this article is my own judgment. Since the video is posted, please refer to it or try it in your own environment.

Verification/Operating environment

  • MacBookPro MacOS13
  • Ionic 7.0.0
  • Capacitor 5.0.3
  • Angular 16.0.0
  • iPhone(Simulator) 14 Pro Max iOS 16.4

Appearance, Impressions, and Conditions of Each

It’s quick, but I’ll show you what each looks and feels like. After looking at this, I think you should use what you want to use.

ng2-pdf-viewer and ngx-extended-pdf-viewer are Angular modules, so you can use them even when creating web apps. It is recommended to use it when unifying the source code of the web application and the native application.

Appearance

The order from the left of the video is “CapacitorBrowser, InAppBrowser, FileOpener, DocumentViewer, ng2-pdf-viewer, ngx-extended-pdf-viewer”. Sorry for the inconvenience.

Also, the video uses only standard options. Please refer to each official page for individual options.

Impressions, and Conditions ※Appearance and usability are personal opinions.

※If there is Yes locally, it can be downloaded and displayed even if the Internet is No. Below are instructions on how to download.

Plugin, Module/ Condition, ImpressionsCapacitor BrowserInApp BrowserFile OpenerDocument Viewerng2-pdf-viewerngx-extended-pdf-viewer
InternetYesYesNoNo△(need CORS)△(need CORS)
LocalNoNoYesYesYesYes
AppearanceYesYesYes(There are various options)△(I don’t like)
UsabilityYesYesNo△(Can’t zoom with two fingers?)Yes

How to download a PDF in Capacitor

Some of the above do not have internet usage, but have local usage. If you download them locally and display the file, you can also display the Internet PDF. So I will write down how to download PDF locally with Capacitor.

CapacitorCommunityHttp and CapacitorFilesystem Install

npm install @capacitor-community/http
npm install @capacitor/filesystem
ionic capacitor sync

※When running Filesystem, there are files to configure on iOS and Android.

iOS info.plist

  • UIFileSharingEnabledApplication supports iTunes file sharing)
  • LSSupportsOpeningDocumentsInPlaceSupports opening documents in place)

Android AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

added. For details, Please refer to the environment settings on the official site.

Code

import { Http, HttpDownloadFileOptions, HttpDownloadFileResult } from '@capacitor-community/http';
import { Filesystem, Directory } from '@capacitor/filesystem';

async function download() {
  const pdf_url = 'https://nittaiori.github.io/IonicPdf/pdf_test.pdf';
  const options: HttpDownloadFileOptions = {
    url: pdf_url,
    filePath: 'document.pdf',
    fileDirectory: Directory.Documents,
    method: 'GET',
  };

  const response: HttpDownloadFileResult = await Http.downloadFile(options);
  console.log(response.path);
}

Each implementation method

CapacitorBrowser

CapacitorBrowser install

※ CapacitorBrowser may have been installed when the Ionic project was created, so it is not necessary for those who have it installed.

npm install @capacitor/browser
ionic capacitor sync

Code

import { Browser } from '@capacitor/browser';

// *** omit
export class Page {
  constructor() {}

  async onClickCapacitorBrowser() {
    const pdf_url = 'https://nittaiori.github.io/IonicPdf/pdf_test.pdf';
    const options = {
      url: pdf_url,
    };
    await Browser.open(options)
      .then(data => {
        console.log(data);
      })
      .catch(error => {
        console.error(error);
      });
  }
}

InAppBrowser

InAppBrowser install

npm install cordova-plugin-inappbrowser 
npm install @awesome-cordova-plugins/in-app-browser 
ionic capacitor sync

Add InAppBrowser in app.module.ts

// *** omit
import { InAppBrowser } from '@awesome-cordova-plugins/in-app-browser/ngx';

// *** omit
@NgModule({
  // *** omit
  providers: [
    // *** omit
    InAppBrowser, // add
  ],
  // *** omit
})
// *** omit

Code

import { InAppBrowser } from '@awesome-cordova-plugins/in-app-browser/ngx';

// *** omit
export class Page {
  constructor(
    private iab: InAppBrowser,
  ) {}

  onClickInAppBrowser() {
    const pdf_url = 'https://nittaiori.github.io/IonicPdf/pdf_test.pdf';
    this.iab.create(pdf_url, "_blank", "toolbarposition=top");
  }
}

FileOpener

FileOpener install

npm install cordova-plugin-file-opener2 
npm install @awesome-cordova-plugins/file-opener 
ionic capacitor sync

Add FileOpener in app.module.ts

// *** omit
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';

// *** omit
@NgModule({
  // *** omit
  providers: [
    // *** omit
    FileOpener, // add
  ],
  // *** omit
})
// *** omit

Code

import { Filesystem, Directory } from '@capacitor/filesystem';
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';

// *** omit
export class Page {
  constructor(
    private fileOpener: FileOpener,
  ) {}

  async onClickFileOpener() {
    const local_url = await Filesystem.getUri({
      path: 'document.pdf',
      directory: Directory.Documents
    });

    if (local_url.uri) {
      this.fileOpener.open(local_url.uri, 'application/pdf');
    }
  }
}

DocumentViewer

DocumentViewer install

npm install cordova-plugin-document-viewer 
npm install @awesome-cordova-plugins/document-viewer 
ionic capacitor sync

Add DocumentViewer in app.module.ts

// *** omit
import { DocumentViewer } from '@awesome-cordova-plugins/document-viewer/ngx';

// *** omit
@NgModule({
  // *** omit
  providers: [
    // *** omit
    DocumentViewer, // add
  ],
  // *** omit
})
// *** omit

Code

import { Filesystem, Directory } from '@capacitor/filesystem';
import { DocumentViewer, DocumentViewerOptions } from '@awesome-cordova-plugins/document-viewer/ngx';

// *** Omit
export class Page {
  constructor(
    private documentViewer: DocumentViewer,
  ) {}

  async onClickDocumentViewer() {
    const local_url = await Filesystem.getUri({
      path: 'document.pdf',
      directory: Directory.Documents
    });

    if (local_url.uri) {
      const document_options: DocumentViewerOptions = {
        title: "TestPdf",
      };
      this.documentViewer.viewDocument(local_url.uri, 'application/pdf', document_options);
    }
  }
}

ng2-pdf-viewer

ng2-pdf-viewer install

npm install ng2-pdf-viewer
ionic capacitor sync

Add ng2-pdf-viewer module in module.ts

// *** omit
import { PdfViewerModule } from 'ng2-pdf-viewer';

// *** omit
@NgModule({
  // *** omit
  imports: [
    // *** omit
    Tab2PageRoutingModule, // add
  ],
  // *** omit
})
// *** omit

Code

<pdf-viewer
  [src]="url"
  [render-text]="true"
  [original-size]="false"
  style="width: 400px; height: 500px"
></pdf-viewer>

<!-- If use LocalFile -->
<pdf-viewer
  [src]="dataUrl"
  [render-text]="true"
  [original-size]="false"
  style="width: 400px; height: 500px"
></pdf-viewer>
import { Filesystem, Directory } from '@capacitor/filesystem';

// *** omit
export class Page {
  url = 'https://nittaiori.github.io/IonicPdf/pdf_test.pdf';
  dataUrl = '';

  constructor() {
    this.loadLocal();
  }

  async loadLocal() {
    const data = await Filesystem.readFile({
      path: 'document.pdf',
      directory: Directory.Documents,
    });
    this.dataUrl = 'data:application/pdf;base64,' + data.data;
  }
}

ngx-extended-pdf-viewer

ngx-extended-pdf-viewer install

npm install ngx-extended-pdf-viewer

PublicFile settings(edit angular.json) Add the following “assets”.

{
  "projects": {
    "app": {
      "architect": {
        "build": {
          "options": {
            "assets": [
              {
                "glob": "**/*",
                "input": "node_modules/ngx-extended-pdf-viewer/assets/",
                "output": "/assets/"
              }
            ],
          },
        },
      },
    },
  },
}

Add ngx-extended-pdf-viewer module in module.ts

// *** omit
import { NgxExtendedPdfViewerModule } from 'ngx-extended-pdf-viewer';

// *** omit
@NgModule({
  // *** omit
  imports: [
    // *** omit
    NgxExtendedPdfViewerModule, // add
  ],
  // *** omit
})
// *** omit

Code

<ngx-extended-pdf-viewer
  [src]="url"
></ngx-extended-pdf-viewer>

<!-- If use LocalFile -->
<ngx-extended-pdf-viewer
  [base64Src]="base64"
></ngx-extended-pdf-viewer>
import { Filesystem, Directory } from '@capacitor/filesystem';

// *** omit
export class Page {
  url = 'https://nittaiori.github.io/IonicPdf/pdf_test.pdf';
  base64 = '';

  constructor() {
    this.loadLocal();
  }

  async loadLocal() {
    const data = await Filesystem.readFile({
      path: 'document.pdf',
      directory: Directory.Documents,
    });
    this.base64 = data.data;
  }
}

Impression

Thank you for reading this far.

This time it was an explanation of how to display PDF using Ionic, Capacitor and Angular.

If there are any mistakes, it would be very helpful if you could tell me in the comments or on Twitter.

I’m Japanese and I’m still learning English, so I’m sorry if my English is wrong. From now on, I will do my best to study English and programming.

I look forward to working with you.

Leave a Comment