Я хочу экспортировать pdf из html в angular 6. Итак, я использую библиотеку jspdf. Но я не могу придать стиль, такой как цвет и цвет фона. Как я могу этого добиться? (Если есть другая бесплатная библиотека от jspdf, я могу ее использовать) Вы можете увидеть демо по ссылке ниже.
.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>
Я проголосовал +1, потому что на самом деле это неплохой вопрос ... но у меня нет ответа. Openslide, кажется, делает это, но я не знаю, как это работает github.com/OpenSlides/OpenSlides
Спасибо @BenjaminCaure. Я не понимал, почему один человек проголосовал против этого вопроса.
Но я хочу от html. Не с машинописным кодом. Потому что в реальном сценарии ячеек будет много. doc.addHtml отлично работает со стилем. Но в doc.addHtml качество pdf очень плохое. @Bharathkumarkamal





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. Прочтите эту статью о как написать хороший ответ. В дополнение к предоставленному вами коду, попробуйте объяснить, почему и как это решает проблему.
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.info(dataURLS);
for (const ind in dataURLS) {
if (dataURLS.hasOwnProperty(ind)) {
console.info(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, чтобы установить следующие
npm install jspdf --save
npm install --save @types/jspdf
npm install html2canvas --save
npm install --save @types/html2canvas
При этом добавьте следующее в файл angular.json внутри тега scripts
"node_modules/jspdf/dist/jspdf.min.js"
Внутри component.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>с помощью этого кода добавьте css, как вы обычно добавляете в component.css, он будет отображаться.
Надеюсь, это решит вашу проблему.
Вы можете использовать пакет jsPDF и dom to image для экспорта HTML div с id='dashboard'.
Установить пакет
import * as domtoimage from 'dom-to-image';
import * as FileSaver from 'file-saver';
import * as jsPDF from 'jspdf';
TS файл
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>
[https://www.c-sharpcorner.com/article/convert-html-to-pdf-using-angular-6/][1 npm install jspdf
And to install html2canvas package, use given npm command. npm install html2canvas
When we are done with the installation part, it's time to import it into our component using the import statement.
> 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
);
Используйте этот способ пример stackblitz В вашей демо-версии используйте этот способ
import {jsPDF} from 'jspdf';
public downloadPDF() {
const doc = new jsPDF();
.....
}
Вы можете использовать
doc.setFillColor(0, 0, 0)для установки цвета фона иdoc.setTextColor(255)для установки цвета