用Angular 6从HTML导出PDF

5
我想从Angular 6中的HTML中导出PDF。所以我正在使用“jspdf”库。但是我无法设置样式,如颜色和背景颜色。我该怎么做才能实现这个功能?(如果有其他免费的库可以用来代替“jspdf”,我也可以使用它) 您可以从下面的链接中查看演示。 DEMO .ts 文件
export class AppComponent  {
  @ViewChild('reportContent') reportContent: ElementRef;

    downloadPdf() {
    const doc = new jsPDF();
    const specialElementHandlers = {
      '#editor': function (element, renderer) {
        return true;
      }
    };

    const content = this.reportContent.nativeElement;

    doc.fromHTML(content.innerHTML, 15, 15, {
      'width': 190,
      'elementHandlers': specialElementHandlers
    });

    doc.save('asdfghj' + '.pdf');
  }
}

.html 文件

<div #reportContent class="p-col-8 p-offset-2">
  <table>
    <tr>
      <td style="color: red;background-color: blue;border:solid;">1111
      </td>
      <td style="border:solid;">2222
      </td>
    </tr>
  </table>
</div>

<button pButton type="button" label="Pdf" (click)="downloadPdf()">Export Pdf</button>

你可以使用 doc.setFillColor(0, 0, 0) 来设置背景颜色,使用 doc.setTextColor(255) 来设置颜色。 - Bharathkumar kamal
我投了+1,因为这实际上是一个非常好的问题...但我自己没有答案。看起来Openslide可以做到,但我不知道它是如何工作的https://github.com/OpenSlides/OpenSlides - Benjamin Caure
感谢@BenjaminCaure。我不理解为什么有一个人对这个问题进行了负评。 - realist
1
但是,我想要从HTML中获取。不用TypeScript代码。因为在实际情况下会有很多单元格。doc.addHtml在样式方面表现良好。但是在doc.addHtml中,PDF的质量非常差。@Bharathkumarkamal - realist
5个回答

2
    captureScreen() {
        const pdf = new jsPDF('p', 'mm');
        const promises = $('.pdf-intro').map(function(index, element) {
            return new Promise(function(resolve, reject) {
                html2canvas(element, { allowTaint: true, logging: true })
                    .then(function(canvas) {
                        resolve(canvas.toDataURL('image/jpeg', 1.0));
                    })
                    .catch(function(error) {
                        reject('error in PDF page: ' + index);
                    });
            });
        });

        Promise.all(promises).then(function(dataURLS) {
            console.log(dataURLS);
            for (const ind in dataURLS) {
                if (dataURLS.hasOwnProperty(ind)) {
                    console.log(ind);
                    pdf.addImage(
                        dataURLS[ind],
                        'JPEG',
                        0,
                        0,
                        pdf.internal.pageSize.getWidth(),
                        pdf.internal.pageSize.getHeight(),
                    );
                    pdf.addPage();
                }
            }
            pdf.save('HTML-Document.pdf');
        });
    }

使用这个方法,我们需要将jsPDF和html2Canvas导入代码中。最初的回答。
    import * as jsPDF from 'jspdf';
    import * as html2canvas from 'html2canvas';

为了实现这个,您需要执行npm install以下内容。最初的回答。
    npm install jspdf --save
    npm install --save @types/jspdf
    npm install html2canvas --save
    npm install --save @types/html2canvas

使用以下内容添加到scripts标签内的angular.json文件中
    "node_modules/jspdf/dist/jspdf.min.js"

在组件的html文件中添加类似以下的代码示例:

<div>
  <input type="button" value="CPTURE" (click)="captureScreen()" />
</div>
<div class="pdf-intro">HTHML content</div>
<div class="pdf-intro">HTHML content</div>
<div class="pdf-intro">HTHML content</div>
<div class="pdf-intro">HTHML content</div>

使用这段代码,就像在 component.css 中添加一样添加 CSS,它将被渲染。
希望这解决了你的问题。

1
你可以使用jsPDFdom to image软件包来导出具有id='dashboard'的HTML div。
安装软件包。
import * as domtoimage from 'dom-to-image';
import * as FileSaver from 'file-saver';
import * as jsPDF from 'jspdf';

TS file

domtoimage.toPng(document.getElementById('dashboard'))
    .then(function (blob) {
        var pdf = new jsPDF('l', 'pt', [$('gridster').width(), $('gridster').height()]);
        pdf.addImage(blob, 'PNG', 0, 0, $('gridster').width(), $('gridster').height());
        pdf.save(`${that.dashboardName}.pdf`);
    });

HTML

<gridster id='dashboard'></gridster>

0

html2canvas可以解决您的问题。请按照以下方式更新您的代码。

downloadPdf() {
const doc = new jsPDF();
const content = this.reportContent.nativeElement;
html2canvas(content).then(canvas => {
        const imgData = canvas.toDataURL('image/png');
        // Few necessary setting options
        const imgWidth = 208;
        const pageHeight = 295;
        const imgHeight = canvas.height * imgWidth / canvas.width;
        const doc = new jspdf('p', 'mm');
        let heightLeft = imgHeight;
        let position = 0;

        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
        while (heightLeft >= 0) {
            position = heightLeft - imgHeight;
            doc.addPage();
            doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;
        }
        // Generated PDF
        doc.save('asdfghj' + '.pdf');
    });

}


欢迎来到stackoverflow。请考虑阅读这篇关于如何撰写优质答案的文章。除了提供代码外,尽量给出一些解释,说明为什么以及如何解决问题。 - jtate

0

使用这种方法 stackblitz 示例 在你的演示中这样使用

import {jsPDF} from 'jspdf';


public downloadPDF() {
   const doc = new jsPDF();
   .....
}

0
[https://www.c-sharpcorner.com/article/convert-html-to-pdf-using-angular-6/][1 npm install jspdf
然后使用以下给定的npm命令安装html2canvas包。 npm install html2canvas
当我们完成安装部分后,就可以使用导入语句将其导入到我们的组件中了。
            > import * as jspdf from 'jspdf';      import html2canvas from
            > 'html2canvas';

                <div id="content" #content>  
            <mat-card>  
                <div class="alert alert-info">  
                    <strong>Html To PDF Conversion - Angular 6</strong>  
                </div>  
                <div>  
                <input type="button" value="CPTURE" (click)="captureScreen()"/>  
                </div>  
            </mat-card>  
            </div>  
            <div >  
            <mat-card>  
                <table id="contentToConvert">  
                    <tr>  
                    <th>Column1</th>  
                    <th>Column2</th>  
                    <th>Column3</th>  
                    </tr>  
                    <tr>  
                    <td>Row 1</td>  
                    <td>Row 1</td>  
                    <td>Row 1</td>  
                    </tr>  
                    <tr>  
                    <td>Row 2</td>  
                    <td>Row 2</td>  
                    <td>Row 2</td>  
                    </tr>  
                    <tr>  
                    <td>Row 3</td>  
                    <td>Row 3</td>  
                    <td>Row 3</td>  
                    </tr>  
                    <tr>  
                    <td>Row 4</td>  
                    <td>Row 4</td>  
                    <td>Row 4</td>  
                    </tr>  
                    <tr>  
                    <td>Row 5</td>  
                    <td>Row 5</td>  
                    <td>Row 5</td>  
                    </tr>  
                    <tr>  
                    <td>Row 6</td>  
                    <td>Row 6</td>  
                    <td>Row 6</td>  
                    </tr>  
                </table>  

            </mat-card>  
            </div>  

                import { Component, OnInit, ElementRef ,ViewChild} from '@angular/core';  
            import * as jspdf from 'jspdf';  
            import html2canvas from 'html2canvas';  

            @Component({  
            selector: 'app-htmltopdf',  
            templateUrl: './htmltopdf.component.html',  
            styleUrls: ['./htmltopdf.component.css']  
            })  
            export class HtmltopdfComponent{  
            public captureScreen()  
            {  
                var data = document.getElementById('contentToConvert');  
                html2canvas(data).then(canvas => {  
                // Few necessary setting options  
                var imgWidth = 208;   
                var pageHeight = 295;    
                var imgHeight = canvas.height * imgWidth / canvas.width;  
                var heightLeft = imgHeight;  

                const contentDataURL = canvas.toDataURL('image/png')  
                let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF  
                var position = 0;  
                pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)  
                pdf.save('MYPdf.pdf'); // Generated PDF   
                });  
            }  
            } 

                new JsPDF(  
                Orientation, // Landscape or Portrait  

                unit, // mm, cm, in  

                format // A2, A4 etc  
            );  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接