Crite
Crite

Reputation: 43

SVG Multiline Text Wrapping With Sharp

I have to use sharp.js to produce PNG out of SVG that contains dynamic text. My question is, how to wrap long text in SVG elements and generate a PNG with sharp? Also if it is too long in height and width it should end up with 3 dots (...).

I tried the following one, but it has no effect.

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
  <rect fill="#CEE" width="100%" height="100%" />
    <foreignObject x="20" y="90" width="150" height="200">
      <p xmlns="http://www.w3.org/1999/xhtml">This is a very very looooooooooooong text, it should have a line break on the end and continue on the next line, then. if it is too long it should end with ...</p>
    </foreignObject>
</svg>

and then

sharp(Buffer.from(svg))
    .png()
    .toFile(fileName)
    .catch(console.log)

Upvotes: 2

Views: 3234

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

<foreignObject> is a way to embed HTML (usually) inside an SVG. It requires an HTML rendering engine. So is really only supported in browsers. It is unlikely Sharp includes an HTML rendering engine. So you'll need to do it another way.

SVG has no automatic line wrapping. At least the current version of SVG (1.1) doesn't. SVG 2 has the inline-size property, but few, if any, SVG renderers support that yet AFAIK.

If you are in an environment that properly supports the SVG DOM, then it can be done by adding a <text> element and measuring it's length. Then iteratively adding or removing words or letters in order to determine where to wrap the text.

Upvotes: 3

Related Questions