Text in PDFKit

The basics

PDFKit makes adding text to documents quite simple, and includes many optionsto customize the display of the output. Adding text to a document is as simpleas calling the text method.

  1. doc.text 'Hello world!'

Internally, PDFKit keeps track of the current X and Y position of text as itis added to the document. This way, subsequent calls to the text method willautomatically appear as new lines below the previous line. However, you canmodify the position of text by passing X and Y coordinates to the textmethod after the text itself.

  1. doc.text 'Hello world!', 100, 100

If you want to move down or up by lines, just call the moveDown or moveUpmethod with the number of lines you'd like to move (1 by default).

Line wrapping and justification

PDFKit includes support for line wrapping out of the box! If no options aregiven, text is automatically wrapped within the page margins and placed in thedocument flow below any previous text, or at the top of the page. PDFKitautomatically inserts new pages as necessary so you don't have to worry aboutdoing that for long pieces of text. PDFKit can also automatically wrap textinto multiple columns.

If you pass a specific X and Y position for the text, it will not wrap unlessyou also pass the width option, setting the width the text should be wrappedto. If you set the height option, the text will be clipped to the number oflines that can fit in that height.

When line wrapping is enabled, you can choose a text justification. There arefour options: left (the default), center, right, and justify. Theywork just as they do in your favorite word processor, but here is an exampleshowing their use in a text box.

  1. lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl.'
  2. doc.fontSize 8
  3. doc.text 'This text is left aligned. ' + lorem,
  4. width: 410
  5. align: 'left'
  6. doc.moveDown()
  7. doc.text 'This text is centered. ' + lorem,
  8. width: 410
  9. align: 'center'
  10. doc.moveDown()
  11. doc.text 'This text is right aligned. ' + lorem,
  12. width: 410
  13. align: 'right'
  14. doc.moveDown()
  15. doc.text 'This text is justified. ' + lorem,
  16. width: 410
  17. align: 'justify'
  18. # draw bounding rectangle
  19. doc.rect(doc.x, 0, 410, doc.y).stroke()

The output of this example, looks like this:

Text  - 图1

Text styling

PDFKit has many options for controlling the look of text added to PDFdocuments, which can be passed to the text method. They are enumeratedbelow.

  • lineBreak - set to false to disable line wrapping all together
  • width - the width that text should be wrapped to (by default, the page width minus the left and right margin)
  • height - the maximum height that text should be clipped to
  • ellipsis - the character to display at the end of the text when it is too long. Set to true to use the default character.
  • columns - the number of columns to flow the text into
  • columnGap - the amount of space between each column (1/4 inch by default)
  • indent - the amount in PDF points (72 per inch) to indent each paragraph of text
  • paragraphGap - the amount of space between each paragraph of text
  • lineGap - the amount of space between each line of text
  • wordSpacing - the amount of space between each word in the text
  • characterSpacing - the amount of space between each character in the text
  • fill - whether to fill the text (true by default)
  • stroke - whether to stroke the text
  • link - a URL to link this text to (shortcut to create an annotation)
  • underline - whether to underline the text
  • strike - whether to strike out the text
  • continued - whether the text segment will be followed immediately by another segment. Useful for changing styling in the middle of a paragraph.
  • features - an array of OpenType feature tags to apply. If not provided, a set of defaults is used.
    Additionally, the fill and stroke color and opacity methods described in thevector graphics section are applied to text content as well.

Here is an example combining some of the options above, wrapping a piece of text into three columns, in a specified width and height.

  1. lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;'
  2. doc.text lorem,
  3. columns: 3
  4. columnGap: 15
  5. height: 100
  6. width: 465
  7. align: 'justify'

The output looks like this:

Text  - 图2

Rich Text

As mentioned above, PDFKit supports a simple form of rich text via the continued option.When set to true, PDFKit will retain the text wrapping state between text calls. This way,when you call text again after changing the text styles, the wrapping will continue rightwhere it left off.

The options given to the first text call are also retained for subsequent calls after a continued one, but of course you can override them. In the following example, the widthoption from the first text call is retained by the second call.

  1. doc.fillColor 'green'
  2. .text lorem.slice(0, 500),
  3. width: 465
  4. continued: yes
  5. .fillColor 'red'
  6. .text lorem.slice(500)

Here is the output:

Text  - 图3

Fonts

The PDF format defines 14 standard fonts that can be used in PDF documents (4styles of Helvetica, Courier, and Times, as well as Symbol and Zapf Dingbats),but also allows fonts to be embedded right in the document. PDFKit supportsembedding TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collection (.ttc),and Datafork TrueType (.dfont) fonts.

To change the font used to render text, just call the font method. If youare using a standard PDF font, just pass the name to the font method.Otherwise, pass the path to the font file, or a Buffer containing the font data.If the font is a collection font (.ttc and .dfont files), meaning that itcontains multiple styles in the same file, you should pass the name of the styleto be extracted from the collection.

Here is an example showing how to set the font in each case.

  1. # Set the font size
  2. doc.fontSize(18)
  3. # Using a standard PDF font
  4. doc.font('Times-Roman')
  5. .text('Hello from Times Roman!')
  6. .moveDown(0.5)
  7. # Using a TrueType font (.ttf)
  8. doc.font('fonts/GoodDog.ttf')
  9. .text('This is Good Dog!')
  10. .moveDown(0.5)
  11. # Using a collection font (.ttc or .dfont)
  12. doc.font('fonts/Chalkboard.ttc', 'Chalkboard-Bold')
  13. .text('This is Chalkboard, not Comic Sans.')

The output of this example looks like this:

Text  - 图4

Another nice feature of the PDFKit font support, is the ability to register afont file under a name for use later rather than entering the path to the fontevery time you want to use it.

  1. # Register a font
  2. doc.registerFont('Heading Font', 'fonts/Chalkboard.ttc', 'Chalkboard-Bold')
  3. # Use the font later
  4. doc.font('Heading Font')
  5. .text('This is a heading.')

That's about all there is too it for text in PDFKit. Let's move on now toimages.

PreviousNext

原文: http://pdfkit.org/docs/text.html