您的位置:首页 > Web前端 > JavaScript

jspdf指定部分转PDF并进行下载(支持中文)

2018-01-22 16:46 1271 查看
<script src="${ctx}/front/jsPDF-master/libs/html2canvas/dist/html2canvas.js"></script>
<script src="${ctx}/front/jsPDF-master/dist/jspdf.min.js"></script>
<script type="text/javascript">
function download1(){
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE=window.ActiveXObject || "ActiveXObject" in window
if (isIE){
alert('抱歉,暂不支持IE浏览器下载!');
return;
}
$('#container')[0].scrollIntoView(true);//防止生成的PDF只能生成一半内容
html2canvas(document.getElementById("container"), {
onrendered:function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 555.28;
var imgHeight = 555.28/contentWidth * contentHeight;

var pageData = canvas.toDataURL('image/jpeg', 1.0);

var pdf = new jsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}

pdf.save('登记表.pdf');
}
})
}

function download2(){
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE=window.ActiveXObject || "ActiveXObject" in window
if (isIE){
alert('抱歉,暂不支持IE浏览器下载!');
return;
}
$('#container2')[0].scrollIntoView(true);//防止生成的PDF只能生成一半内容
html2canvas(document.getElementById("container2"), {
onrendered:function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 555.28;
var imgHeight = 555.28/contentWidth * contentHeight;

var pageData = canvas.toDataURL('image/jpeg', 1.0);

var pdf = new jsPDF('', 'pt', 'a4');

4000
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}

pdf.save('附表.pdf');
}
})
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: