1

I tried to put a text from a JSON together in JSPDF with a "Lable" which is supposed to be BOLD and a comment which should be written normally.

so something like this:

LABLE:COMENTAR

LABLE2:COMENTAR2

LABLE3:COMENTAR3

I have tried following:

var doc = new jsPDF();
doc.setFont("Helvetica");
doc.setFontSize(25);

var comDim= doc.getTextDimensions(coment.coment);
var labledim = doc.getTextDimensions(coment.lable);

doc.setFontStyle('bold');
doc.text(21, currentDistance, '- '+coment.lable+':');
doc.setFontStyle('normal');
doc.text(labledim.w, currentDistance, coment.coment);

doc.save('Storecheck.pdf');

which brings me the following result:

Result

But the gaps between the label and the comment are too big and unfortunately, the text is not wrapped. Which is really bad because I can't say how long the text is.

I would be very grateful for a hint or approach, maybe there is an example somewhere.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Frieder Knabe
  • 53
  • 2
  • 7

1 Answers1

1

I'm not sure why there is a gap between the "label" and the "comment". What texts are stored in coment? Might they be padded with whitespaces or tabs? In that case you might want to .trim() your texts before adding them to the pdf (here).

For word wrapping you can use doc.splitTextToSize before passing the text itself to doc.text. Have a look at this question.

I made a fiddle for you: http://jsfiddle.net/tbrpo30f/

Fabian Scheidt
  • 372
  • 3
  • 10
  • Hi Fabian, the **coments** are just simple texts with no Tab or whitespaces :-( – Frieder Knabe Sep 02 '18 at 16:18
  • Could you try to create a fiddle or provide some more of your code? My example works fine so the issue has to be somewhere else... – Fabian Scheidt Sep 02 '18 at 16:58
  • hi fabian Basically, I have something like that: https://jsfiddle.net/frief/L57fh9bz/16/#&togetherjs=5ih6LpTIHK – Frieder Knabe Sep 03 '18 at 08:59
  • For some reason, the Labledim.w is wrong it is 140 but sould be 76 – Frieder Knabe Sep 03 '18 at 09:23
  • According to this post the result highly depends on the unit system you are using: https://stackoverflow.com/a/25675981/4528518. I worked a bit on your fiddle and got slightly better results but I think you are better off if you use some build-in features like `fromHTML` or tables... https://stackoverflow.com/a/25675981/4528518 – Fabian Scheidt Sep 03 '18 at 12:11
  • var htmlString ="- "+lable+" "+ coment.coment; doc.fromHTML(htmlString,21,currentDistance-7,{}); with fromHTML I have the problem that neither the font nor the line break works :-( – Frieder Knabe Sep 03 '18 at 14:04
  • The formulas from the last post are doing relatively well.. I still have small gaps but it works. I would wish that it is easier – Frieder Knabe Sep 03 '18 at 15:06
  • @FabianScheidt thanks for the fiddle :) helped me big time 3 years later while pulling an all nighter – Padua Dec 13 '21 at 22:29