I'm facing some issues while creating tables in jspdf. I could not find any good related docs, but if anyone knows one, please share.
I found two related methods:
1) doc.getStringUnitWidth(text, {widths:12,kerning:2});
2) doc.getTextDimensions(text)
What does widths and kerning mean in the first method? What should I provide? Which method should I use to get the width and height of text?
My goal is to solve some issues related to overlapping cell content, wrapping of text and text overflow relative to the page width.
You might want to look at the AutoTable plugin for generating tables with jsPDF. I found the built in plugin hard to work with and isn't documented at all.
The best way I have found to calculate the width is simply doing this:
If you really need to calculate the height
getDimensions()
might be an option. However, it is not pixel perfect and looking at the source I doubt it will work for anything butpt
. Here is an example:I found this question looking for answers to a similar issue. Unfortunately, the answers provided did not solve my problem, but I figure what I did find out may help other people stumbling onto this question.
As already mentioned, the .getStringUnitWidth(text) will return the width of a string (in pt). I could never find any explanation of the options like "kerning" or "widths" in the documentation or in the actual .js file. I also noticed with my own usage that this method was actually underestimating widths by ~10%, which started to add up very quickly. Finally, this did not account for fonts that were bold, italicized or bold and italicized.
Since I required a high level of accuracy, I ended up calculating the width of each character on my own and using this to calculate a string width (by totaling the width of each character in a string).
Below are the font widths at size 1 (in pt) for each character accepted by jsPDF in the 3 default fonts (helvetica, times, courier):
Once you have determined the width of your string with the above table you need to convert the answer to your desired unit of measurement.
The only caveat to using the above I could think of was if your output pdf was making use of kerning pairs. My output files did not appear to be using kerning pairs, so I did not explore the issue further. If for some reason this is an issue for you, you would need to adjust your widths slightly for each kerning pair as it occurred.
The calculation of height is much less involved. The height of a single line of text is simply the font size. A line of text at size 10 will take up 10 pt.
If you are wanting to calculate multiple lines of text you will need to account for the "line height" (essentially the amount of whitespace between lines). In my testing I found that jsPDF uses a default line height of 115% (1.15x) of the font size. Thus your calculation of line height would become:
You then simply convert to your desired unit of measurement as above.
It's now included in jsPDF: