Невозможно получить правильное форматирование моего PDF с jsPDF - PullRequest
0 голосов
/ 15 ноября 2018

Я пытался экспортировать свои данные в формат PDF, но при загрузке этого файла я не смог получить правильный формат в моем PDF.

Если у меня только 2,3 поля, оно отображается правильно, но если у меня более 5,6 полей, мой файл PDF отображается как показано ниже.

enter image description here

Как решить эту проблему.

Есть ли простой способ экспортировать мои данные в формат PDF.

это мой listuser.component.html

<div class="container" id="content" #content>                          
     <table class="table table-striped">
       <thead>
          <th>Id</th>
          <th>User Name</th>
          <th>type</th>
          <th>Model Name</th>
          <th>Year</th>
      </thead>
        <tbody *ngIf="isTableResult ; else noTableResults">         
           <tr *ngFor="let user of users">
             <td>{{user.id}}</td>
             <td>{{user.username}}</td>
             <td>{{user.type}}</td>
             <td>{{user.modelname}}</td>
             <td>{{user.year}}</td>                                
          </tr>
        </tbody>
          <ng-template #noTableResults>
            <tr>
               <td> 
                 We are sorry , no users according to your search.
               </td>
            </tr>
         </ng-template>
     </table>        
</div>
    <br />
    <button (click)="downloadPDF()">Export to PDF</button>

это мой listuser.component.html

import { Component, ViewChild,ElementRef,OnInit } from '@angular/core';
import * as jsPDF from 'jspdf';
@Component({
  selector: 'app-listuser',
  templateUrl: './listuser.component.html',
  styleUrls: ['./listuser.component.css'],
})
export class ListuserComponent implements OnInit {

  ngOnInit() {
    this.filteredUsers = this.users.slice();
    this._userService.getUsers().subscribe((users) => {
      this.users = users;          
    }, (error) => {
      console.log(error);
    })
  }

  @ViewChild('content') content:ElementRef;
  public downloadPDF(){
    let doc=new jsPDF();
    let specialElementHandlers={
      '#editor':function(element,renderer){
        return true;
      }
    };
    let content=this.content.nativeElement;
    doc.fromHTML(content.innerHTML,15,15 ,{
      'width':50,
      'elementHandlers':specialElementHandlers
    });

    doc.save('test.pdf');
  }
}

1 Ответ

0 голосов
/ 15 ноября 2018

У меня нет больше идей о jsPDF, так как я больше не использовал его.

Здесь я использовал пакет с именем pdfmake.Итак, я обновил ответ, используя пакет pdfmake.

Выполните следующие шаги, чтобы добавить pdfmake в свой угловой проект:

Установите pdfmake, используя npm

npm i pdfmake

Тогдав компонент добавьте строки сверху:

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

Наконец, добавьте большую часть кода для создания и загрузки pdf:

function generatePDF() {
 var docDefinition = {
  content: [
    {
      layout: 'lightHorizontalLines', // optional
      table: {
        headerRows: 1,
        widths: ['auto', 'auto', 'auto'],

        body: [
          ['Name', 'DOB', 'Status'], // headers
          ['Surjeet Bhadauirya', '22/08/1994', 'active'] // data
          ['Preeti', '23/01/1995', 'active']
        ]
      }
    }
  ]
};


this.users.forEach((user) => {
  let temp = [user.id, user.type, user.modelname, user.year, user.seating_capacity, user.milleage, user.pincode, user.number, user.email, user.cost];
  docDefinition.content[0].table.body.push(temp); 
});  

pdfMake.createPdf(docDefinition).download();
}

Рабочая демонстрация здесь: https://stackblitz.com/edit/angular-hcxlfw

...