1. 程式人生 > >js實現pdf對頁面的打印

js實現pdf對頁面的打印

點擊 dataurl png mage esp 數據 轉化 project java

//-------------------------------點擊打印的圖標---------------------------------

<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>

js實現pdf對頁面的打印