5

enter image description here

Latest code::: convert() {

  const doc = new jsPDF();
  // tslint:disable-next-line:max-line-length
  const col = ['DischargeDate', 'Case Number', 'Patient Name', 'Hospital Name',  'Payor', 'Total Doctor Fee', 'To be Collected'];
  const rows = [];

/* The following array of object as response from the API req  */

const itemNew = this.finalArList;

itemNew.forEach(element => {
  // tslint:disable-next-line:max-line-length
  const temp = [element.dischargeDate, element.caseNo, element.patientName, element.instName, element.payor, element.totalDrFee, element.drFeeToCollect];
  rows.push(temp);

});

  doc.autoTable(col, rows);
  doc.save('Test.pdf');
}

The above is the api url that returns an array of object and in View I am printing those data. Now how to download this list as a pdf format.enter image description here

json data returned from api call would look something like this. How do I implement download as PDF for this json data.

Okay here is the code I have tried.

public downloadPdf() {
      return this.http
        .get('http://161.202.31.51:8185/sgdocsrv/ar/getARList', {
          responseType: ResponseContentType.Blob
        })
        .map(res => {
          return {
            filename: 'filename.pdf',
            data: res.blob()
          };
        })
        .subscribe(res => {
            console.log('start download:', res);
            const url = window.URL.createObjectURL(res.data);
            const a = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display: none');
            a.href = url;
            a.download = res.filename;
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove(); // remove the element
          }, error => {
            console.log('download error:', JSON.stringify(error));
          }, () => {
            console.log('Completed file download.')
          });
    }

But it doesnt work . Here the return this.http has a get call, but my api has a post method. I am not sure whats the exact logic to try.

Nancy
  • 911
  • 7
  • 26
  • 54
  • Since the backend is just giving you JSON data, I think the best you are going to be able to do is let the user print the page to pdf. Think about all the places you see "See Printable Version"" links, like for plane tickets. – Andrew Roth Apr 24 '18 at 16:42
  • 1
    It got downvoted because it is not of sufficient quality to provide a good answer. Ways to improve the question could include things like things you've already tried, sample code, documentation that you are using, etc. Edit: It's rude to delete your comment like that, now my comment is out of context. OP originally asked "Why did my question get downvoted?" – Andrew Roth Apr 24 '18 at 16:43
  • Okay i have added the code I have tried Can u remove the downvote now – Nancy Apr 24 '18 at 16:47
  • 1
    I didn't downvote it. – Andrew Roth Apr 24 '18 at 16:48
  • @whoever has downvoted I am looking for a serious solution after lot many tries . Just like that downvoting is not fair – Nancy Apr 24 '18 at 16:49
  • 1
    Something like [jsPDF](https://github.com/MrRio/jsPDF) may suit your needs. – Andrew Roth Apr 24 '18 at 16:57
  • I think you're question got downvoted because your approach is too naive. You cannot just add a `.pdf` extension to JSON file and expect the outcome to be valid PDF file. – kvetis Apr 24 '18 at 17:04
  • okay so can u tell me the proper solution for this – Nancy Apr 24 '18 at 17:13

1 Answers1

8

You can use jspdf and jspdf-autotable to download as pdf. Here is the example: But you need to modify the code as per your requirement. You need to assign your JSON array in rowCountModNew. Hope it will help u

In HTML:

<a (click)="convert()">Generate PDF</a>

In TS file:

import * as jsPDF from 'jspdf';
import 'jspdf-autotable';

And use the below function :

convert() {

    var doc = new jsPDF();
    var col = ["Id", "TypeID","Accnt","Amnt","Start","End","Contrapartida"];
    var rows = [];

var rowCountModNew = [
["1721079361", "0001", "2100074911", "200", "22112017", "23112017", "51696"],
["1721079362", "0002", "2100074912", "300", "22112017", "23112017", "51691"],
["1721079363", "0003", "2100074913", "400", "22112017", "23112017", "51692"],
["1721079364", "0004", "2100074914", "500", "22112017", "23112017", "51693"]
]


rowCountModNew.forEach(element => {
      rows.push(element);

    });


    doc.autoTable(col, rows);
    doc.save('Test.pdf');
  }

Considering an array of object as response the modified code will be:

    convert() {

        var doc = new jsPDF();
        var col = ["Details", "Values"];
        var rows = [];

  /* The following array of object as response from the API req  */

     var itemNew = [    
      { id: 'Case Number', name : '101111111' },
      { id: 'Patient Name', name : 'UAT DR' },
      { id: 'Hospital Name', name: 'Dr Abcd' }    
    ]


   itemNew.forEach(element => {      
        var temp = [element.id,element.name];
        rows.push(temp);

    });        

        doc.autoTable(col, rows);
        doc.save('Test.pdf');
      }

And the pdf will look like thisenter image description here

Rak2018
  • 935
  • 6
  • 16
  • Thanks for the response. Your solution works great !. Here you have hardcoded row and column data . But my question is to retrieve the data from api Request url :(http://161.202.31.51:8185/sgdocsrv/ar/getARList) and response will be an array of objects. How do I achieve this? – Nancy Apr 25 '18 at 06:06
  • Ok..So I believe you are getting response from the URL above as an array of objects ..Can you put a sample response here, so that it will be easy to answer. – Rak2018 Apr 25 '18 at 14:46
  • However I updated the code with a sample array objects. The key name may be different in your case which you can modify. Hope it will help u – Rak2018 Apr 25 '18 at 15:46
  • Any idea about this question ? html2canvas plugin https://stackoverflow.com/questions/50018124/download-pdf-is-not-rendering-the-complete-list-of-data-from-ngfor-using-html2ca – Nancy Apr 25 '18 at 16:47
  • I have implemented this method. I am getting the list of data in my PDF . But in my case, the number of columns are more . So the row elements form a ellipsis and doesnt display completely . Please help !! I have attached the screen shot for reference. Any way can we see the data with out being hidden? – Nancy May 18 '18 at 15:52
  • Rak2018 any suggestions for the above comment? – Nancy May 19 '18 at 06:25
  • You can use styles: { overflow: 'linebreak', // fontSize: 50, // rowHeight: 60, columnWidth: 'wrap' }, pageBreak: 'auto' to solve your problem...if your table coloumn no is too long, then it will be better to divide it into two table and print to pdf – Rak2018 May 21 '18 at 14:53
  • Could you pls provide an example of two table structure – Nancy May 23 '18 at 05:07
  • You can refer this post..https://stackoverflow.com/questions/50180380/export-an-array-as-table-using-jspdf/50182131?noredirect=1#comment87384607_50182131 – Rak2018 May 23 '18 at 14:16
  • Do you have a solution for this link https://stackoverflow.com/questions/50484000/jspdf-and-jspdf-auto-table-height-issue – Nancy May 23 '18 at 15:34