drawText accepts a maxWidth, when this width is exceeded it will wrap your text! https://pdf-lib.js.org/docs/api/interfaces/pdfpagedrawtextoptions
Answer from paco on Stack OverflowPDF-LIB
pdf-lib.js.org › docs › api › interfaces › multilinetextlayout
MultilineTextLayout · PDF-LIB
pdf-lib › MultilineTextLayout · MultilineTextLayout · bounds · fontSize · lineHeight · lines · • bounds: LayoutBounds · Defined in api/text/layout.ts:94 · • fontSize: number · Defined in api/text/layout.ts:96 · • lineHeight: number · Defined in api/text/layout.ts:97 ·
GitHub
github.com › Hopding › pdf-lib › issues › 1202
layoutMultilineText takes a very long time for long strings · Issue #1202 · Hopding/pdf-lib
November 4, 2021 - let text = ''; for (let i = 0; i < 2000; i++) { text += 'test '; } const now = Date.now(); layoutMultilineText(text, { alignment: TextAlignment.Left, bounds: { width: 500, height: 500, x: 0, y: 0 }, font, fontSize: 12, }); console.log(Date.now() - now); // 30 to 40 seconds ... My report includes a Short, Self Contained, Correct (Compilable) Example. I have attached all PDFs, images, and other files needed to run my SSCCE. Again, thanks for your efforts in maintaining this terrific library!
Published Mar 29, 2022
GitHub
github.com › Hopding › pdf-lib › issues › 72
Text in multiple lines · Issue #72 · Hopding/pdf-lib
January 28, 2019 - Hi! First of all, thanks a lot for this library. I am trying to paint a long and dynamic text that comes from an API, the text is content of multiple paragraphs that must be painted on one or several pages, the characters have not been i...
Published Jan 28, 2019
PDFlib
pdflib.com › pdflib-cookbook › form_fields › form_multiline_textfield
form_multiline_textfield
* Define a tooltip (tooltip={Enter a comment}). */ optlist = "backgroundcolor={rgb 0.95 0.95 1} bordercolor={gray 0} " + "currentvalue={Enter a multiline comment} multiline=true " + "scrollable=false tooltip={Enter a comment} font =" + font + " fontsize=14"; p.create_field(llx, lly, llx + width, lly + height, "comment", "textfield", optlist); p.setfont(font, 12); p.fit_textline("Multiline text field; a tooltip is provided.", llx, lly-=30, ""); p.fit_textline("Text is not allowed to scroll out of the window.", llx, lly-=20, ""); p.end_page_ext(""); p.end_document(""); } catch (PDFlibException e) { System.err.println("PDFlib exception occurred:"); System.err.println("[" + e.get_errnum() + "] " + e.get_apiname() + ": " + e.get_errmsg()); exitcode = 1; } catch (Exception e) { System.err.println(e); exitcode = 1; } finally { if (p != null) { p.delete(); } System.exit(exitcode); } } }
Top answer 1 of 3
8
drawText accepts a maxWidth, when this width is exceeded it will wrap your text! https://pdf-lib.js.org/docs/api/interfaces/pdfpagedrawtextoptions
2 of 3
4
Use maxWidth with wordBreaks. i.e
const text = 'This is a really long bit of text and I want it to remain on the page and resize as needed and not get cut off';
pdfPage.drawText(text, {
x: width / 2 - (text.length * 10),
y: height - 200,
size: 40,
font: pdfFont,
color: rgb(0.95, 0.1, 0.1),
maxWidth: 500, wordBreaks: [" "]
});
GitHub
github.com › Hopding › pdf-lib › blob › master › src › api › text › layout.ts
pdf-lib/src/api/text/layout.ts at master · Hopding/pdf-lib
export const layoutMultilineText = ( text: string, { alignment, fontSize, font, bounds }: LayoutTextOptions, ): MultilineTextLayout => { const lines = lineSplit(cleanText(text)); ·
Author Hopding
Snyk
snyk.io › advisor › pdf-lib › functions › pdf-lib.drawlinesoftext
How to use the pdf-lib.drawLinesOfText function in pdf-lib | Snyk
We'll draw // him centered horizontally in the top half of the page. drawImage(MARIO_PNG, { x: 200, y: 350, width: MARIO_PNG_WIDTH, height: MARIO_PNG_HEIGHT, }), // Now let's draw 2 lines of red Courier text near the bottom of the page. drawLinesOfText(['This text was added', 'with JavaScript!'], { x: 30, y: 150, font: COURIER_FONT, size: 48, colorRgb: [1, 0, 0], }), ); // Here we (1) register the content stream to the PDF document, and (2) add the // reference to the registered stream to the page's content streams.
PDF-LIB
pdf-lib.js.org › docs › api
pdf-lib · PDF-LIB
▸ (dropdown: PDFDropdown, widget: PDFWidgetAnnotation, font: PDFFont): AppearanceOrMapping‹PDFOperator[]›
UNPKG
unpkg.com › browse › [email protected] › src › api › text › layout.ts
pdf-lib
0; } // We were unable to split the input enough to get a chunk that would fit // within the specified `maxWidth` so we'll just return everything return { line: input, encoded: font.encodeText(input), width: font.widthOfTextAtSize(input, fontSize), remainder: undefined, }; }; export const layoutMultilineText = ( text: string, { alignment, fontSize, font, bounds }: LayoutTextOptions, ): MultilineTextLayout => { const lines = lineSplit(cleanText(text)); if (fontSize === undefined || fontSize === 0) { // fontSize = computeFontSize(lines, font, bounds); // This is hardcoded to make it easier to perform automatic line-wrapping.
GitHub
github.com › Hopding › pdf-lib › pull › 1203
Improve performance of layoutMultilineText by seibar · Pull Request #1203 · Hopding/pdf-lib
What? Addresses: #1202. Previously long strings (> 10k characters) took very long for this function to execute (> 30 seconds). With this fix, a 10k character string executes in less than 1 second. Testing? Added a unit test Executed integration tests (and fixed an issue that test number 15 uncovered) A lot of testing using the scratchpad.
Author Hopding
PDFlib
pdflib.com › pdflib-cookbook › textflow
textflow
PDFlib GmbH(Powered by Apryse, Producer of the Market's Leading PDF SDK)
JSFiddle
jsfiddle.net › Hopding › rgu6ca59 › 2
Embed Font and Measure Text (pdf-lib) - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
GitHub
github.com › Hopding › pdf-lib-docs › blob › master › docs › api › interfaces › multilinetextlayout.md
pdf-lib-docs/docs/api/interfaces/multilinetextlayout.md at master · Hopding/pdf-lib-docs
pdf-lib › MultilineTextLayout · MultilineTextLayout · bounds · fontSize · lineHeight · lines · • bounds: LayoutBounds · Defined in api/text/layout.ts:94 · • fontSize: number · Defined in api/text/layout.ts:96 · • lineHeight: number · Defined in api/text/layout.ts:97 ·
Author Hopding
GitHub
github.com › Hopding › pdf-lib › issues › 701
Text Alignment Center for a Multi line text · Issue #701 · Hopding/pdf-lib
July 19, 2020 - I have a client's house address which I have to render on PDF, and addresses tend to wrap in multiple lines so when I render the text using drawText with maxWidth I am getting as displayed in attached PDF. I need the text to be center aligned in all rows.
Published Dec 11, 2020
GitHub
github.com › Hopding › pdf-lib › discussions › 1333
SingleLineTextLayout example · Hopding/pdf-lib · Discussion #1333
const rightAlign = async ( doc: PDFDocument, page: PDFPage, currentPosition: { x: number; y: number }, moveRight: number, text: string, textOptions: PDFPageDrawTextOptions ) => { const helveticaFont = await doc.embedFont(StandardFonts.Helvetica) const textWidth = helveticaFont.widthOfTextAtSize(text, textOptions.size) page.moveTo(currentPosition.x, currentPosition.y) page.moveRight(moveRight) page.moveLeft(textWidth) page.drawText(text, textOptions) page.moveRight(textWidth) page.moveLeft(moveRight) }
Author Hopding
GitHub
github.com › Hopding › pdf-lib › issues › 930
add text alignment option to PDFPage.drawText() · Issue #930 · Hopding/pdf-lib
June 5, 2021 - The drawText method does a nice job with multiline texts that in a box when maxWith is defined in options. However it always aligns the text LEFT, while in some cases we would like to use CENTER of RIGHT. It seems line we have some code ...
Published Jul 07, 2021
Syncfusion
support.syncfusion.com › kb › article › 8479 › how-to-draw-multiline-text-in-pdf-using-c-and-vb-net
How to draw multi-line text in PDF using C# and VB.NET
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; // Create a text element PdfTextElement element = new PdfTextElement(text); element.Brush = new PdfSolidBrush(Color.Black); element.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // Set the properties to paginate the text PdfLayoutFormat layoutFormat = new PdfLayoutFormat(); layoutFormat.Break = PdfLayoutBreakType.FitPage; // Set bounds to draw multiline text RectangleF bounds = new RectangleF(PointF.Empty, page.Graphics.ClientSize); // Draw the text element with the properties and formats set element.Draw(page, bounds, layoutFormat); // Save and close the document document.Save("MultipleLineText.pdf"); document.Close(true);
Top answer 1 of 2
1
Daniel's answer helped. 2 lines need correcting, though:
let centerText = setTextCenter(pages[0], font, fontSize)
let rightText = setTextRight(pages[0], font, fontSize)
2 of 2
1
You can do it using widthOfTextAtSize font property like this:
const pdfDoc = await PDFDocument.load(file)
const pages = pdfDoc.getPages()
const font = await pdfDoc.embedFont(StandardFonts.TimesRoman)
const fontSize = 10
let centerText = setTextCenter(pages[0], font, fontSize)
centerText('This text is center aligned', xPos, yPos)
let rightText = setTextRight(pages[0], font, fontSize)
rightText('this text is right aligned', xPos, yPos)
const setTextCenter = (page, font, size) => {
return (text, x, y) => {
const widthText = font.widthOfTextAtSize(text, size)
const props = {
x: x - widthText / 2,
y: y,
size,
font,
}
page.drawText(text, props)
}
}
const setTextRight = (page, font, size) => {
return (text, x, y) => {
const widthText = font.widthOfTextAtSize(text, size)
const props = {
x: x - widthText,
y: y,
size,
font,
}
page.drawText(text, props)
}
}
Thanks Eric, correction is done.
PDF-LIB
pdf-lib.js.org › docs › api › classes › pdftextfield
PDFTextField · PDF-LIB
If this is a rich text field, it will be converted to a standard text field in order to set the text. pdf-lib does not support writing rich text strings. Nor do most PDF readers and writers.