1

I build an Ionic 3 app and I want to display a preview of an base64 encoded file.

I first try to use this plugin : https://www.npmjs.com/package/ng2-pdf-viewer

It worked at the beginning but today my PDF doesn't appear anymore. Maybe because dependecies are out of date. Whatever, this plugin doesn't give me a satisfactory preview.

Now I find this : https://ionicframework.com/docs/native/base64/

But the problem is that I can't use Base64 with this plugin.

I really don't know what I can do to solve this problem. Someone have a solution ?

V. Pivet
  • 1,320
  • 3
  • 25
  • 57

2 Answers2

0

You have to convert the Base64 string to a Uint8Array. From Download File from Bytes in JavaScript.

Add a base 64 convert function to your calling component

base64ToArrayBuffer(base64) {
    const binary_string = window.atob(base64);
    const len = binary_string.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

After the content was initialized:

public ngAfterContentInit(): void {
  this.viewer.pdfSrc =  this.base64ToArrayBuffer(this.model.pdfBytes);
}

where this.model.pdfBytes contains the base64 encoded string.

gwallis
  • 1
  • 2
-1

I dont know if my solution is what you are looking for but I used this and It works.

 Pdf(){
this.rest.getPdfVacation(this.mail).then(data=>{
  if(data.json()){
    let pdf = window.open(); 
    pdf.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64, " + data.json().RESPUESTA + "'></iframe>"); 
  }
}) }

as you can see I opening the pdf in a new tab but you can avoid that, my base64 string is in data.json().RESPUESTA, so in that place you shouwld put your base64 data.

cheers!

  • This code does not work in ionic 3 and this is not the right way to open a PDF in a ionic app. – SBO Sep 05 '18 at 09:44