使用jspdf为pdf中的canvas标签赋予边距

时间:2017-12-08 10:02:12

标签: jquery html html5 canvas jspdf

我想给canvas标签留一个边距,这样它就不会与标题及其内容重叠。

<script>
 $('#cmd').click(function() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  var options = {
   pagesplit: true,
  };


  try {
   canvas.getContext('2d');
   var imgData = canvas.toDataURL("image/png", 1.0);
   pdf.addImage(imgData, 'JPEG', 5, 5);
  }
  catch(e) {
   alert("Error description: " + e.message);
 }
 source = $('#content')[0];
 specialElementHandlers = {
   'img' : function(element, renderer){
     return true;
   }
 };
 margins = {
   top: 0,
   bottom: 0,
   left: 25,
   width: 522
 };
 pdf.fromHTML(
   source, // HTML string or DOM elem ref.
   margins.left, // x coord
   margins.top, { // y coord
     'width': margins.width, // max width of content on PDF
     'elementHandlers': specialElementHandlers
   },enter code here

   function (dispose) {

     pdf.save('Test.pdf');
   }, margins);
 });
</script>

我希望画布标签(图片)没有重叠,页眉和页脚在每个pdf页面上都是永久性的。

2 个答案:

答案 0 :(得分:0)

<script>
 $('#cmd').click(function() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  var options = {
   pagesplit: true,
  };

   canvas.getContext('2d');
   var imgData = canvas.toDataURL("image/png", 1.0);
   pdf.addImage(imgData, 'JPEG', 0, 200);

 source = $('#content')[0];
 specialElementHandlers = {
   'img' : function(element, renderer){
     return true;
   }
 };
 margins = {
   top: 0,
   bottom: 0,
   left: 25,
   width: 522
 };
 pdf.fromHTML(
   source, // HTML string or DOM elem ref.
   margins.left, // x coord
   margins.top, { // y coord
     'width': margins.width, // max width of content on PDF
     'elementHandlers': specialElementHandlers
   },enter code here

   function (dispose) {

     pdf.save('Test.pdf');
   }, margins);
 });
</script>

答案 1 :(得分:0)

为图像设置边距的最佳方法是:

const pdf = new jsPdf({
        orientation: 'l',
        unit: 'pt',
        format: [canvas.width + 60, canvas.height + 160], // set surface larger according to desired margins
      });

      pdf.addImage(img, 'JPEG', 15, 40, canvas.width, canvas.height); // set margins there in image / 2 of margins above

通过这种方式,我们通过图像尺寸设置偏移量。

希望它可以帮助某人快速解决问题