Pdfkit: Vertical align text

Created on 5 Sep 2016  路  4Comments  路  Source: foliojs/pdfkit

The docs show text styling options: http://pdfkit.org/docs/text.html

Although align is not on the list, it is in a few examples on the page and works.

There is no mention of a verticalAlign option which would be really useful. You can set a width and height, and I'd like to vertically align the text so it appears dead center.

Any plans to add verticalAlign..?

Most helpful comment

It's already possible to do it:

var string = lorem.slice(0,1000);
var x = doc.x, y = doc.y, h = 300, w = 400;
var options = {width:w, align:'center'};
doc.rect(x, y, w, h).stroke();
doc.text(string, x, y + 0.5 * (h - doc.heightOfString(string, options)), options);

All 4 comments

It's already possible to do it:

var string = lorem.slice(0,1000);
var x = doc.x, y = doc.y, h = 300, w = 400;
var options = {width:w, align:'center'};
doc.rect(x, y, w, h).stroke();
doc.text(string, x, y + 0.5 * (h - doc.heightOfString(string, options)), options);

@alafr I don't think that will work for me.

First, heightOfString() doesn't seem to be in the documentation anywhere, I can only see widthOfString() and currentLineHeight() on the Annotations page: http://pdfkit.org/docs/annotations.html.

I've tried both heightOfString() and currentLineHeight(), they both return 10.982 in my example.

The problem is that I'm working with product titles of varying lengths like:

  • Heartwood Creek Snowman with Ornaments Hanging Ornament
  • Red Hat Lady

The first one here will line wrap, the second won't, so they're two different heights in my design, but heightOfString() and currentLineHeight() return the same for both, so I can't position them differently.

I need a verticalAlign that works the same as align, in that the length of the string and line wrapping don't matter - it's always centred.

The code above works in the browser demo (http://pdfkit.org/demo/browser.html).
heightOfString(text, options) returns different values when the text wraps, you just need to add the width in the options argument

@alafr Got it, thank you!

I'm guessing you looked at the code to see both that heightOfString() exists, and that you pass text and options to it...??

The docs for PDFKit could do with being updated.

Was this page helpful?
0 / 5 - 0 ratings