我们需要将包含图像的HTML下载到Pdf文件中。
为此,我们使用了html2canvas和jsPDF,但是它仅导出HTML,HTML中也使用了某些图像,这些图像未包含在Pdf文件中。
import html2canvas from 'html2canvas';
import * as jsPDF from 'jspdf';
downloadPdf() {
var data = document.getElementById('v-9');
html2canvas(data).then(canvas => {
var imgWidth = canvas.width > 198 ? 198 : canvas.width;
var imgHeight = canvas.height * imgWidth / canvas.width;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jsPDF('p', 'mm', 'a4'); // A4 size page of PDF
var position = 5;
pdf.addImage(contentDataURL, 'PNG', 5, position, imgWidth, imgHeight)
pdf.save('file.pdf'); // Generated PDF
});
}
<button id="roomChildrenClear" class="btn btn-block" type="button" (click)="downloadPdf()">Download</button>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="v-9" width="100%" height="100%">
<g id="v-10" class="joint-viewport">
<g model-id="a3bf26bd-bdbf-4e3a-84e9-7ba266a33f59" id="j_4" class="joint-cell joint-type-basic joint-type-basic-image joint-element joint-theme-default" data-type="basic.Image" fill="#ffffff" stroke="none" transform="translate(1,1)">
<g class="rotatable" id="v-26">
<g class="scalable" transform="scale(3.125,3.125)">
<image id="v-28" xlink:href="../../images/icons/door.png" width="16" height="16"></image>
</g>
<text id="v-27" font-size="14" display="none" xml:space="preserve" y="0.8em" text-anchor="middle" fill="#000000" font-family="Arial, helvetica, sans-serif" transform="matrix(1,0,0,1,25,70)">
<tspan id="v-29" class="v-line v-empty-line" dy="0em" style="fill-opacity: 0; stroke-opacity: 0;">-</tspan>
</text>
</g>
</g>
<g model-id="c4349d44-5b4e-4d3b-ba73-73691cd88c29" id="j_5" class="joint-cell joint-type-basic joint-type-basic-rect joint-element joint-theme-default" data-type="basic.Rect" fill="#ffffff" stroke="none" transform="translate(1,1)">
<g class="rotatable" id="v-30">
<g class="scalable" transform="scale(0.5,0.8333333333333334)">
<rect id="v-31" fill="#1240AB" stroke="#1240AB" width="100" height="60" stroke-miterlimit="10" dbid="doorid123:0" fill-opacity="0.03"></rect>
</g>
<text id="v-32" font-size="14" display="none" xml:space="preserve" y="0.8em" fill="#000000" text-anchor="middle" font-family="Arial, helvetica, sans-serif" transform="matrix(1,0,0,1,25,25)">
<tspan id="v-33" class="v-line v-empty-line" dy="0em" style="fill-opacity: 0; stroke-opacity: 0;">-</tspan>
</text>
</g>
</g>
</g>
<defs id="v-11"></defs>
</svg>
实际:图片图标未显示在pdf文件中。
答案 0 :(得分:0)
您可以尝试将这些配置设置为options参数:
html2canvas(data, {
useCORS: true,
foreignObjectRendering: true,
allowTaint: true
})
如果这对您不起作用,我将在此处附加文档链接: https://html2canvas.hertzen.com/configuration
在某些情况下,尝试微调这些选项的配置会产生令人满意的结果。
我在Angular 5应用程序上尝试该问题时独自面对了这个问题,并通过使用puppeteer访问我自己的应用程序解决了该问题。 您也可以尝试操纵p:https://pptr.dev
链接到有关我的问题的讨论: Html2Canvas foreignObjectRendering only render viewpoint Html2Canvas foreignObjectRendering only render viewpoint
希望我的回答对您有所帮助。