简体   繁体   English

jsPDF 如何将图像设置为适合各种页面大小的高度和宽度到单个 PDF 文件

[英]jsPDF How to set images to fit with various page size height & width to a single PDF file

I have multiple types of data images of different sizes (height & width) that need to be converted to PDF using jspdf,html2canvas but I have trouble when I download pdf its works for small name user data but when I get a big name or other data then in right side it's got increase and go out of the page like distorted it's working if the user name is small and less data but when data get its go out of the page from X side I tried scrollX: 0 and scrollX: -window.scrollX both but not getting in proper see the image below the data number getting out and how can I improve PDF quality.我有多种不同大小(高度和宽度)的数据图像需要使用 jspdf,html2canvas 转换为 PDF 但是当我下载 pdf 时遇到问题数据然后在右侧它会增加,并且 go 会像扭曲一样从页面中移出,如果用户名很小且数据较少,但是当数据从 X 侧将其 go 移出页面时,我尝试了 scrollX: 0scrollX: -window .scrollX两者都没有正确进入,请参阅下面的图像数据编号退出以及如何提高 PDF 质量。 ? ?

export const pdfDownloadHandler = (name, div, user) => {
  const input = document.getElementById(div);
  var clientHeight = input.clientHeight;
  var clientWidth = input.clientWidth;

  html2canvas(input,{
    scrollX: 0,
    scrollY: 0,
  }).then((canvas) => {
    const imgData = canvas.toDataURL('image/jpeg');
    const pdf = new jsPDF('p', 'px', [clientWidth, clientHeight]);
    console.log('@PDF: ', pdf, user);
    var width = pdf.internal.pageSize.getWidth();
    var height = pdf.internal.pageSize.getHeight();

    function loadImage(url) {
      return new Promise((resolve) => {
        let img = new Image();
        img.onload = () => resolve(img);
        img.src = url;
      })
    }


    pdf.addImage(imgData, 'jpeg', 0, 0, width, height);
    pdf.text(`Reviewed By Analyst : ${user} on ${new Date().toLocaleString()}`, 450, 35);
    pdf.setFontSize(16);
    pdf.text("Powered By ", width - 500, height - 20)
    loadImage(solytics).then((logo1) => {
      pdf.addImage(logo1, "png", width - 425, height - 35, 90, 25);

    });

    loadImage(banklogo).then((logo) => {
      pdf.addImage(logo, "png", 15, 0, 85, 55);

      pdf.save(`${name}.pdf`);

    });


  });
};

this is possible but a bit tricky, you can substract the Y coordinate by user length.这是可能的,但有点棘手,您可以通过user长度减去 Y 坐标。 For the example if I set the font size to 12:例如,如果我将字体大小设置为 12:

const user="ihsan fajar ramadhan"
doc.setFontSize(12);
doc.text(`Reviewed By Analyst : ${user} on ${new Date().toLocaleString()}`, 105 - user.length*2.1, 25);

the Y coordinate of the text will follow the user length so it will not go out of the page.文本的 Y 坐标将跟随user长度,因此它不会 go 超出页面。 but the equation is not perfect in that example, I suggest you to make a graph (with excel or something) and generate the trendline to get the most desirable equation.但是该示例中的方程式并不完美,我建议您制作一个图表(使用 excel 或其他东西)并生成趋势线以获得最理想的方程式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM