angular changing the src attribute of ng2-pdf-viewer

I'm currently utilizing ng2-pdf-viewer within a modal component to view a PDF file. The PDF is generated from a blob using the URL.createObjectURL method. After initialization, I have signed the PDF. However, when I update the src variable with a new value, the changes are not reflected until I manually click on the PDF.

@Component({
  selector: 'app-trip-detail-pdf',
  template: `
  <div class="form-group">
    <div class="row">
        <div class="col-12">
            <pdf-viewer #pdfViewer
              [src]="documentData"
              [render-text]="true"
              [original-size]="false"
              [autoresize]="false"
              [show-all]="true"
              [fit-to-page]="false"
              [zoom]="1"
              [zoom-scale]="'page-width'"
              style="width: 100%;"
              [style.height.vh]="loadingPlanDetail?.IsSigned? 90:  (bs.xs$|async)?70:(bs.sm$|async)&&(bs.handSetLandscape$|async)?40:(bs.tablet$|async)?60:72"
            ></pdf-viewer>
        </div>
        <div class="pt-1 col-12" >
          <app-signature (signed)="signedPdf($event)" *ngIf="!loadingPlanDetail?.IsSigned"></app-signature>
        </div>
    </div>
    </div>
  `,
  styles: [
  ]
})
export class DeliverDetailPdfComponent implements OnInit {
  @ViewChild('pdfViewer', { static: true }) pdfViewer: PdfViewerComponent;
  @Input() documentData: any;
  @Input() loadingPlanDetail: LoadingPlanDetailModel;
  @Input() deliverHeader: DeliverHeaderModel;
  @Output() td: EventEmitter<any> = new EventEmitter();

  pdfArray: any;
  pdfDoc: PDFDocument;


  constructor(public bs: BreakpointService, private store: Store) { }

  ngOnInit() {
    this.drawDriverSign()
  }

   
  async drawDriverSign() {
    console.log("drawDriverSign")
    this.pdfArray = await this.loadingPlanDetail.Pdf.arrayBuffer();
    this.pdfDoc = await PDFDocument.load(this.pdfArray)

    const signDriverImage = await this.pdfDoc.embedPng(this.deliverHeader.Sign);
    const signImageSize = signDriverImage.size();//.scale(0.25)

    //get first page dimension
    const pages = this.pdfDoc.getPages()
    const firstPage = pages[0]

    const { width, height } = firstPage.getSize()

    const page = this.pdfDoc.addPage([width, height]);

    //begin - driver signature
    page.drawRectangle({
      x: 20,
      y: 700,
      width: 350,
      height: 100,
      borderColor: rgb(0, 0, 1),
      rotate: degrees(0),
      xSkew: degrees(0),
      ySkew: degrees(0),
    })
    page.drawText('Driver Signature', {
      x: 25, y: 802, size: 10, color: rgb(0, 0, 0)
    })

    page.drawImage(signDriverImage, {
      x: 25, //page.getWidth() / 2 - signImageSize.width / 2,
      y: 680, //page.getHeight() / 2 - signImageSize.height / 2,
      width: signImageSize.width,
      height: signImageSize.height,
    });
    //end - driver signature

    const pdfSave = await this.pdfDoc.save()
    const pdfBlob = new Blob([pdfSave], { type: 'application/pdf' });

    this.documentData = URL.createObjectURL(pdfBlob);

  }
}

Answer №1

Initially, the documentData is set to null before being updated with the new blob URL.

This code snippet illustrates the process:

this.documentData = null; this.documentData = URL.createObjectURL(pdfBlob);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Child Component featuring an Accordion group implemented with ngx-bootstrap

Primary Component <input type="button" class="btn btn-primary" (click)="allExpanded = !allExpanded" [attr.value]="allExpanded ? 'Collapse All': 'Expand All'" > <div class=& ...

The TypeScript `unknown` type restricts the use of non-unknown types in function parameters

Why is there an error in this code? const x: unknown[] = ['x', 32, true]; // OK const y: (...args: unknown[]) => unknown = (xx: number) => {}; // ERROR // Type '(xx: number) => void' is not assignable to type '(...args: u ...

Is it possible for Swagger to produce unique custom generic types?

Let's consider a scenario where we receive an API return model in C# public class ApiResult<T> { public T Result; public bool Success; } and send back an ApiResult<string> object instance to the client This leads us to a swagger gen ...

Leverage Prisma's auto-generated types as the input type for functions

Exploring the capabilities of Prisma ORM has led me to experiment with creating models and generating the PrismaClient. Initially, I thought it would be possible to utilize the generated types for variables and response types, but that doesn't seem to ...

Guide on How to Simulate a Backend in Angular2 Development

Currently, I am developing an angular2 application and I am in need of mocking the backend since it is not yet available. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Headers, Response, RequestO ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

Angular 4: Transform a string into an array containing multiple objects

Recently, I received an API response that looks like this: { "status": "success", "code": 0, "message": "version list", "payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta&b ...

Experimenting with integrating an external JavaScript library into Angular 5

I've noticed similar questions but I'm still struggling to make it work... My goal is to implement slick.js in my Angular application. I downloaded the necessary files and placed them in the assets folder. I have added the libraries in my angu ...

Changing the Image Source in HTML with the Power of Angular2

Despite my efforts, I'm unable to display the updated image in my HTML file. In my TypeScript file, the imageUrl is updating as expected and I've verified this in the console. However, the HTML file is not reflecting these changes. In my researc ...

How to link an observable to an array in Angular 4

When attempting to initialize an array from an observable, I encountered a compilation error with the following message: https://i.sstatic.net/cocn8.png Here is the code snippet from my component: export class LeaderBoardComponent implements OnInit { ...

Directive's timeout function fails to execute

My goal was to experiment with a simple AutoScrollDirective. @Directive({ selector: '[appAutoScroll]', }) export class AutoScrollDirective implements AfterViewInit { constructor(private element: ElementRef<HTMLElement>) {} @Input() ...

Issue with the text wrapping of Angular mat-list-option items

When the text of my checkboxes is too long, it doesn't wrap properly. Please see the image below for reference: Click here to view Checkbox image and check the red box Here is my HTML code: <mat-selection-list #rolesSelection ...

"Utilizing TypeScript Definitions in a Node.js/Express Application: A Step-by-Step

I initially started using tsd and typings to install declaration files from external sources and reference them in the server file. However, now we have the option to obtain declaration files through @types/filename. I'm not sure why the move was made ...

The 'XX' Typescript type does not match the type import ("/Volumes/D/test").XX.ts(2322)

I wrote a piece of code to customize the default configuration for a Class, but I encountered an unusual error message: Type 'IConfig' is not assignable to type 'import("/Volumes/D/www/js/tsc_1/test").IConfig'.ts(2322) It seems that I ...

Error encountered with NextJS and useRouter due to TypeScript - The type 'undefined' is invalid for use as an index

I'm facing a TypeScript error that I can't seem to resolve, despite trying solutions from other questions. It's giving me the error message 'Type 'undefined' cannot be used as an index type.' Type 'undefined' ...

Using useEffect with promises causing TypeScript errors

useEffect(login, []) In this case, the login function returns a promise and the useEffect hook is triggered without expecting a return value. However, TypeScript shows errors like: Argument of type '() => Promise<void>' is not assi ...

Continuously summon commitments

After extensive searching online, I am still grappling with this particular issue. Currently, I'm developing an Angular service for an Ionic application. This service's primary function is to download an image. In traditional JavaScript, I would ...

When using Angular Reactive Forms with a number type control, the form will trigger a re-render when the

My Angular(v7) Reactive Form (or template-only form) is experiencing issues with re-rendering and validation on blur when using an <input> with type="number". The error feedback <div> next to the input contains a value suggestion button, whic ...

What steps are needed to integrate a Spring Boot application with Angular 2?

After incorporating Angular 2 into my Spring Boot application, I successfully deployed all of my files. However, the routing feature is not working as expected. Below is the file structure. This setup works smoothly with a Node.js server. https://i.sstati ...

Difficulty with Mobx observables and componentDidUpdate() in Typescript React when passing props may lead to unexpected behavior

I am currently working with react, mobx, and typescript and I am facing an issue while trying to send a json array from my logic layer to a UI component. The json data is fetched from an async API call and then stored in an observable variable using mobx. ...