我一直在研究在客户端将 HTML 页面转换为 PDF。我发现了一个使用 Javascript 的方法,使用 html2canvas 解析 DOM 并计算应用的样式,并使用 jsPDF 创建 PDF。链接到我的页面 - http://www.choosenj.com/html-to-pdf/
我正在努力处理我需要解决的几个问题:
-
Canvased 图像将整个页面渲染为单个 PDF,有没有办法将长图像分割成多页 PDF?
-
当前面板在向下滚动时加载,有没有办法在单击“创建 PDF 按钮”时加载整个页面?
-
如果我只想绘制选中复选框的面板,我将如何编辑我的 JS?
这里我的代码如下(注意:大多数包括 html2canvas 和 jsPDF javascript 库):
// Html to PDF
$(window).load(function(){
var
form = $('#Content'),
cache_width = form.width(),
a4 =[ 850, 2000]; // for a4 size paper width and height
$('#create_pdf').on('click',function(){
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF(){
getCanvas().then(function(canvas){
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit:'px',
format:'a4'
});
doc.addImage(img, 'JPEG', 0, 0, 180, 630);
doc.save('choosenj.pdf');
form.width(cache_width);
});
}
// create canvas object
function getCanvas(){
form.width(cache_width).css('max-width','none');
return html2canvas(form,{
imageTimeout:2000,
removeContainer:true
});
}
}());
<!-- #Content -->
<div id="Content">
<div class="content_wrapper clearfix">
<!-- .Main Content -->
<div class="sections_group">
<div class="entry-content" itemprop="mainContentOfPage">
<div style="margin: 10px 0;"><a id="create_pdf" class="vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-square vc_btn3-style-flat vc_btn3-color-green" style="margin:0 20px;cursor:pointer;color:#fff;font-family: 'FranklinGothicStd-ExtraCond', Arial, sans-serif !important;text-transform: uppercase !important;">Create PDF</a> </div>
<?php
while ( have_posts() ){
the_post(); // Post Loop
}
?>
</div>
<!-- Contact Section-->
<?php wp_reset_postdata(); ?>
<?php get_template_part('contact-us') ?>
</div>
</div>
</div>
任何见解将不胜感激,
克里斯 G