Ng2-pdf-viewer: pdf not displayed: no src in source visible

Created on 9 Jan 2018  Â·  13Comments  Â·  Source: VadimDez/ng2-pdf-viewer

Bug Report or Feature Request (mark with an x)
- [ ] Regression (a behavior that used to work and stopped working in a new release)
- [x] Bug report -> please search issues before submitting
- [ ] Feature request
- [ ] Documentation issue or request

I'm trying to display a pdf from an arraybuffer, working myself through issue 88, and there are no errors concerning this.
But I have no content displayed. It's odd that I have barely any info within the <pdf-viewer>:

screen shot 2018-01-09 at 17 03 54

Although it's called correctly: <pdf-viewer [src]="pdf" [render-text]="true" style="display: block;"></pdf-viewer>

I had trouble during installation with dependencies, so I downgraded webpack from 3.1.0 to 2.7.0 according to the unmet dependency warning I received when installing ng2-pdf-viewer. Could that cause problems?

Here are my versions:

$ ng --version

    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / â–³ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/

Angular CLI: 1.6.1
Node: 6.9.2
OS: darwin x64
Angular: 5.1.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cdk: 5.0.1
@angular/cli: 1.6.1
@angular/material: 5.0.1
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.1
@schematics/angular: 0.1.11
@schematics/schematics: 0.0.11
typescript: 2.4.2
webpack: 2.7.0

You're help is much appreciated!

stale

Most helpful comment

This is how I display my PDF. I have the PDF as a base64 string read from a file as my starting point. I convert the base64 string to an ArrayBuffer to use as the source for the pdf-viewer.

    pdf: ArrayBuffer;

    // PDF is received as a NavParam from the calling page.
    constructor(public navParams: NavParams) {
        this.pdfParam= navParams.get('pdf');
        // Convert the base64 PDF to an ArrayBuffer
        this.pdf = this.base64ToArrayBuffer(this.pdfParam.base64);
    }

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

HTML

<pdf-viewer [src]="pdf" [original-size]="false" style="display: block;"></pdf-viewer>

I hope this helps.

All 13 comments

How does pdf variable looks like?
What kind of problem did you have with webpack?

  • pdf: I create it in the backend and receive it like this:
this.http.get(this.BASE_URL + '/streamPdf/' + id, { responseType: 'arraybuffer' }).subscribe(
            (result: any) => {
                if (result.success === false) {
                    this.alertService.translateError('MSG_DN_STREAM_ERROR');
                } else {
                    const pdf = new Uint8Array(result)
                    const deliveryNoteDialogRef = this.openDeliveryNoteDialog(DeliveryNotePreviewDialogComponent, pdf);
                    this.afterDeliveryNoteDialogClosed(deliveryNoteDialogRef);
                }
            }
        )

It seems to be ok:
screen shot 2018-01-09 at 17 12 06

  • webpack: I had 3.1.0 installed, and it stated:
    screen shot 2018-01-09 at 15 44 07

Or is that maybe not related to ng2-pdf-viewer?

First following 2 unmet dependencies:

npm WARN [email protected] requires a peer of [email protected] but none was installed.
npm WARN [email protected] requires a peer of @types/pdfjs-dist@^0.1.1 but none was installed.

The installation of [email protected] goes w/o problems. If I install the @types/pdfjs-dist@^0.1.1 one, I receive again: npm WARN [email protected] requires a peer of webpack@>=0.9 <2 || ^2.1.0-beta || ^2.2.0 but none was installed.

Without any webpack given manually, I have 3.10.0 installed.

@surachaitanya Have you declared your pdf in a way that is accessible to your template, and not just const pdf?

Here is my pdf: I pass it to this mat-dialog component:

import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { DomSanitizer } from '@angular/platform-browser';
import { URL } from 'url';

@Component({
    selector: 'delivery-note-preview-dialog',
    templateUrl: './delivery-note.preview.dialog.component.html',
    styleUrls: ['../../../device/device-details.component.css', '../../../accounting/accounting.component.css']
})
export class DeliveryNotePreviewDialogComponent {

    pdf;

    constructor(private dialogRef: MatDialogRef<DeliveryNotePreviewDialogComponent>,
                @Inject(MAT_DIALOG_DATA) public url,
                private sanitizer: DomSanitizer) {
        this.pdf = this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
    }

    onNoClick(): void {
        this.dialogRef.close();
    }

Note: for the time being I use iframe until I get it to display within this viewer, that's why it's suddenly a url, not as before a Uint8Array.

Hi all,

I do have the same problem. I receive a byte array from my REST endpoint (not a PDF file URL), so I need to display this byte stream... but nothing shows.

I have tried several things, one of them is using the data attribute instead of src (see data attribute here). So I now have something like this:

<pdf-viewer data="{{pdf}}"></pdf-viewer>

With pdf being an ArrayBuffer:

@Component({
    selector: 'spn-agreement-pdf',
    templateUrl: './agreement-pdf.component.html',
})
export class AgreementPDFComponent {

    pdf: ArrayBuffer;

But nothing shows up.

Any idea?

This is how I display my PDF. I have the PDF as a base64 string read from a file as my starting point. I convert the base64 string to an ArrayBuffer to use as the source for the pdf-viewer.

    pdf: ArrayBuffer;

    // PDF is received as a NavParam from the calling page.
    constructor(public navParams: NavParams) {
        this.pdfParam= navParams.get('pdf');
        // Convert the base64 PDF to an ArrayBuffer
        this.pdf = this.base64ToArrayBuffer(this.pdfParam.base64);
    }

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

HTML

<pdf-viewer [src]="pdf" [original-size]="false" style="display: block;"></pdf-viewer>

I hope this helps.

@AndrWeisR I converted my PDF to Base64 on my back-end (Java REST endpoint). So I now I receive a Base64 encoded PDF on my Angular app, but I have this error:

DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
    at PDFComponent.base64ToArrayBuffer 

So it looks like I have encoding/decoding problems now. I now my Base64 encoding on the back-end works, because I'm sending this PDF Base64 encoded to DocuSign. And it displays nicely on DocuSign.

But why do I have to Base64 encode it ? Shouldn't sending the byte array work ?

@AndrWeisR My bad, it's working !!!!

The problem was on my side: I am going through a service and this service was still returning a byte array instead of a String. By changing the service (res.text()), it works:

    viewPDF(id: number): Observable<String> {
        return this.http.get(`${this.resourceUrl}/${id}/pdf`).map((res: Response) => {
            return res.text();
        });
    }

Thanks !

@AndrWeisR

Thanks man... that base64ToArrayBuffer was the little hint I needed to get past this hurdle and get PDF Blobs from a REST API to work correctly.

@AndrWeisR I tried your code but getting error

DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. at PDFComponent.base64ToArrayBuffer

Converted the bytes.buffer to (bytes.buffer).toString but still getting that error.

  • pdf: I create it in the backend and receive it like this:
this.http.get(this.BASE_URL + '/streamPdf/' + id, { responseType: 'arraybuffer' }).subscribe(
            (result: any) => {
                if (result.success === false) {
                    this.alertService.translateError('MSG_DN_STREAM_ERROR');
                } else {
                    const pdf = new Uint8Array(result)
                    const deliveryNoteDialogRef = this.openDeliveryNoteDialog(DeliveryNotePreviewDialogComponent, pdf);
                    this.afterDeliveryNoteDialogClosed(deliveryNoteDialogRef);
                }
            }
        )

It seems to be ok:
screen shot 2018-01-09 at 17 12 06

  • webpack: I had 3.1.0 installed, and it stated:

screen shot 2018-01-09 at 15 44 07

Or is that maybe not related to ng2-pdf-viewer?

Were you able to resolve this? I am having same issue :)

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ShayShaked picture ShayShaked  Â·  5Comments

roginneil picture roginneil  Â·  3Comments

manojbhardwaj picture manojbhardwaj  Â·  7Comments

GarciaFreelancer picture GarciaFreelancer  Â·  6Comments

viktorhajer picture viktorhajer  Â·  7Comments