Pdfkit: Calculating a text width

Created on 18 Dec 2011  路  4Comments  路  Source: foliojs/pdfkit

I want to handle line wrapping myself, so I need to calculate the text width, by looking at the code, I noticed this function: https://github.com/devongovett/pdfkit/blob/master/lib/font.coffee#L191

Is there a way that I can expose it? Or any other way that I can use it? (copy pasting?)

Most helpful comment

Well the document has a widthOfString method as well, which calls the method you linked to on the current font. So set the font in the normal manner, and call that method:

# make a document
doc = new PDFDocument

# set the font
doc.font('fonts/PalatinoBold.ttf')
      .fontSize(25);

# get the width of a string
var w = doc.widthOfString("hello world");

All 4 comments

Well the document has a widthOfString method as well, which calls the method you linked to on the current font. So set the font in the normal manner, and call that method:

# make a document
doc = new PDFDocument

# set the font
doc.font('fonts/PalatinoBold.ttf')
      .fontSize(25);

# get the width of a string
var w = doc.widthOfString("hello world");

cool, thanks

What if I want to get width of text in a different font or different style (like bold and italic) other than the set font?

I needed a right aligned text line to have a different font (bold) in one of the middle words. Feel free to edit it to suit your needs.

`const rightAlignmentDifferentFontText = ({
textBoxX,
textBoxY,
textBoxWidth,
startText,
middleText,
endText,
startTextFont,
middleTextFont,
endTextFont
}) => {
// get the endText width
doc.font(endTextFont);
const endTextWidth = doc.widthOfString(endText);
// take the given width of the whole text
// add the textBoxX
// and subtract the endTextWidth
const endTextX = textBoxWidth + textBoxX - endTextWidth;

  const endTextY = textBoxY;

  doc.text(endText, endTextX, endTextY);

  doc.font(middleTextFont);
  const middleTextWidth = doc.widthOfString(middleText);
  // take the X of the endText computed above
  // and compute the X of the replacementText
  // based on the middleText width
  const middleTextX = endTextX - middleTextWidth;

  // the Y is the same as the whole textbox
  const middleTextY = textBoxY;

  // set the font

  // draw the middleText
  doc.text(middleText, middleTextX, middleTextY);


  doc.font(startTextFont);
  const startTextWidth = doc.widthOfString(startText);

  // take the X of the middleText computed above
  // and compute the X of the startText
  // based on the startText width
  const startTextX = middleTextX - startTextWidth;
  const startTextY = textBoxY;
  doc.text(startText, startTextX, startTextY);
};`
Was this page helpful?
0 / 5 - 0 ratings