Я использую Angular и хочу преобразовать таблицу из html в pdf, это мой код в component.ts:
downloadPDF() {
const doc = new jsPDF();
const specialElememtHandlers = {
'#editor'(element, renderer) {
return true;
}
};
doc.fromHTML(this.content.nativeElement.innerHTML, 15, 15, {
width: 190,
elementHandlers: specialElememtHandlers
});
doc.save('test.pdf');
}
и мой html-код:
<button (click) = "downloadPDF()">Save as PDF</button>
Я на самом деле могу скачать pdf, но он полностью белый.
🤔 А знаете ли вы, что...
Angular Universal позволяет рендерить веб-приложение на сервере для улучшения SEO и производительности.
Вы можете использовать библиотеку «PrintJS» для преобразования html-шаблонов в pdf. https://printjs.crabbly.com/
Сначала установите этот пакет
npm install jspdf
И установить пакет html2canvas.
npm install html2canvas
Импортируйте его в наш компонент, используя оператор импорта.
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
в вашем коде ТС:
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'); //Id of the table
html2canvas(data).then(canvas => {
// Few necessary setting options
let imgWidth = 208;
let pageHeight = 295;
let imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
let position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
pdf.save('MYPdf.pdf'); // Generated PDF
});
}
}
Сначала установите этот пакет
npm install jspdf
npm install [email protected] //working with this html2canvas version.
Импортируйте его в наш компонент, используя оператор импорта (app.component.ts).
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
Добавьте app.component.html
<div class = "abc" id = "content">
<h1>Hello World!</h1>
<button (click) = "Screen()">make pdf</button>
</div>
Добавить app.component.ts
Screen()
{
var data = document.getElementById('content');
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
});
}