js实现pdf对页面的打印

//-------------------------------点击打印的图标---------------------------------

<div class="dcsc"><img src="${rootUrl }images/pdf-icon.png" id="file_pdf_kong" class="center-block img-responsive" title="下载PDF"></div>

//------------------------------要打印的内容-------------------------------

<div class="right-box" id="content_kong" >

</div>

//----------------------------------------------引用的js-----------------------------------------------

<script type="text/javascript" src="${rootUrl}js/jspdf/html2canvas.js"></script>
<script type="text/javascript" src="${rootUrl}js/jspdf/jsPdf.debug.js"></script>
<script type="text/javascript" src="${rootUrl}js/jspdf/bluebird.js"></script>

<script type="text/javascript">
$("#file_pdf_kong").click(function() {
$('#content_kong').animate({
scrollTop : 0
});
//var p = $(this).data("name");
// console.log(p);

setTimeout('downloadPdf()', 500);

});
function downloadPdf() {
var filename = "projectImages.pdf";
// 将 id 为 content_kong 的 div 渲染成 canvas
html2canvas(document.getElementById("content_kong"), {
// 渲染完成时调用,获得 canvas
onrendered : function(canvas) {

// 从 canvas 提取图片数据

var imgData = canvas.toDataURL('image/jpeg', 1);

var canWidth = canvas.width;
var canHeight = canvas.height;

//一页pdf显示html页面生成的canvas高度;
var pageHeight = canWidth / 592.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = canHeight;
//pdf页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 595.28;
var imgHeight = 592.28 / canWidth * canHeight;
//l:横向, p:纵向
// var doc = new jsPDF("p", "mm", "a4");
var doc = new jsPDF("p", "pt", "a4");
//var doc = new jsPDF('', 'in', [(canWidth+10)/dpiX,(canHeight+10)/dpiY]);//设置PDF宽高为要显示的元素的宽高,将像素转化为英寸

//doc.addImage(imgData, 'JPEG', 0, 0,0,0);
//doc.addImage(imgData, 'JPEG', 0, 0,dpiX,dpiY);
if (leftHeight < pageHeight) {
doc.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
doc.addImage(pageData, 'JPEG', 0, position+0, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
doc.addPage();
};
};
}
doc.save(filename);
},
background : "#ffffff" //设置PDF背景色(默认透明,实际显示为黑色)
});
}
</script>

上一篇:iOS HTML 字符串中的图片 自适应大小


下一篇:react-native run-android Starting: Intent Error type 3 Error: Activity class does not exist