Home > OS >  Export data to pdf with a requested parameter
Export data to pdf with a requested parameter

Time:06-27

I want to export part of my data to pdf file using spring boot and angular by including parameter, it worked fine and I tested it with postman, but I can't figure out how to do it with angular.

My Controller :

public ResponseEntity<InputStreamResource>exportPdf(@RequestParam(value="lotNum",required=false) String lotNum) {
    List<Accord> accords=accordRepository.findAllByOrigineAccordLotLotNum(lotNum);
    List<Accord> accordss=accordRepository.findAll();

    List<Affaire> affaires=affaireRepository.findAll();

    if(simulationService.checkLength(accordss, affaires)) {
    
       ByteArrayInputStream bais=simulationService.GeneratePdf(accords);
       HttpHeaders headers = new HttpHeaders();
       headers.add("Content-Dispositon", "inline; filename=simulation.pdf");
       return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_PDF).body(new InputStreamResource(bais));
    } else {
       return new ResponseEntity<>( HttpStatus.CONFLICT);
    }
}

My service.ts:

exportPdf(lotNum:any): Observable<Blob>  {
let params = new HttpParams();
params = params.append('lotNum', lotNum);

const headers =new HttpHeaders({ 'Access-Control-Allow-Origin':'*' ,'Content-Type':'application/json','responseType' :'text' });
return this.http.get("http://localhost:8080/export/pdf",{headers:headers,params:params,responseType:'blob'});}

simulation.ts:

exportPdf(lotNum:any){
  this.date=new Date();
 let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
  this.simulationService.exportPdf(lotNum).subscribe(x=>{
    const blob = new Blob([x],{type:'application/pdf'});
   if (window.navigator && (window.navigator as any).msSaveOrOpenBlob){
   ( window.navigator as any).msSaveOrOpenBlob(blob);
    return;}
    const data = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href=data;
    link.download="simulation" latest_date ".pdf";
    link.dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true,view:window}));
    setTimeout(function(){
      window.URL.revokeObjectURL(data);
      link.remove();
    },100);
  });
}

when I send the request from client side it gives me Status code : 200 and Request URL: http://localhost:8080/export/pdf?lotNum=undefined

CodePudding user response:

Edit: the mistake was in the html file , that's why it was giving undefined in the URL.

<input type="text" id="lotNum" name="lotNum" [(ngModel)]="lotNum">

it was missing [(ngModel)]="lotNum"

  • Related