Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
7.02k stars 676 forks source link

BUG: breakTextIntoLines removes empty lines in multiline text #1590

Open AmilKey opened 10 months ago

AmilKey commented 10 months ago

What were you trying to do?

draw multiline text with empty line and maxWidth param

How did you attempt to do it?

function page.drawText have different result when pass maxWidth param and text with empty line for example:

  page.drawText(
    `first\n` +
    `\n` +
    `second\n`
    ,
    {
      x: 25,
      y: 100,
      font,
      size: 24,
      color: rgb(1, 0, 0),
      lineHeight: 24,
      opacity: 0.75,
      maxWidth: 500,
    },
  )

result :

image

call page.drawText without maxWidth

  page.drawText(
    `first\n` +
    `\n` +
    `second\n`
    ,
    {
      x: 25,
      y: 100,
      font,
      size: 24,
      color: rgb(1, 0, 0),
      lineHeight: 24,
      opacity: 0.75,
    },
  )

result:

image

as you can see, without maxWidth parameter the empty line is also present

What actually happened?

empty line not rendered

What did you expect to happen?

few tests that should passed

https://github.com/Hopding/pdf-lib/blob/master/tests/utils/strings.spec.ts#L23

  it(`handles trailing newlines`, () => {
    const input = 'foo\n';
    const expected = ['foo', ''];
    const actual = breakTextIntoLines(input, [], 21, computeTextWidth);
    expect(actual).toEqual(expected);
  });

  it(`handles empty lines`, () => {
    const input = 'foo\n\nbar';
    const expected = ['foo', '', 'bar'];
    const actual = breakTextIntoLines(input, [], 21, computeTextWidth);
    expect(actual).toEqual(expected);
  });

How can we reproduce the issue?

see above

Version

1.17.1

What environment are you running pdf-lib in?

Browser

Checklist

Additional Notes

No response