【问题标题】:Print PDF in ionic 3在 ionic 3 中打印 PDF
【发布时间】:2018-08-13 08:56:25
【问题描述】:

我正在使用 PDFMake 来创建带有我预定义的文档定义的 pdf。在我的旧 ionic 1 项目中,我将编码的字符串传递给 print 函数,它工作正常。这是旧离子 1 的代码

var dd = $scope.createDocumentDefinition();
            $timeout(function () {
                var pdf = pdfMake.createPdf(dd);
                pdf.getBase64(function (encodedString) {
                    console.log(encodedString);
                    $ionicLoading.hide();
                    window.plugins.PrintPDF.print({
                        data: encodedString,
                        type: 'Data',
                        title: 'Print Document',
                        success: function () {
                            console.log('success');
                        },
                        error: function (data) {
                            data = JSON.parse(data);
                            console.log('failed: ' + data.error);
                        }
                    });
                });
            }, 1000);

现在我正在将我的项目升级到 Ionic 3,所以我尝试了同样的事情,但输出不同,这里是我的新 ionic 3 代码。打印机打开,但不是按照我的文档定义打印,而是打印编码的字符串。

let printer_ = this.printer;
    var dd = this.createDocumentDefinition();
    var pdf = pdfMake.createPdf(dd);
    pdf.getBase64(function (_encodedString) {
      let options: PrintOptions = {
        name: 'MyDocument'
      };
      console.log(JSON.stringify(pdf));
      printer_.print(_encodedString, options).then((msg)=>{
        console.log("Success",msg);
      },(error)  => {
        console.log("Error", error);
      });
  });

知道如何在 ionic 3 中使用它吗??

【问题讨论】:

    标签: ionic-framework ionic3 pdfmake


    【解决方案1】:

    您可以使用 pdfmake 使用 ionic 生成 PDF。

    首先你需要为文件和文件打开器安装插件。

    ionic cordova plugin add cordova-plugin-file-opener2
    ionic cordova plugin add cordova-plugin-file
    

    然后安装 NPM 文件包,FileOpener 和 PDF make

    npm install pdfmake 
    npm install @ionic-native/file-opener 
    npm install @ionic-native/file
    

    打开您的 src/app.module.ts 并包含文件和文件操作器参考:

    import { File } from '@ionic-native/file';
    import { FileOpener } from '@ionic-native/file-opener';
    

    在提供程序中添加 File 和 FileOpener

    providers: [
        StatusBar,
        SplashScreen,
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        File,
        FileOpener
      ]
    

    我正在生成一个模板 UI,如下所示:

    <ion-header>
      <ion-navbar>
        <ion-title>
          Ionic PDF
        </ion-title>
      </ion-navbar>
    </ion-header>
    
    <ion-content padding>
    
      <ion-item>
        <ion-label stacked>From</ion-label>
        <ion-input [(ngModel)]="letterObj.from"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>To</ion-label>
        <ion-input [(ngModel)]="letterObj.to"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>Text</ion-label>
        <ion-textarea [(ngModel)]="letterObj.text" rows="10"></ion-textarea>
      </ion-item>
    
      <button ion-button full (click)="createPdf()">Create PDF</button>
      <button ion-button full (click)="downloadPdf()" color="secondary" [disabled]="!pdfObj">Download PDF</button>
    
    </ion-content>
    

    之后,您的 home.component.ts 代码如下所示:

    import { Component } from '@angular/core';
    import { NavController, Platform } from 'ionic-angular';
    
    import pdfMake from 'pdfmake/build/pdfmake';
    import pdfFonts from 'pdfmake/build/vfs_fonts';
    pdfMake.vfs = pdfFonts.pdfMake.vfs;
    
    import { File } from '@ionic-native/file';
    import { FileOpener } from '@ionic-native/file-opener';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      letterObj = {
        to: '',
        from: '',
        text: ''
      }
    
      pdfObj = null;
    
      constructor(public navCtrl: NavController, private plt: Platform, private file: File, private fileOpener: FileOpener) { }
    
      createPdf() {
        var docDefinition = {
          content: [
            { text: 'REMINDER', style: 'header' },
            { text: new Date().toTimeString(), alignment: 'right' },
    
            { text: 'From', style: 'subheader' },
            { text: this.letterObj.from },
    
            { text: 'To', style: 'subheader' },
            this.letterObj.to,
    
            { text: this.letterObj.text, style: 'story', margin: [0, 20, 0, 20] },
    
            {
              ul: [
                'Bacon',
                'Rips',
                'BBQ',
              ]
            }
          ],
          styles: {
            header: {
              fontSize: 18,
              bold: true,
            },
            subheader: {
              fontSize: 14,
              bold: true,
              margin: [0, 15, 0, 0]
            },
            story: {
              italic: true,
              alignment: 'center',
              width: '50%',
            }
          }
        }
        this.pdfObj = pdfMake.createPdf(docDefinition);
      }
    
      downloadPdf() {
        if (this.plt.is('cordova')) {
          this.pdfObj.getBuffer((buffer) => {
            var blob = new Blob([buffer], { type: 'application/pdf' });
    
            // Save the PDF to the data Directory of our App
            this.file.writeFile(this.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(fileEntry => {
              // Open the PDf with the correct OS tools
              this.fileOpener.open(this.file.dataDirectory + 'myletter.pdf', 'application/pdf');
            })
          });
        } else {
          // On a browser simply use download!
          this.pdfObj.download();
        }
      }
    
    }
    

    【讨论】:

    • 我知道这一点.. 正确阅读问题.. 我想打印 PDF .. 但打印机插件仅将输入作为 HTML 和字符串,而 PDFmake 库输出为 base64/buffer/blob ..
    • 然后您可以使用此代码打印 Printer.isAvailable().then(function(){ Printer.print(this.file.dataDirectory + 'myletter.pdf', options).then (function(){ alert("打印成功!"); },function(){ alert("打印时出错!"); }); }, function(){ alert('错误:您的打印机无法打印设备 '); });
    • 你能做同样的演示 git repo 吗?
    • 学分,除非这是你的教程?:ionicacademy.com/create-pdf-files-ionic-pdfmake
    • @mc01 我在 youtube 上观看 ionic academy 的 Simon 时也认出了这个代码..
    猜你喜欢
    • 2013-08-31
    • 2021-01-10
    • 2018-09-12
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多