jsPDF icon indicating copy to clipboard operation
jsPDF copied to clipboard

Can I use html() multiple times in a PDF

Open CurryPaste opened this issue 5 years ago • 25 comments

I want to export a PDF in a function. At the same time, the content inside is generated by using .html() many times. If only once .html() there is no problem at all. But I found that I used it twice, and the content of the second time would not be generated in PDF. So I want to know,.html() Only once? this is code

async getPdfByJSPDF(){
      // console.log(this.$refs.ProjectDesignReport.changeHeightToA4(),"这里在执行子组件的改变高度函数")
      const { width:A4W, height: A4H } = {width:960,height:1362};
      const { unit, orientation, format } = {unit:"px", orientation:"p", format:[A4H,A4W]} // optionPDF(A4W,A4H);
      // console.log(unit, orientation, format,"unit, orientation, format")

      let thePDF = new JsPDF({ orientation, unit, format });
      thePDF = addSelfFont(thePDF, MyFont, "Alibaba-PuHuiTi-Regular-normal" ); // 增加字体

      const pdfBody = document.querySelector("#export");

      await thePDF.html(pdfBody,{x:0,y:0});
      await thePDF.html(pdfBody,{x:0,y:1362*3});

      const num = thePDF.internal.getNumberOfPages(); // 可以获得页数
      for(let i = 0; i < num; i+=1) {
        thePDF.setPage(i); 
        thePDF.setTextColor("red");
        thePDF.setFontSize(32);
        thePDF.text(`${thePDF.internal.getCurrentPageInfo().pageNumber  }/${  num}`,40,40, );
      }
      thePDF.save();
    }

By the way, we've dealt with this problem in other ways, so now we're just a little curious.

At the same time, if I continue to use html() in html() callback, I can write the content into PDF, but in the way of covering the previous one.

version 2.3.0

CurryPaste avatar Jan 25 '21 05:01 CurryPaste

Can confirm. Calling html a second time has no effect.

HackbrettXXX avatar Jan 25 '21 09:01 HackbrettXXX

Yes, but if you call html again in the callback function, you can override the last time. That's more interesting 😀 So we finally adopted the window.print to deal with pdf

CurryPaste avatar Jan 27 '21 01:01 CurryPaste

Yeah, I thought I could use .addPage() after .html() and call .html() again to insert anoter DOM element into a new page. Turns out I can't. Is there a differrent way to go about doing this?

joanc-naia avatar Feb 24 '21 13:02 joanc-naia

Interesting. So then I'm stuck and wondering if someone can help: I have a document where I'd like to print html twice. Once at the following coordinates: {x: 15, y: 100} and the second time slightly lower (depending on the size of a table in between, generated with autotable), for example at {x: 15, y: 150}. I achieved this previously with the deprecated function fromHtml

How can I achieve this with the latest version of jspdf (v2.3.0) and the html function?

Another interesting, (maybe related?) issue is the font size of the html - I tried to use inline styling on the div that wraps the text with a fixed width (as described in #3088 ), and tried forcing the font-size. Regardless of what I enter though, I always get the same font size (nothing smaller).

I've attached an illustration of my current struggle. Here is my code snippet to generate the pdf,

document.html(
  `<div style="width: 180px !important; font-size: 14px; font-family: Arial, Helvetica, sans-serif; line-height: 1.2 !important;">${text}</div>`,
  {
    // eslint-disable-next-line object-shorthand, func-names
    callback: function () {
      doc.save();
    },
    x,
    y,
  }
);

CleanShot 2021-03-21 at 17 11 42@2x

everttrollip avatar Mar 21 '21 15:03 everttrollip

This is a duplicate of #2899, which contains two more examples to reproduce this bug.

I'd be willing to create a pull request with a fix. Any clue where I should look first would be appreciated. It seems html2canvas is executed correctly for subsequent html() calls, but the result does not end up in the pdf document.

ahocevar avatar Jul 02 '21 18:07 ahocevar

Some workarounds:

  • Use html2canvas directly
  • Use html-to-image if your users can use Chrome/Firefox(Safari is not well supported). This library is using SVG and I personally think it's better than html2canvas.

helsonxiao avatar Jul 03 '21 03:07 helsonxiao

Using html2canvas directly has the disadvantage that text will be converted to an image, whereas using doc.html() preserves text as text. And html-to-image is not an option because of the Safari limitations.

ahocevar avatar Jul 03 '21 10:07 ahocevar

Using html2canvas directly has the disadvantage that text will be converted to an image, whereas using doc.html() preserves text as text. And html-to-image is not an option because of the Safari limitations.

Yes, that's why they are workarounds.

BTW: If server side rendering is activated, HTML element transformed by html-to-image will be more accurate than html2canvas does(css shadow, position, ... or any other things Canvas can't do). I'm now using both html-to-image & html2canvas with jsPDF to create complicate worksheets for user. And I do hope the text could be copied. :)

helsonxiao avatar Jul 04 '21 10:07 helsonxiao

@helsonxiao that is a very interesting workaround suggestion. The goal of my PDF to create not too complicated reports with a few charts and some minimal text. Copying text is not a "requirement".

So this might be worth looking into...

Would you be able to share some examples how you are using html-to-image with jsPDF to create a pdf?

everttrollip avatar Jul 04 '21 12:07 everttrollip

@helsonxiao that is a very interesting workaround suggestion. The goal of my PDF to create not too complicated reports with a few charts and some minimal text. Copying text is not a "requirement".

So this might be worth looking into...

Would you be able to share some examples how you are using html-to-image with jsPDF to create a pdf?

Sure! Just turn html into image then call addImage API.

import html2canvas from 'html2canvas';
import * as htmlToImage from 'html-to-image';

// using svg
image = await htmlToImage.toPng(element, {
  // cacheBust: true,
  // fontEmbedCss,
});

// or canvas
image = await html2canvas(element, {
  // useCORS: true,
});

doc.addImage(
  image,
  imgX,
  imgY,
  scaledImgW,
  scaledImgH,
  undefined,
  comporession,
);

helsonxiao avatar Jul 06 '21 02:07 helsonxiao

Closing this in favor of #2899.

HackbrettXXX avatar Jul 13 '21 09:07 HackbrettXXX

Hey hi, Try with Timeout functions with 5 seconds delay. It works great!

const createPDF = async (index) => { let pdf = new jsPDF("portrait", "pt", "a4"); let data = await document.querySelector(#reportCardPdf_${index}); pdf.html(data).then(() => { pdf.save(ExamReportCard_${index + 1}.pdf); } ); };

const handlePdfGeneration = () => {
    const delay = 2; //please add delay minimum of 2 seconds to avoid white pages in pdf
    const limit = state.data.length;
    let i = 0;
    const limitedInterval = setInterval(() => {
        createPDF(i++);
        if (i > limit) {
            clearInterval(limitedInterval);
        }
    }, delay * 1000);
}

Sherline1998 avatar Sep 30 '22 04:09 Sherline1998

Didnt work for me :(

kito-arch avatar Oct 16 '22 11:10 kito-arch

I've found a workaround for generating multipage PDF using .html() method,

const doc = new jsPDF("p", "pt", "a4");   
let pageHeight = doc.internal.pageSize.getHeight();
   doc.html(document.getElementById("Page1"), {
      callback: function (pdf) {
        pdf.addPage("a4", "l");
        pdf.html(document.getElementById("Page2"), {
          callback: function (pdf2) {
            pdf2.addPage("a4", "l");
            pdf2.html(document.getElementById("Page3"), {
              callback: function (pdf3) {
                pdf3.save("multipage.pdf")
              },
              x: 0,
              y: 2 * pageHeight,
            });
          },
          x: 0,
          y: pageHeight,
        });
      },
      x: 0,
      y: 0,
    });

prasheel888 avatar Nov 17 '22 08:11 prasheel888

I've tried your solution and it renders only the first element(Page 1). The rest of the pages (with elements Page2 and Page3) are empty. Can you maybe provide a JSFiddle working example? Thanks.

adidahl avatar Nov 17 '22 15:11 adidahl

I've tried your solution and it renders only the first element(Page 1). The rest of the pages (with elements Page2 and Page3) are empty. Can you maybe provide a JSFiddle working example? Thanks.

U can try this: https://codesandbox.io/s/a11y-tabs-forked-rr814c?file=/src/App.js

prasheel888 avatar Nov 18 '22 04:11 prasheel888

I found an answer to this question (refrencing)

Just use await and make sure to return doc inside the callback

something like this

var doc = new jspdf.jsPDF({
  orientation: 'p',
  unit: 'pt',
  format: 'letter'
});


var field = "<b>html test </b>";
doc.text(10, 10, "test");
//add first html
await doc.html(field, {
  callback: function (doc) {
    return doc;
  },
  width: 210,
  windowWidth: 210, 
      html2canvas: {
          backgroundColor: 'lightyellow',
          width: 210, 
          height: 150
      },
      backgroundColor: 'lightblue', 
  x: 10,
  y: 50,
  autoPaging: 'text'
});
window.open(doc.output('bloburl'));

now you can call doc.html as many times as you want for that same document

bakuur avatar Nov 28 '22 01:11 bakuur

I've found a workaround for generating multipage PDF using .html() method,

const doc = new jsPDF("p", "pt", "a4");   
let pageHeight = doc.internal.pageSize.getHeight();
   doc.html(document.getElementById("Page1"), {
      callback: function (pdf) {
        pdf.addPage("a4", "l");
        pdf.html(document.getElementById("Page2"), {
          callback: function (pdf2) {
            pdf2.addPage("a4", "l");
            pdf2.html(document.getElementById("Page3"), {
              callback: function (pdf3) {
                pdf3.save("multipage.pdf")
              },
              x: 0,
              y: 2 * pageHeight,
            });
          },
          x: 0,
          y: pageHeight,
        });
      },
      x: 0,
      y: 0,
    });

@prasheel888 Thank you for this. Working as expected.

gitalvininfo avatar Dec 28 '22 07:12 gitalvininfo

I've found a workaround for generating multipage PDF using .html() method,

const doc = new jsPDF("p", "pt", "a4");   
let pageHeight = doc.internal.pageSize.getHeight();
   doc.html(document.getElementById("Page1"), {
      callback: function (pdf) {
        pdf.addPage("a4", "l");
        pdf.html(document.getElementById("Page2"), {
          callback: function (pdf2) {
            pdf2.addPage("a4", "l");
            pdf2.html(document.getElementById("Page3"), {
              callback: function (pdf3) {
                pdf3.save("multipage.pdf")
              },
              x: 0,
              y: 2 * pageHeight,
            });
          },
          x: 0,
          y: pageHeight,
        });
      },
      x: 0,
      y: 0,
    });

Thank You mate!

Samik-Pandit avatar Feb 08 '23 08:02 Samik-Pandit

I've found a workaround for generating multipage PDF using .html() method,

const doc = new jsPDF("p", "pt", "a4");   
let pageHeight = doc.internal.pageSize.getHeight();
   doc.html(document.getElementById("Page1"), {
      callback: function (pdf) {
        pdf.addPage("a4", "l");
        pdf.html(document.getElementById("Page2"), {
          callback: function (pdf2) {
            pdf2.addPage("a4", "l");
            pdf2.html(document.getElementById("Page3"), {
              callback: function (pdf3) {
                pdf3.save("multipage.pdf")
              },
              x: 0,
              y: 2 * pageHeight,
            });
          },
          x: 0,
          y: pageHeight,
        });
      },
      x: 0,
      y: 0,
    });

saved me Thanks

tthomaz avatar May 05 '23 16:05 tthomaz