Quote of the Day

more Quotes

Categories

Buy me a coffee

  • Home>
  • ASP.NET core>

Rendering a PDF in angular that works with mobile browsers using ng2-pdf-viewer

Published August 21, 2021 in Angular , ASP.NET core - 0 Comments

In several applications I worked on, we used iframe to display PDFs. The PDF displays fine on desktop browsers. However, on a mobile browser such as Safari on iPhone and iPAD, only the first page shows up. Many people have run into the same issue, as discussed in this stackoverflow post and also on the apple communities page.

In the most recent application that I worked on, I checked out ng2-pdf-viewer for rendering a PDF. This library is straightforward to use. The installation and setup is straightforward. I was able to get PDF rendering working in my app without much effort by following this post.

Once you got it setup, for the most part, you can simply replace the <iframe> tag with the <pdf-viewer> tag.

 <pdf-viewer [src]="sourceURL" class="pdfStyles modal-body" [original-size]="false" [autoresize]="false" [show-borders]="false"></pdf-viewer>

sourceURL can simply be a web URL to a PDF file, or a blob object URL. In the above snippet, sourceURL refers to the blob object URL, as shown in the below snippet.

    private getPdfBlobUrl(documentId: number): Observable<string> {
        return this.apiService.clientGet('/api/document/GetPDFByID', { Id: documentId }, ResponseContentType.Blob).pipe(map((res: Blob) => {
            const blob = new Blob([res], { type: 'application/pdf' });
            return window.URL.createObjectURL(blob);
        }));
    }

The PDF payload comes from the web api as a stream.

  [HttpGet("GetPDFByID")]
        public async Task<FileStreamResult> GetPDFByID(long Id)
        {
            try
            {
                var stream = await _service.GetDocById(Id);
                outStream.Position = 0;
                return new FileStreamResult(outStream, "application/pdf");
            }
            catch (Exception ex)
            {
                _logger.LogError(message: "Failed to retrieve document", exception: ex);
                throw;
            }
        }

References

ng2-pdf-viewer

No comments yet