Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - How to calculate width and height of text in jspdf?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

var doc = new jsPDF();
var width = doc.getTextWidth('Text');
console.log(width);

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 but pt. Here is an example:

var doc = new jsPDF('p', 'pt');
var dim = doc.getTextDimensions('Text');
console.log(dim); // Object {w: 24.149968818897642, h: 19.499975433070865}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...