Hi, guys. That would be great if you to add drawing text with fixed width so that the text would wrap the next lines.
Hello @ithillel-aminev. I agree that this would be useful. It's a feature I plan implement in pdf-lib eventually.
In the mean time, however, you should be able to accomplish this manually if you're willing to do a bit of of work. I've explained how to center and right-align text on a page here: https://github.com/Hopding/pdf-lib/issues/10. In that thread, I include code for measuring a string of text. Once you're able to do this, it should be easy enough to manually wrap your lines when they exceed your desired line length.
Please let me know if this doesn't work for you, or you have additional questions!
Thank you a lot
Happy to help!
I'm going to close this for now. Feel free to reopen it if you have additional questions 馃憤
Now I'm trying to wrap a text into lines and experience a problem with setting n elements (r or rn) in my test string literal. The result is the string is not wrapped and the n elements are just drawn instead.
Yes, but there is still the drawLinesOfText operator.
PDFs don't treat control characters like \r and \n specially within a string. So you must manually split the string into lines and use the drawText operator for each line (then you have to deal with line spacing). Or, as you mentioned, you can just use the drawLinesOfText operator.
Note that it's rather simple to define a helper function around drawLinesOfText that wraps on newlines if that's what you need:
const drawWrappingText = (text, options) => drawLinesOfText(text.split('\n'), options);
Version 0.6.0 is now published. It adds new methods to measure the width and height of text in standard and embedded fonts (example). The full release notes are available here.
You can install this new version with npm:
npm install [email protected]
It's also available on unpkg:
@rehman-ahmad-nbs Here's the corresponding link for the current version of pdf-lib: https://github.com/Hopding/pdf-lib#embed-font-and-measure-text
Here is a function to break lines with a maxWidth given.
function fillParagraph(text, font, fontSize, maxWidth) {
var paragraphs = text.split('\n');
for (let index = 0; index < paragraphs.length; index++) {
var paragraph = paragraphs[index];
if (font.widthOfTextAtSize(paragraph, fontSize) > maxWidth) {
var words = paragraph.split(' ');
var newParagraph = [];
var i = 0;
newParagraph[i] = [];
for (let k = 0; k < words.length; k++) {
var word = words[k];
newParagraph[i].push(word);
if (font.widthOfTextAtSize(newParagraph[i].join(' '), fontSize) > maxWidth) {
newParagraph[i].splice(-1); // retira a ultima palavra
i = i + 1;
newParagraph[i] = [];
newParagraph[i].push(word);
}
}
paragraphs[index] = newParagraph.map(p => p.join(' ')).join('\n');
}
}
return paragraphs.join('\n');
}
Most helpful comment
Here is a function to break lines with a maxWidth given.