SVG未呈现在pdf文件中(使用pdfmake和html2canvas)

时间:2018-10-24 09:16:24

标签: angular typescript html2canvas pdfmake

这是我的代码,但是此块在IE11上存在一些问题:

let chartTwo = document.getElementById('chartPosizioneGlobale');
              self.callHtml2canvas(chartTwo, 'chartPosizioneGlobale').then((canvas) => {
                const chartData = canvas.toDataURL('image/png');
                /* self.docDefinition.content.push({ image: chartData, alignment: 'right' });*/
                self.docDefinition.content['columns'] = {};
                self.docDefinition.content.push({ "columns": [{ image: chartData, fit: [400, 400] }/*, { image: chartData, fit: [300, 300] }*/] }); 

这是一个svg图表(ngx-charts插件),在chrome上以pdf格式呈现。我尝试更改html2canvas versione,但仍然无法正常工作。这在IE上不起作用,除此图表外,我在pdf上具有所有正确的元素。任何人都知道解决方案,或者您建议使用其他插件?谢谢(在完整的.ts之后)

 import { Component, OnInit, ViewChildren } from '@angular/core';
declare var $: any;
import * as _ from 'underscore';
import { PageService } from '../commons/service.component';
import { AppSettings } from '../commons/url-constant';
import { DatePipe, DecimalPipe } from '@angular/common';
import { IOption } from 'ng-select';
import { TimelineLayoutComponent } from '../timeline-layout/timeline-layout.component';
import { Router, ActivatedRoute } from '@angular/router';
import { Ng2SmartTableModule, LocalDataSource } from 'ng2-smart-table';
import { DomSanitizer } from '@angular/platform-browser';
import { LastUpdateComponent } from '../last-update/last-update.component';
import { DotsMenuComponent } from '../commons/dots-menu/dots-menu.component';
import { SnotifyService, SnotifyPosition, SnotifyToastConfig } from 'ng-snotify';
import { SharedServiceComponent } from '../commons/shared-service/shared-service.component';
import { StartupService } from '../commons/startup.service';
import { GenericChartComponent } from '../generic-chart/generic-chart.component';
/*import * as jsPDF from 'jspdf';*/

declare var pdfMake: any;
import pdfFonts from "./pdfmake/vfs_fonts";
import pdfMake from "pdfmake/build/pdfmake";

/*import 'es6-promise';*/

pdfMake.vfs = pdfFonts.pdfMake.vfs;
import * as html2canvas from 'html2canvas';
import { AUTO_STYLE } from '@angular/animations';
import { discardPeriodicTasks } from '@angular/core/testing';
pdfMake.fonts = {
  myFont: {
    normal: 'Ubuntu-Regular.ttf',
    bold: 'Ubuntu-Bold.ttf',
    italics: 'Ubuntu-Light.ttf',
    bolditalics: 'Ubuntu.ttf'
  }
};

@Component({
  selector: 'app-report-manager',
  templateUrl: './report-manager.component.html',
  styleUrls: ['./report-manager.component.scss']
})

export class ReportManagerComponent implements OnInit {


  /* Provvisori */

  chartAsset2Report = [];
  idChartAsset2 = "chartAsset2";
  tipoServizio = 'UBI Light PF';
  ndg = 'XX9EF41241F';
  nConsulenza = '23648124312';
  luogo = 'Bergamo';
  cliente = 'Mario Rossi';
  today = '23 Ottobre 2018';
  titoloSezione = 'Vista di sintesi - Principali informazioni di portafoglio';
  currentPage = 0;
  downloadFlag = false;

  orangeBar = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQUAAAAECAYAAAA3ZFkCAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAA8SURBVHhe7dgxAQAgAMOwgSWMopYXHlwseeqh4+x1AwAAAADUmL8AAAAAQAlTEAAAAADKmIIAAAAAUCV5/C4CwC0exZ0AAAAASUVORK5CYII=';

  logoUbiBanca = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD';

  iconaVistaSintesi = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAnCAYAAAB9qAq4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAK+SURBVFhH5Zg9a1RBFIb9TyJKNESNJqJZCz';

  docDefinition = {
    content: [
    ],
    defaultStyle: {
      font: 'myFont'
    },
    styles: {
      h1: {
        fontSize: 28,
        color: '#004777',
        bold: true
      },
      h2: {
        fontSize: 17,
        color: '#004777',
        bold: true
      },
      h3: {
        fontSize: 12,
        color: '#004777'
      },
      blue: {
        color: '#004777'
      }
    },
    pageOrientation: 'landscape',
    pageMargins: [0, 0, 0, 0]
  };

  /*  view: any[] = [700, 400];*/

  // options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Country';
  showYAxisLabel = true;
  yAxisLabel = 'Population';

  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
  };

  initialAssets;
  prodottiPortafoglio;
  lastUpdate;
  rows;
  /*pdf = [{
    'tipo': "grafico",
    "grafico": [
      { "CODICE": "001", "DESCRIZIONE": "OBB. E TIT. STATO", "PERCENTUALE": 69.86, "CONTROVALORE": 3942097.1, "CTVPFTTOTALE": 5642856.95 },
      { "CODICE": "002", "DESCRIZIONE": "OBB. E TIT. STATO", "PERCENTUALE": 69.86, "CONTROVALORE": 3942097.1, "CTVPFTTOTALE": 5642856.95 }
    ]
  }];*/

  constructor(private pageService: PageService) {
    let self = this;
    /*self.pdf.forEach(function (item) {
      if (item['tipo'] == 'grafico') {
        item['grafico'].forEach(function (element) {
          element['name'] = element['DESCRIZIONE'];
          element['value'] = element['CTVPFTTOTALE'] / 100 * element['PERCENTUALE'];
          element['percent'] = element['PERCENTUALE'];
        })
      }
    })*/
    self.initialAssets = self.pageService.getSessionStorage('ptfIniziale_' + AppSettings.lastCustomerNdg);
    if (self.initialAssets) {
      let filteredPf = self.initialAssets['grpPortafoglio']['grpElementoSaldo'];
      self.lastUpdate = AppSettings.lastUpdate;
      let groupByCode = _.groupBy(filteredPf, 'dscRapportoCompleto');
      var dataReworked = _.map(groupByCode, function (value, key) {
        return {
          name: key,
          value: value
        };
      });
      self.prodottiPortafoglio = dataReworked;
      self.prodottiPortafoglio.forEach(function (it) {
        let arrayCtv = [];
        let arrayUtile = [];
        it['value'].forEach(function (element) {
          arrayCtv.push(element['impCtvDisponibile']);
          arrayUtile.push(element['impUtilePerdita'])
        })
        var sum = _.reduce(arrayCtv, function (memo, num) { return memo + num; }, 0);
        var sum2 = _.reduce(arrayUtile, function (memo, num) { return memo + num; }, 0);
        it['ctvTotale'] = sum;
        it['impUtileTotale'] = sum2;
      });
    }
    let filters = {}
    /*  debugger;*/
    self.pageService.getProfilazioneReport(filters).toPromise().then(response => {
      let groupedDatas = _.groupBy(response, 'CODICESEZIONE');
      groupedDatas = _.toArray(groupedDatas);
      self.rows = groupedDatas;
      console.log(self.rows)
      let arr = [];
      self.rows.forEach(function (el) {
        let stored = _.filter(el, function (store) {
          if (store.STORED && store.STORED != '') {
            arr.push(store.STORED);
          }
        })
      })
      arr.forEach(function (stored) {
        if (stored == '/recuperaasset2livreport/') {
          self.pageService.getAsset2Report(filters).toPromise().then(response => {

            let firstAggregazione = [];
            firstAggregazione.push({ content: [] });

            firstAggregazione['content'] = response;
            firstAggregazione['content'].forEach(function (item) {
              item['name'] = item['DESCRIZIONE'];
              item['value'] = item['CTVPFTTOTALE'] / 100 * item['PERCENTUALE'];
              item['percent'] = item['PERCENTUALE'];
            });
            self.chartAsset2Report = firstAggregazione['content'];
          })
        }
      })



    })
  }

  callHtml2canvas(chart, chartId) {
    return html2canvas(chart, {
      async: false,
      //height: 500,
      //width: 1000,
      //scale: 3,
      useCORS: false,
      backgroundColor: null,
      logging: false,
      onclone: (document) => {
        document.getElementById(chartId).style.visibility = 'visible';
      }
    })

  }

  printHeader() {
    if (this.currentPage > 3) {
      this.docDefinition.content.push({
        columns: [
          {
            width: 35,
            image: this.iconaVistaSintesi
          },
          {
            width: 'auto',
            text: this.titoloSezione,
            style: ['h2'],
            margin: [0, 7, 0, 0]
          }
        ], columnGap: 10, margin: [10, 15, 0, 0], pageBreak: 'before'
      });
      this.docDefinition.content.push({ image: this.orangeBar, margin: [0, 5, 0, 20] });
    }
  }
  printFooter() {
    if (this.currentPage > 3) {
      this.docDefinition.content.push({
        columns: [
          {
            width: 'auto',
            text: this.currentPage,
            style: ['blue'],
            margin: [15, 15, 580, 15]
          },
          {
            width: 180,
            image: this.logoUbiBanca,
            margin: [30, 15]
          }
        ]
      });
    }
    else if (this.currentPage === 2)
      this.docDefinition.content.push({ image: this.logoUbiBanca, width: 180, margin: [25, 150, 0, 15], alignment: 'right' });
  }

  ngOnInit() {// Charts are now rendered

    let self = this;
    let logo = document.getElementById('logoUbiBanca');
    self.callHtml2canvas(logo, 'logoUbiBanca').then((canvas) => {
      /* Pg.1 */
      self.currentPage++;
      const  logoData  =  canvas.toDataURL();
      self.docDefinition.content.push({  image:  logoData,  width:  230, margin: [35, 50, 0, 175]  });
      self.docDefinition.content.push({ text: 'Report di Diagnosi e Monitoraggio', style: ['h1'], margin: [35, 0, 0, 2] });
      self.docDefinition.content.push({ image: self.orangeBar, margin: 0 });
      let  banner  =  document.getElementById('bannerCanvas');
      self.callHtml2canvas(banner,  'bannerCanvas').then((canvas)  =>  {
        const  bannerData  =  canvas.toDataURL();
        self.docDefinition.content.push({  image:  bannerData, margin: 0,  pageBreak:  'after'  });
        /* Pg.2 */
        self.currentPage++;
        self.docDefinition.content.push({ text: self.cliente, alignment: 'right', style: ['h1'], margin: [25, 260, 35, 5] });
        self.docDefinition.content.push({ image: self.orangeBar, margin: 0 });
        self.docDefinition.content.push({ text: self.tipoServizio, alignment: 'right', style: ['blue'], margin: [25, 8, 35, 2] });
        self.docDefinition.content.push({ text: 'NDG ' + self.ndg, alignment: 'right', style: ['blue'], margin: [25, 2, 35, 2] });
        self.docDefinition.content.push({ text: 'Rapporto di consulenza n. ' + self.nConsulenza, alignment: 'right', style: ['blue'], margin: [25, 2, 35, 5] });
        self.docDefinition.content.push({ text: self.luogo + ', ' + self.today, alignment: 'right', style: ['blue'], margin: [25, 15, 35, 2], fontSize: 9 });
        self.printFooter();
        /* Pg.3 */
        self.currentPage++;
        self.docDefinition.content.push({ text: 'Indice', alignment: 'right', style: ['h1'], margin: [25, 260, 35, 5], pageBreak: 'before' });
        self.docDefinition.content.push({ image: self.orangeBar, margin: 0 });
        this.docDefinition.content.push({
          columns: [
            {
              width: '50%',
              text: ''
            },
            {
              width: '45%',
              table: {
                widths: ['*', 'auto', 20, '*'],
                body: [
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Profilatura ed elenco rapporti considerati', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Posizione globale e composizione portafoglio', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Performance', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Andamento del portafoglio complessivo', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Andamento plus/minus posizioni in essere', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'CVaR', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Indicatore Sintetico di Qualità e Adeguatezza', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Scadenziario e posizione fiscale', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Analisi della componente azionaria', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }],
                  [{ image: self.iconaVistaSintesi, width: 25 }, { text: 'Analisi della componente obbligazionaria', style: ['blue'], bold: true, margin: [0, 5, 0, 0] }, '', { text: 'pag.x', style: 'blue', bold: true, margin: [0, 5, 0, 0] }]
                ]
              },
              layout: 'noBorders'
            },
            {
              width: '5%',
              text: ''
            }
          ]
        });
        let  chart  =  document.getElementById('chartElencoRapporti');
        self.callHtml2canvas(chart,  'chartElencoRapporti').then((canvas)  =>  {
          /* Pg.4 */
          self.currentPage++;
          self.printHeader();
          //DA SCOMMENTARE
          /* const chartData = canvas.toDataURL();
           self.docDefinition.content.push({ image: chartData, width: 400 });*/
          **let chartTwo = document.getElementById('chartPosizioneGlobale');
          self.callHtml2canvas(chartTwo, 'chartPosizioneGlobale').then((canvas) => {
            const chartData = canvas.toDataURL('image/png');
            /* self.docDefinition.content.push({ image: chartData, alignment: 'right' });*/
            self.docDefinition.content['columns'] = {};
            self.docDefinition.content.push({ "columns": [{ image: chartData, fit: [400, 400] }/*, { image: chartData, fit: [300, 300] }*/] });**

            //self.printFooter();


            /* Pg. 43 */
            const disclaimer1 = 'Lorem ipsum dolor sit amet';

            self.currentPage++;
            self.printHeader();
            self.docDefinition.content.push({ text: disclaimer1, margin: [35, 15, 35, 3] });
            self.docDefinition.content.push({ text: disclaimer2, margin: [35, 3, 35, 3] });
            self.docDefinition.content.push({ text: disclaimer3, margin: [35, 3, 35, 3] });
            self.docDefinition.content.push({ text: disclaimer4, margin: [35, 3, 35, 15] });
            self.printFooter();

            self.downloadFlag = true;

          });
        });
      });
    });

  }
  download() {
    // Download PDF
    let self = this;
    if (self.downloadFlag) {
      pdfMake.createPdf(self.docDefinition).download('chartToPdf' + '.pdf');
    } else {
      console.log('Chart is not yet rendered!');
    }

  }

}

0 个答案:

没有答案