- Home>
- ASP.NET core>
- Rendering a PDF in angular that works with mobile browsers using ng2-pdf-viewer
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; } }
Displaying PDFs in Blazor.
Cache angular components using RouteReuseStrategy
Using MSAL angular to authenticate a user against azure ADB2C via authorization code flow with Proof Key for Code Exchange.
Displaying text in a tool tip when text overflows its container
Azure AD authentication in angular using MSAL angular v2 library
Common frameworks, libraries and design patterns I use
Differences between a Promise and an Observable
Integrate Azure AD B2C reset password user flow in angular using oidc-client-js.