TextWriter#
This class represents a MuPDF text object. The basic idea is to decouple (1) text preparation, and (2) text output to PDF pages.
During preparation, a text writer stores any number of text pieces (“spans”) together with their positions and individual font information. The output of the writer’s prepared content may happen multiple times to any PDF page with a compatible page size.
A text writer is an elegant alternative to methods Page.InsertText() and friends:
Improved text positioning: Choose any point where insertion of text should start. Storing text returns the “cursor position” after the last character of the span.
Free font choice: Each text span has its own font and
fontSize. This lets you easily switch when composing a larger text.Automatic fallback fonts: If a character is not supported by the chosen font, alternative fonts are automatically searched. This significantly reduces the risk of seeing unprintable symbols in the output (“TOFUs” – looking like a small rectangle). MuPDF.NET now also comes with the universal font “Droid Sans Fallback Regular”, which supports all Latin characters (including Cyrillic and Greek), and all CJK characters (Chinese, Japanese, Korean).
Cyrillic and Greek Support: The Base-14-fonts have integrated support of Cyrillic and Greek characters without specifying encoding. Your text may be a mixture of Latin, Greek and Cyrillic.
Transparency support: Parameter opacity is supported. This offers a handy way to create watermark-style text.
Justified text: Supported for any font – not just simple fonts as in
Page.InsertTextbox().Reusability: A TextWriter object exists independent from PDF pages. It can be written multiple times, either to the same or to other pages, in the same or in different PDFs, choosing different colors or transparency.
Using this object entails three steps:
When created, a TextWriter requires a fixed page rectangle in relation to which it calculates text positions. A text writer can write to pages of this size only.
Store text in the TextWriter using methods
TextWriter.Append(),TextWriter.Appendv()andTextWriter.FillTextbox()as often as is desired.Output the TextWriter object on some PDF page(s).
Note
Starting with version 1.17.0, TextWriters do support text rotation via the morph parameter of
TextWriter.WriteText().There also exists
Page.WriteText()which combines one or more TextWriters and jointly writes them to a given rectangle and with a given rotation angle – much likePage.ShowPdfPage().
Method / Attribute |
Short Description |
|---|---|
Add text in horizontal write mode |
|
Add text in vertical write mode |
|
Fill rectangle (horizontal write mode) |
|
Output TextWriter to a PDF page |
|
Text color (can be changed) |
|
Last written character ends here |
|
Text opacity (can be changed) |
|
Page rectangle used by this TextWriter |
|
Area occupied so far |
Class API
- class TextWriter#
- TextWriter(Rect rect, float opacity: 1, float[] color: null)#
- Parameters:
rect (Rect) – rectangle internally used for text positioning computations.
opacity (float) – sets the transparency for the text to store here. Values outside the interval
[0, 1)will be ignored. A value of e.g. 0.5 means 50% transparency.color (float[]) – the color of the text. All colors are specified as floats 0 <= color <= 1. A single float represents some gray level, an array of float implies the colorspace via its length.
- Append(Point pos, string text, Font font: null, int fontSize: 11, string language: null, bool right2left: false, int smallCaps: 0)#
Add some new text in horizontal writing.
- Parameters:
pos (Point) – start position of the text, the bottom left point of the first character.
text (string) – a string of arbitrary length. It will be written starting at position “pos”.
font – a Font. If omitted,
new Font(fontName: ..., fontFile: ...)will be used. See the available in-built fonts which can be used here.fontSize (float) – the font size, a positive number, default
11.language (string) – the language to use, e.g. “en” for English. Meaningful values should be compliant with the ISO 639 standards 1, 2, 3 or 5. Reserved for future use: currently has no effect as far as we know.
right2left (bool) – whether the text should be written from right to left. Applicable for languages like Arabian or Hebrew. Default is false. If true, any Latin parts within the text will automatically converted. There are no other consequences, i.e.
TextWriter.LastPointwill still be the rightmost character, and there neither is any alignment taking place. Hence you may want to useTextWriter.FillTextbox()instead.smallCaps (int) – look for the character’s Small Capital version in the font. If present, take that value instead. Otherwise the original character (this font or the fallback font) will be taken. The fallback font will never return small caps. For example, this snippet:
Document doc = new Document(); Page page = doc.NewPage(); string text = "MuPDF.NET: the C# bindings for MuPDF"; // choose a font with small caps like Noto Serif Regular MuPDF.NET.Font font = new MuPDF.NET.Font(""); MuPDF.NET.TextWriter tw = new MuPDF.NET.TextWriter(page.Rect); tw.Append(new(50, 100), text, font, smallCaps:1); tw.WriteText(page); doc.Save("test.pdf");
will produce this PDF text:
- Appendv(Point pos, string text, Font font: null, float fontSize: 11, string language: null, int smallCaps: 0)#
Add some new text in vertical, top-to-bottom writing.
- Parameters:
pos (Point) – start position of the text, the bottom left point of the first character.
text (string) – a string. It will be written starting at position “pos”.
font – a Font. If omitted,
new Font(fontName: ..., fontFile: ...)will be used.fontSize (float) – the
fontSize, a positive float, default 11.language (string) – the language to use, e.g. “en” for English. Meaningful values should be compliant with the ISO 639 standards 1, 2, 3 or 5. Reserved for future use: currently has no effect as far as we know.
smallCaps (bool) – see
Append().
- Returns:
TextRectandLastPoint. Raises an exception for an unsupported font – checked viaFont.IsWritable.
- FillTextbox(Rect rect, string text, Point pos: null, Font font: null, float fontSize: 11, float lineHeight: 0, int align: 0, bool right2left: false, bool warn: false, bool smallCaps: false)#
Fill a given rectangle with text in horizontal writing mode. This is a convenience method to use as an alternative for
Append().- Parameters:
rect (Rect) – the area to fill. No part of the text will appear outside of this.
text (string) – the text. Can be specified as a (UTF-8) string or a list / tuple of strings. A string will first be converted to a list using Split(’n’). Every list item will begin on a new line (forced line breaks).
pos (Point) – start storing at this point. Default is a point near rectangle top-left.
font (Font) – the Font, default
new Font(fontName: ..., fontFile: ...).fontSize (float) – the
fontSize.align (int) – text alignment. Use one of TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT or TEXT_ALIGN_JUSTIFY.
right2left (bool) – whether the text should be written from right to left. Applicable for languages like Arabian or Hebrew. Default is false. If true, any Latin parts are automatically reverted. You must still set the alignment (if you want right alignment), it does not happen automatically – the other alignment options remain available as well.
warn (bool) –
on text overflow do nothing, warn, or raise an exception. Overflow text will never be written.
Default is null.
The list of overflow lines will be returned.
smallCaps (bool) – see
Append().
- Return type:
list of Tuple(string, float)
- Returns:
List of lines that did not fit in the rectangle. Each item is a tuple
(text, length)containing a string and its length (on the page).
Note
Use these methods as often as is required – there is no technical limit (except memory constraints of your system). You can also mix
Append()and text boxes and have multiple of both. Text positioning is exclusively controlled by the insertion point. Therefore there is no need to adhere to any order. Raise an exception for an unsupported font – checked viaFont.IsWritable.- WriteText(Page page, float opacity: -1, float[] color: null, Morph morph: null, int overlay: 1, int oc: 0, int renderMode: 0)#
Write the TextWriter text to a page, which is the only mandatory parameter. The other parameters can be used to temporarily override the values used when the TextWriter was created.
- Parameters:
page – write to this Page.
opacity (float) – override the value of the TextWriter for this output.
color (float[]) – override the value of the TextWriter for this output.
morph (Morph) – modify the text appearance by applying a matrix to it. If provided, this must be a sequence (P, M) with a point-like P and a matrix-like matrix. A typical example is rotating the text around P.
overlay (int) – put in foreground (default) or background.
oc (int) – the
Xrefof anOCGorOCMD.renderMode (int) –
The PDF
Troperator value. Values: 0 (default), 1, 2, 3 (invisible).
- LastPoint#
The “cursor position” – a Point – after the last written character (its bottom-right).
- Return type:
- Opacity#
The text opacity (modifiable).
- Return type:
float
- Color#
The text color (modifiable).
- Return type:
float[]
Note
To see some demo scripts dealing with TextWriter, have a look at this repository.
Opacity and color apply to all the text in this object.
If you need different colors / transparency, you must create a separate TextWriter. Whenever you determine the color should change, simply append the text to the respective TextWriter using the previously returned
LastPointas position for the new text span.Appending items or text boxes can occur in arbitrary order: only the position parameter controls where text appears.
Font and
fontSizecan freely vary within the same TextWriter. This can be used to let text with different properties appear on the same displayed line: just specify pos accordingly, and e.g. set it toLastPointof the previously added item.You can use the pos argument of
TextWriter.FillTextbox()to set the position of the first text character. This allows filling the same textbox with contents from different TextWriter objects, thus allowing for multiple colors, opacities, etc.MuPDF does not support all fonts with this feature, e.g. no Type3 fonts. Starting with v1.18.0 this can be checked via the font attribute
Font.IsWritable. This attribute is also checked when using TextWriter methods.
