以角度将 HTML 转换为 PDF 时,屏幕内容被裁剪,并且正在创建多个页面。
我尝试过使用jspdf。 这是我的 ts 代码
import { Component, ElementRef, ViewChild } from '@angular/core';
import {jsPDF} from 'jspdf';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'HTML_JSPDF';
@ViewChild('htmlTemplate', { static: false })
htmlTemplate!: ElementRef;
generatePDF(){
const doc = new jsPDF();
doc.html(this.htmlTemplate.nativeElement, {
callback: (pdf) => {
pdf.save("sample.pdf")
}
})
}
}
但是 PDF 是使用裁剪后的内容创建的,而我希望 PDF 中的所有内容与屏幕上显示的内容完全相同。
这是 jsPDF 的一个非常常见的问题 我要做的就是解决这个问题 我给我们想要打印的 html 元素提供以英寸为单位的高度和宽度, 高度和宽度应与首选页面尺寸相同。 对于 A4 来说是 (8.3 x 11.7) 对于字母来说是 (8.5 x 11)
.a4{
width: 8.3in;
height: 11.7in;
}
<div class="a4">
This is the html to be printed
</div>
generatePDF(){
const doc = new jsPDF();
doc.html(this.htmlTemplate.nativeElement, {
callback: (pdf) => {
pdf.save("sample.pdf")
}
})
}
请记住,某些 css 属性可能不适用于 jsPDF
'auto' values for css properties
,
shorthand css values
,
svg images
,
flex
(有时),
psuedo css(before, after)
给出图像的固定高度和宽度。
问题可能是当您使用以下代码创建实例时:
const doc = new jsPDF();
它有一些默认属性,例如“A4”格式,您的内容可能不适合其中。您可以更改这些属性以适应内容。
const doc = new jsPDF( {orientation: 'p',unit: 'mm',format: 'a4',putOnlyUsedFonts:true} )