Open pdf file saved assets folder

Hello,
I am using Ionic Angular v5 Capacitor in my App.
I am trying to create a button that open a pdf file saved at assets folder.
I tried File Opener (File Opener | Ionic Documentation) and Document Viewer (Document Viewer | Cordova Plugin Document Viewer for PDF Files), but both failed.

It looks like a simple function, but I’m not getting it.

Someone suggests a tutorial or example to open pdf file in this case?

Many thanks.

you should use http client. With url like http.get(’/assets/folder/file.pdf’)

Mime type to use:

Example:

Official doc:
https://angular.io/guide/http

Many thanks. I will try this and post the result.

Mp4 file saved at assets folder and using Video Player (VideoPlayer | Ionic Native Cordova-Plugin-VideoPlayer), Can I use http client also?

I also had the same error.

well, give it a try - I’d say. I have no experience and trying shouldn’t be that hard…

I am trying as below:
openList() {
const var = this.httpClient.get(’/assets/IOA_esp.pdf’).subscribe((x)=>{

  this.document.viewDocument(xxxx, 'application/pdf', this.options);
});

Console gives this result:
HttpErrorResponse {
headers: HttpHeaders,
status: 200,
statusText: ‘OK’,
url: ‘http://localhost:8100/assets/IOA_esp.pdf’,
ok: false, …}

xxxx must be a string (url: string, …).

How can I obtain and use url from var?

Suggestions?

I also tried this, but does not work:

import {
DocumentViewer
} from ‘@ionic-native/document-viewer/ngx’;

constructor(private document: DocumentViewer) {}


const options: DocumentViewerOptions = {
title: ‘My PDF’
}

this.document.viewDocument(‘assets/myFile.pdf’, ‘application/pdf’, options)

I tried this tutorial, but also did not work:

I used this function:

import { File } from ‘@awesome-cordova-plugins/file/ngx’;
import { DocumentViewer, DocumentViewerOptions } from ‘@awesome-cordova-plugins/document-viewer/ngx’;

openPdf(){
const filePath = this.file.applicationDirectory + ‘/assets’;
console.log(filePath);

   const options: DocumentViewerOptions = {
     title: 'My PDF'
   }
   this.document.viewDocument('${filePath}/1.pdf', 'application/pdf', options);
 }

filePath is null in console (null/assets)

Emulator console shows
“[error] - Error in SitewaertsDocumentViewer.viewDocument(): {“message”:“invalid file url ‘${filePath}/1.pdf’ or no viewer for mime type ‘application/pdf’”,“details”:{“status”:0}}“

openList() {
const var = this.httpClient.get(’/assets/IOA_esp.pdf’).subscribe((x)=>{
  this.document.viewDocument(xxxx, 'application/pdf', this.options);
});

You cannot use var as variable name - nor should you be using it to declare a variable. Next, assigning the http.get to a variable will not yield the content but in this case a completed subscription.

At least you should do a console.log on x to see the content before passing on.

Next, the error might indicate something weird - sometimes like CORS, but you are referring to localhost? On what device are you running?

Using this function:


import { File } from ‘@awesome-cordova-plugins/file/ngx’;
import { DocumentViewer, DocumentViewerOptions } from ‘@awesome-cordova-plugins/document-viewer/ngx’;
…

openPdf(){
const filePath = this.file.applicationDirectory + ‘/assets’;
console.log(filePath);

   const options: DocumentViewerOptions = {
     title: 'My PDF'
   }
   this.document.viewDocument('${filePath}/1.pdf', 'application/pdf', options);
 }

Console of Chrome results: “null/assets”.
iOS emulator results: “[error] - Error in SitewaertsDocumentViewer.viewDocument(): {“message”:“invalid file url ‘${filePath}/1.pdf’ or no viewer for mime type ‘application/pdf’”,“details”:{“status”:0}}“

Using


openList() {
const t = this.httpClient.get(’/assets/1.pdf’).subscribe((x)=>{

  console.log(x);
});

Chrome console shows:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: ‘OK’, url: ‘http://localhost:8100/assets/1.pdf’, ok: false, …}

A minimal reproduction on stackblitz or github would be helpful.

I’m testing a new project. I’m beginning, so I hope you understand. I will share my steps below (I restarted the project) .

I started a project: ionic start testPdf tabs --capacitor. (Angular)

I’m using:

  • Ionic CLI : 6.16.3
  • Ionic Framework: @ionic/angular 6.0.1
  • Capacitor CLI: 3.3.3
  • NodeJS : v14.16.0
  • npm: 6.14.15
  • macOS Big Sur

1) app.module.ts

Included

import { HttpClientModule } from '@angular/common/http';
@NgModule({
...
imports: [HttpClientModule,
...

2) tab1.page.ts
Included

import { HttpClient } from '@angular/common/http';
...
  constructor(private http: HttpClient) {}

openPdf(){
    const t = this.http.get('/assets/file.pdf').subscribe((x)=>{
      console.log(x);
    });
  }
  1. tab1.page.html
<ion-button (click)="openPdf()" expand="full">
    OPEN PDF
</ion-button>

After click on button chrome console returns:

core.mjs:6484 ERROR 
HttpErrorResponse {
headers: HttpHeaders, 
status: 200,
 statusText: 'OK', 
url: 'http://localhost:8100/assets/file.pdf', 
ok: false, …
}
error: {error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: '%PDF-1.3\n%���������\n3 0 obj\n<< /Filter /FlateDecod…cc7ce855f52f38fcf5b> ] >>\nstartxref\n144438\n%%EOF\n'}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8100/assets/file.pdf"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8100/assets/file.pdf"
[[Prototype]]: HttpResponseBase

How could I proceed to open the pdf file (ios and Android)?

I solved using Document-Viewer (Document Viewer | Cordova Plugin Document Viewer for PDF Files).
The problem was in the path of the file, which should be this.document.viewDocument(’…/…/…/assets/file.pdf’, ‘application/pdf’, options); NOT this.document.viewDocument(’/assets/file.pdf’, ‘application/pdf’, options);

I am trying with Httpclient and Document Viewer as below:

 openPdf() {
    const options: DocumentViewerOptions = {
      title: 'My PDF'
    };

    this.httpClient.get("assets/file.pdf", {
      observe: 'response',
      responseType: 'blob'})
      .subscribe(response => {
        this.document.viewDocument(response.url, 'application/pdf', options);
      });
  }

Iphone emulator returns error:

[error] - Error in SitewaertsDocumentViewer.viewDocument(): 
 {"message":"invalid file url 'capacitor://localhost/assets/file.pdf' or 
no viewer for mime type 'application/pdf'","details":{"status":0}}

But file path ‘http://localhost:8100/assets/file.pdf’ works on Chrome, it is correct.

Document Viewer works when I use iPhone emulator and absolute path from file (such as /Users/usuer/app/src/assets/file.pdf), showing that Document Viewer is working.

Any suggestion?

On real device this didn’t work.