Pdfmake: How to get text width ?

Created on 22 May 2019  路  3Comments  路  Source: bpampuch/pdfmake

Hello,

is there a way to calculate text width from its definition ?
{ text: 'My text`, fontSize: 24 }

or to define the width ?
{ text: 'My text`, fontSize: 24, width: 200, alignment: 'left', background: 'blue' }

(so my text will be center in a 200px block)

Most helpful comment

I can get the maxWidth and other parameter as well.
And the magic happen!
Shakala booom ;)

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

console.log(
        this.getTextMaxWidth({
          absolutePosition: { x: offsetX, y: offsetY },
          columns: [
            {
              text: productEntry.product.name,
              fontSize: 10
            }
          ]
        })
      )
  private getTextMaxWidth(content: {}) {
    const temp = [];
    temp.push(content);
    const pdf = pdfMake.createPdf({ content: temp });
    pdf.getStream({});
    return pdf.docDefinition.content[0]._maxWidth;
  }

All 3 comments

is there a way to calculate text width from its definition ?
{ text: 'My text`, fontSize: 24 }

No, it is not possible.

or to define the width ?
{ text: 'My text`, fontSize: 24, width: 200, alignment: 'left', background: 'blue' }

(so my text will be center in a 200px block)

Block containter not supported now (feature request: #15), but as workarround can be used table, see example:

var dd = {
    content: [
        {
            table: {
                widths: [200],
                body: [
                    [{text: 'My text', fontSize: 24, alignment: 'center', fillColor: 'blue' }],
                ],
            },
            layout: 'noBorders'
        }
    ]
}

I can get the maxWidth and other parameter as well.
And the magic happen!
Shakala booom ;)

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

console.log(
        this.getTextMaxWidth({
          absolutePosition: { x: offsetX, y: offsetY },
          columns: [
            {
              text: productEntry.product.name,
              fontSize: 10
            }
          ]
        })
      )
  private getTextMaxWidth(content: {}) {
    const temp = [];
    temp.push(content);
    const pdf = pdfMake.createPdf({ content: temp });
    pdf.getStream({});
    return pdf.docDefinition.content[0]._maxWidth;
  }

@zullo91 man this works like a charm, thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

m-brudi picture m-brudi  路  3Comments

svenyonson picture svenyonson  路  3Comments

stefanmihoc picture stefanmihoc  路  3Comments

sayjeyhi picture sayjeyhi  路  3Comments

michaelqiji picture michaelqiji  路  3Comments