我正在使用jsPDF将jsPDF-autotable生成html到pdf,页眉和页脚打印良好。我曾尝试在标头中添加徽标,但无法打印它,当我console.log(base64Img)
并将其转换时,它是相同的徽标。
这是将图像转换为base64字符串的代码
imgToBase64 (url, callback) {
if (!window.FileReader) {
callback(null);
return;
}
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
const reader = new FileReader();
reader.onloadend = function () {
callback((reader.result as string).replace('text/xml', 'image/jpeg'));
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
这是生成pdf的代码
generatePDF() {
let base64Img = null;
this.imgToBase64(this.imageURL, (base64) => {
base64Img = base64;
console.log('image in base 64', base64Img);
const doc = new jspdf('p', 'pt', 'a4');
const header = function(headerData: any) {
doc.setFontSize(20);
doc.setTextColor(0, 190, 208);
doc.setFontStyle('normal');
if (this.base64Img) {
doc.addImage(this.base64Img, 'JPEG', headerData.settings.margin.left, 15, 60, 10);
doc.setFontSize(20);
}
doc.text('Header Title', headerData.settings.margin.left, 60);
const currentdate = new Date();
const datetime = currentdate.getDate() + '/' + (currentdate.getMonth() + 1) + '/' + currentdate.getFullYear();
doc.text('Date: ' + datetime, headerData.settings.margin.left + 400, 60);
doc.setFontSize(5);
};
const totalPagesExp = '{total_pages_count_string}';
const footer = function(footerData) {
doc.setFontSize(10);
let str = 'Page ' + footerData.pageCount;
// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
str = str + ' of ' + totalPagesExp;
console.log('test');
}
doc.text(str, footerData.settings.margin.left, doc.internal.pageSize.height - 10);
doc.text('https://wwww.example.com', footerData.settings.margin.left + 400, doc.internal.pageSize.height - 10);
};
const head = [['Name', 'Phone', 'Email', 'Gender', 'Location', 'Country']]
const options = {
beforePageContent: header,
afterPageContent: footer,
margin: {
top: 100
},
head: head,
columnStyles: {
0: {columnWidth: 100},
1: {columnWidth: 80},
2: {columnWidth: 80},
3: {columnWidth: 50},
}
};
const elem = document.getElementById('pdfContent');
const data = doc.autoTableHtmlToJson(elem);
doc.autoTable( data.columns, data.rows, options);
// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
doc.putTotalPages(totalPagesExp);
}
doc.save('generated.pdf');
});
}
答案 0 :(得分:0)
我觉得我为时已晚,但这会帮助其他人。
您可以使用like
var doc = new jsPDF('p', 'pt');
var header = function (data) {
doc.setFontSize(18);
doc.setTextColor(40);
doc.setFontStyle('normal');
doc.addImage(base64_source, 'JPEG', data.settings.margin.left, 20, 50, 50);
//doc.addImage(image base64_source, 'image format', logo_sizes.centered_x, _y, logo_sizes.w, logo_sizes.h);
//Image must be Base64 encoded
};
doc.autoTable(columns, rows, {margin: {top: 80}, beforePageContent: header});
doc.save("test.pdf");
注意:您必须与代码变量一起使用,这只是演示。