jspdf的使用,js 根据base64字符串生成pdf

<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script src="https://cdn.bootcss.com/jspdf/1.3.4/jspdf.debug.js"></script>

img.onload = function(){
  //使用h5画布重新画出返回的base64图片,直接写进pdf会失真和不完整,估计是格式有问题
let can = $('<canvas width="' + img.naturalWidth+'" height="'+ img.naturalHeight
+'"></canvas>').get(0);
can.getContext("2d").drawImage(img,0,0);
let canvasBase64 = can.toDataURL('image/jpeg',2.0);
var pdf = new jspdf('p', 'pt', 'a4'); //默认是a4纸大小,试了很多种办法不能调节大小
   pdf.addPage([600,420]); //添加新的指定大小的页面
   pdf.deletePage(1); //删除空白的第一页,就可以得到指定大小的pdf
  //l:横向, p:纵向
  //var doc = new jsPDF('p', 'mm', [290, 210]);
var contentWidth = can.width;
var contentHeight = can.height;

//一页pdf显示html页面生成的canvas高度;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 595.28;
var imgHeight = 592.28/contentWidth * contentHeight;
  //x位置,y位置,宽,高
pdf.addImage(canvasBase64, 'jpeg', 0, 0, 592.28, 592.28/contentWidth * contentHeight);
pdf.save('test.pdf');
};
原文地址:https://www.cnblogs.com/shihx/p/13162446.html