[英]Html, css, img(svg) to pdf using js jspdf
i want convert a div to pdf and download it.我想将 div 转换为 pdf 并下载它。
I am using a svg image file which streches when i download it.我正在使用 svg 图像文件,该文件在我下载时会拉伸。
This code is working well in safari browser.此代码在 safari 浏览器中运行良好。 streches image in chrome and remove pictures in firefox Text is generated dynamically.
在 chrome 中拉伸图像并在 firefox 中删除图片 文本是动态生成的。
this is the code i am using这是我正在使用的代码
JS: JS:
<script>
// Define variables
var
form = $('#certificateDiv'),
cache_width = form.width(),
cache_height = form.height(),
a4 = [595.28, 841.89]; // for a5 size paper width and height
//create pdf
function createPDF() {
$('#exportBtn').addClass("hide");
//form.removeClass('back-repeat');
if (cache_height > 600)
cache_height = 600;
// Call create canvas function
getCanvas().then(function (canvas) {
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit: 'px',
format: 'a4'
});
doc.addImage(img, 'JPEG', 10, 10, 430, cache_height);
var FileName = '@ViewBag.ModuleName';
doc.save(FileName+'.pdf');
form.width(cache_width);
});
$('#exportBtn').removeClass("hide");
//form.addClass('back-repeat');
}
// create canvas object
function getCanvas() {
form.width((a4[0] * 1.2)).css('max-width', 'none');
return html2canvas(form, {
imageTimeout: 3000,
removeContainer: true
});
}
</script>
Asp Code: ASP代码:
<div id="OuterCertificate">
<div id="certificateDiv" class="certificate-container-span">
<img src="@CertificateURL" class="certificate-image">
<div class="certificate_inner">
<div class="certificate-title">@Model.Title</div>
<div class="certificate-message">
@Html.Raw(Model.Message)
</div>
</div>
<a id="exportBtn" class="btn btn-sm btn-default no-print" onclick="createPDF();"><i class="filetypes filetypes-pdf"></i>Export</a>
</div>
</div>
And this is how it looks like after downloading这是下载后的样子
You should use a4 size declared in variable a4 instead of 430 and cache_height in doc.addImage您应该使用变量 a4 中声明的 a4 大小而不是 doc.addImage 中的 430 和 cache_height
Your image is looking stretched because of incorrect width and height.由于宽度和高度不正确,您的图像看起来被拉伸了。
try use canvas at this:尝试在此使用画布:
html2canvas(form,
{
height: window.outerHeight + window.innerHeight,
width: window.outerWidth + window.innerWidth,
windowHeight: window.outerHeight + window.innerHeight,
windowWidth: window.outerWidth + window.innerWidth,
scrollX: 0,
scrollY: 0
}
).then(canvas => {
var pdf = new jsPDF("l", "mm", "a4");
var imgData = canvas.toDataURL('image/png');
var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();
pdf.addImage(imgData, 'PNG', 0, 0, width, height);
pdf.save('fulljspdfdiv.pdf');
});
Good luck祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.