如何使用jsPDF设置图像以适合页面的宽度?

时间:2016-04-07 09:32:29

标签: javascript jspdf

有什么方法可以解决这个问题吗? 我试图以mm为单位设置宽度和高度。如何将其设置为全宽?

15 个答案:

答案 0 :(得分:39)

您可以获得PDF文档的宽度和高度,如下所示

var doc = new jsPDF("p", "mm", "a4");

var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();

然后,您可以使用图像的宽度和高度来适合整个PDF文档。

var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJ......';

doc.addImage(imgData, 'JPEG', 0, 0, width, height);

确保您的图像具有与PDF文档相同的大小(分辨率)。否则它会看起来扭曲(拉伸)。

如果您想将px转换为mm,请使用此链接http://www.endmemo.com/sconvert/millimeterpixel.php

答案 1 :(得分:10)

commit以来的API发生了更改,使用的是1.4.1版

var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();

答案 2 :(得分:8)

我的回答是针对您要求的更具体的案例,但我认为可以从中得出一些想法以更广泛地应用。另外,我会发布此评论作为对Purushoth答案(我的基础)的评论,如果我能做的话。

好的,我的问题是如何在不丢失宽高比的情况下将网页放入pdf文档中。我使用jsPDF与html2canvas结合使用,我计算了div的宽度和高度的比率。我将相同的比例应用于pdf文档,页面完美地适合页面而没有任何失真。

var divHeight = $('#div_id').height();
var divWidth = $('#div_id').width();
var ratio = divHeight / divWidth;
html2canvas(document.getElementById("div_id"), {
     height: divHeight,
     width: divWidth,
     onrendered: function(canvas) {
          var image = canvas.toDataURL("image/jpeg");
          var doc = new jsPDF(); // using defaults: orientation=portrait, unit=mm, size=A4
          var width = doc.internal.pageSize.getWidth();    
          var height = doc.internal.pageSize.getHeight();
          height = ratio * width;
          doc.addImage(image, 'JPEG', 0, 0, width-20, height-10);
          doc.save('myPage.pdf'); //Download the rendered PDF.
     }
});

答案 3 :(得分:5)

我今天早上在尝试使用html2canvas时发现了这一点。虽然这并不包括打印多个页面的规定,但它会将图像缩放到页面宽度,并根据调整后的宽度重新调整高度:

html2canvas(document.getElementById('testdiv')).then(function(canvas){
        var wid: number
        var hgt: number
        var img = canvas.toDataURL("image/png", wid = canvas.width, hgt = canvas.height);
        var hratio = hgt/wid
        var doc = new jsPDF('p','pt','a4');
        var width = doc.internal.pageSize.width;    
        var height = width * hratio
        doc.addImage(img,'JPEG',20,20, width, height);
        doc.save('Test.pdf');
    });

答案 4 :(得分:3)

如果希望动态尺寸的图像尽可能自动地填充页面并仍保持图像的宽度/高度比,则可以执行以下操作:

let width = doc.internal.pageSize.getWidth()
let height = doc.internal.pageSize.getHeight()

let widthRatio = width / canvas.width
let heightRatio = height / canvas.height

let ratio = widthRatio > heightRatio ? heightRatio : widthRatio

doc.addImage(
  canvas.toDataURL('image/jpeg', 1.0),
  'JPEG',
  0,
  0,
  canvas.width * ratio,
  canvas.height * ratio,
)

答案 5 :(得分:2)

这就是我在Reactjs中实现的方式。

主要问题是比例和比例如果您执行一个window.devicePixelRatio快速设置,则默认值为2,这会导致出现一半图像问题。

const printDocument = () => {
  const input = document.getElementById('divToPrint');
  const divHeight = input.clientHeight
  const divWidth = input.clientWidth
  const ratio = divHeight / divWidth;

  html2canvas(input, { scale: '1' }).then((canvas) => {
    const imgData = canvas.toDataURL('image/jpeg');
    const pdfDOC = new JSPDF("l", "mm", "a0"); //  use a4 for smaller page

    const width = pdfDOC.internal.pageSize.getWidth();
    let height = pdfDOC.internal.pageSize.getHeight();
    height = ratio * width;

    pdfDOC.addImage(imgData, 'JPEG', 0, 0, width - 20, height - 10);
    pdfDOC.save('summary.pdf');   //Download the rendered PDF.
  })
}

答案 6 :(得分:2)

我的解决方案是根据 pdf 方向和图像大小检查需要应用的比例(高度或宽度)。注意:如果不需要边距,请将边距设置为 0。

   const imgData = canvas.toDataURL("image/jpeg");

   const pdf = new jsPDF({
       orientation: "portrait", // landscape or portrait
       unit: "mm",
       format: "a4",
   });
   const imgProps = pdf.getImageProperties(imgData);
   const margin = 0.1;

   const pdfWidth = pdf.internal.pageSize.width * (1 - margin);
   const pdfHeight = pdf.internal.pageSize.height * (1 - margin);

   const x = pdf.internal.pageSize.width * (margin / 2);
   const y = pdf.internal.pageSize.height * (margin / 2);

   const widthRatio = pdfWidth / imgProps.width;
   const heightRatio = pdfHeight / imgProps.height;
   const ratio = Math.min(widthRatio, heightRatio);
   
   const w = imgProps.width * ratio;
   const h = imgProps.height * ratio;

   pdf.addImage(imgData, "JPEG", x, y, w, h);

答案 7 :(得分:1)

我面临同样的问题,但我解决了使用此代码

html2canvas(body,{
                onrendered:function(canvas){
                    var pdf=new jsPDF("p", "mm", "a4");
                    var width = pdf.internal.pageSize.getWidth();    
                    var height = pdf.internal.pageSize.getHeight();
                    pdf.addImage(canvas, 'JPEG', 0, 0,width,height);
                    pdf.save('test11.pdf');
                }
            }) 

答案 8 :(得分:0)

更好的解决方案是使用图像的宽高比设置文档宽度/高度。



var ExportModule = {
  // Member method to convert pixels to mm.
  pxTomm: function(px) {
    return Math.floor(px / $('#my_mm').height());
  },
  ExportToPDF: function() {
    var myCanvas = document.getElementById("exportToPDF");

    html2canvas(myCanvas, {
      onrendered: function(canvas) {
        var imgData = canvas.toDataURL(
          'image/jpeg', 1.0);
        //Get the original size of canvas/image
        var img_w = canvas.width;
        var img_h = canvas.height;

        //Convert to mm
        var doc_w = ExportModule.pxTomm(img_w);
        var doc_h = ExportModule.pxTomm(img_h);
        //Set doc size
        var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);

        //set image height similar to doc size
        doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);
        var currentTime = new Date();
        doc.save('Dashboard_' + currentTime + '.pdf');

      }
    });
  },
}

<script src="Scripts/html2canvas.js"></script>
<script src="Scripts/jsPDF/jsPDF.js"></script>
<script src="Scripts/jsPDF/plugins/canvas.js"></script>
<script src="Scripts/jsPDF/plugins/addimage.js"></script>
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>
<div id="my_mm" style="height: 1mm; display: none"></div>

<div id="exportToPDF">
  Your html here.
</div>

<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
&#13;
&#13;
&#13;

答案 9 :(得分:0)

如果只有一张图像,则很容易适合页面。更具挑战性的任务是使各种大小的图像适合pdf文件。存档的关键是计算图像的纵横比和页面的相对宽度/高度比。以下代码是我用来在线将多个图像转换为PDF文件的代码。它将根据图像/页面的方向旋转图像并设置适当的边距。我的项目使用在线src图像。您应该能够进行修改以满足您的需求。

对于图像旋转,如果旋转后看到空白页,则可能只是图像超出范围。有关详情,请参见此answer

function exportPdf(urls) {
    let pdf = new jsPDF('l', 'mm', 'a4');
    const pageWidth = pdf.internal.pageSize.getWidth();
    const pageHeight = pdf.internal.pageSize.getHeight();
    const pageRatio = pageWidth / pageHeight;

    for (let i = 0; i < urls.length; i++) {
        let img = new Image();
        img.src = urls[i];
        img.onload = function () {
            const imgWidth = this.width;
            const imgHeight = this.height;
            const imgRatio = imgWidth / imgHeight;
            if (i > 0) { pdf.addPage(); }
            pdf.setPage(i + 1);
            if (imgRatio >= 1) {
                const wc = imgWidth / pageWidth;
                if (imgRatio >= pageRatio) {
                    pdf.addImage(img, 'JPEG', 0, (pageHeight - imgHeight / wc) / 2, pageWidth, imgHeight / wc, null, 'NONE');
                }
                else {
                    const pi = pageRatio / imgRatio;
                    pdf.addImage(img, 'JPEG', (pageWidth - pageWidth / pi) / 2, 0, pageWidth / pi, (imgHeight / pi) / wc, null, 'NONE');
                }
            }
            else {
                const wc = imgWidth / pageHeight;
                if (1 / imgRatio > pageRatio) {
                    const ip = (1 / imgRatio) / pageRatio;
                    const margin = (pageHeight - ((imgHeight / ip) / wc)) / 4;
                    pdf.addImage(img, 'JPEG', (pageWidth - (imgHeight / ip) / wc) / 2, -(((imgHeight / ip) / wc) + margin), pageHeight / ip, (imgHeight / ip) / wc, null, 'NONE', -90);
                }
                else {

                    pdf.addImage(img, 'JPEG', (pageWidth - imgHeight / wc) / 2, -(imgHeight / wc), pageHeight, imgHeight / wc, null, 'NONE', -90);
                }
            }
            if (i == urls.length - 1) {
                pdf.save('Photo.pdf');
            }
        }
    }
}
  

如果很难做到这一点,也可以使用.addPage([imgWidth, imgHeight]),它更简单。该方法的缺点是第一页由new jsPDF()固定。有关详细信息,请参见this answer

答案 10 :(得分:0)

如果您需要获取宽度100%的PDF文件和自动高度,则可以使用“ getImageProperties”属性。

html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF({
          orientation: 'landscape',
        });
        const imgProps= pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save('download.pdf');
      });

答案 11 :(得分:0)

所有屏幕尺寸和动态方向的解决方案:

import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

export default async function downloadComponentInPDF(Component: HTMLElement) {
  await html2canvas(Component).then((canvas) => {
    const componentWidth = Component.offsetWidth
    const componentHeight = Component.offsetHeight

    const orientation = componentWidth >= componentHeight ? 'l' : 'p'

    const imgData = canvas.toDataURL('image/png')
    const pdf = new jsPDF({
    orientation,
    unit: 'px'
  })

    pdf.internal.pageSize.width = componentWidth
    pdf.internal.pageSize.height = componentHeight

    pdf.addImage(imgData, 'PNG', 0, 0, componentWidth, componentHeight)
    pdf.save('download.pdf')
  })
}

答案 12 :(得分:0)

那里有很多带有 .addImage 的解决方案,我尝试了其中的很多,但没有任何效果。 所以我找到了 .html() 函数,然后尝试了 html2canvas-scale-option。 此解决方案不是通用解决方案,您必须调整比例以使其适合您的 pdf,但这是唯一对我有用的解决方案。

// Global
var todayMonth = getMonthToday();
var NEWL = String.fromCharCode(10); // newline

var accId = "<Spreadsheet_ID"; // Accounting Spreadsheet
var acc = SpreadsheetApp.openById(accId);
var sAcc = acc.getSheetByName(todayMonth);
var sBot = acc.getSheetByName("Bot");

// @usernames who have access to the bot
var andreyChatId = sBot.getRange("B2").getValue();
var donyChatId = sBot.getRange("B3").getValue();

// chat_id who have access to the bot
var logins = ["99587408", "155390785"];

// Get current month
function getMonthToday() {
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var todayDate = new Date();
  var todayMonth = months[todayDate.getMonth()];

  return todayMonth;
}

答案 13 :(得分:0)

convertPhotoImageToPdf(imgPath){
   var doc = new jsPDF(undefined, null, null, true);
   var imgData = 'data:image/jpeg;base64,'+ imgPath;
   doc.addImage(imgData, 'JPEG',10,10,0,0,null,'FAST',0);
   //if want add one page 
   //doc.addPage()
   doc.save('testPdf.pdf')
}

答案 14 :(得分:-1)

        var width = doc.internal.pageSize.width;    
        var height = doc.internal.pageSize.height;