Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsPDF, Add text after another dynamic text

I need to create a PDF with dynamic fields. Sometimes a text can be 2 lines, sometimes 3 lines. How can I do to insert directly after the first dynamic text another element without hardcode a static Y coordinate ?

This is my code :

const pdf = new window.jspdf.jsPDF();

pdf.text(`DYNAMIC TEXT THAT CAN HAVE 1 TO X LINES`, 5, 10);

//The next text which must be under the first, but without hardcode Y:20, because sometime, this is too much
pdf.text(`DYNAMIC TEXT THAT CAN HAVE 1 TO X LINES`, 5, 20);

I'm using jsPDF 2.3.0 from CDN link

Thank You !

like image 941
Beweelam Avatar asked Nov 14 '25 12:11

Beweelam


1 Answers

I also had the same issue, couldn't find any official solution so used other methods for this. Here is my way of solving it. I'm splitting the text to the size I need, then I'm getting its height. Hope it helps

  const start = 20;
  let nextY = 60;
  const textOne= `This might change: ${myTextOne}`;
  nextY = addText(doc, textOne, nextY);
  
  const textTwo = `This might change: ${myTextTwo}`;
  nextY = addText(doc, textTwo, nextY);

  function addText(doc, text, nextY) {
  const locationsText = text;
  doc.text(locationsText, start, nextY, { maxWidth: 180 });
  nextY += roundUp(doc.getTextDimensions(doc.splitTextToSize(locationsText, 
  180)).h) + 5;
  return nextY;
  }
like image 68
Biloliddin Makhmudov Avatar answered Nov 17 '25 10:11

Biloliddin Makhmudov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!