如何确定pdf-lib中自动换行文本的高度?

问题描述 投票:0回答:1

pdf-lib 中,可以使用此处概述的技术自动换行文本:https://stackoverflow.com/a/77436904/1766230

import { PDFDocument, StandardFonts } from 'pdf-lib';
const doc = await PDFDocument.create();
const font = await doc.embedFont(StandardFonts.TimesRoman);
const page = doc.addPage();
// This will word-wrap fine:
page.drawText(someLongText, { font, size: 20, lineHeight: 25, maxWidth: 200, wordBreaks: [' '] });
// But now what?
// page.moveDown(???);

问题是您可能需要...

  • 向下移动 y 光标,以便将下一行写入页面。 (
    page.moveDown
    )
  • 检测何时可能需要新页面(即,此换行文本的高度将超出页面底部),以便您可以拆分文本并添加新页面 (
    doc.addPage
    )。

但是文档中似乎没有任何函数可以让您确定正在绘制到页面上的自动换行文本的高度。

font.heightAtSize(size)
只是获取字体的高度。可以做什么?

javascript pdf pdf-generation pdf-lib.js
1个回答
0
投票

在研究了drawText

代码后,我找到了解决方案。
有一个名为 
breakTextIntoLines
的实用函数,我们需要再次运行它来获取行数。

import { breakTextIntoLines } from 'pdf-lib';
//
// ... define font, doc, page ...
//

function wordWrapHeight(text, options) {
    const { font, size, lineHeight, wordBreaks, maxWidth } = options;
    const getTextWidth = (t) => font.widthOfTextAtSize(t, size);
    const lines = breakTextIntoLines(text, wordBreaks, maxWidth, getTextWidth);
    return lines.length * lineHeight;
}

const size = 20;
const lineHeight = size * 1.4;
const maxWidth = 200;
const wordBreaks = [' '];
const options = { size, lineHeight, font, maxWidth, wordBreaks };
const distanceDown = wordWrapHeight(text, options);
const y = page.getY();
const endY = y - distanceDown;
// TODO: Determine if the endY would take you off the page.
// If so, then split the lines up based on the amount of room left.
// Otherwise, you do this:
page.drawText(text, options);
page.moveDown(distanceDown);
© www.soinside.com 2019 - 2024. All rights reserved.