Layout text with MultilineTextShape

Generate PDF, Shapes
3/12/2014

Downloads

This sample demonstrates how to format and layout text with MultilineTextShape.

The following code adds a MultilineTextShape at the center of the page. A RectangleShape highlights the text block.

C#

1 const string text = 2 "With PDFKit.NET you can Manipulate existing " + 3 "PDF documents and forms using a highly intuitive object model. " + 4 "Add pages, stamp content and fill forms."; 5 6 // create a new document with a single page 7 Document document = new Document(); 8 Page page = new Page(PageSize.Letter); 9 document.Pages.Add(page); 10 11 // add a shapes collection at the center of the page 12 // it will be the container for multiline text shapes 13 var shapes = new ShapeCollection 14 { 15 Width = page.Width/2, 16 Height = page.Height*0.85 17 }; 18 shapes.Transform = new TranslateTransform 19 { 20 X = (page.Width - shapes.Width)/2, 21 Y = (page.Height - shapes.Height)/2 22 }; 23 page.Overlay.Add(shapes); 24 25 // add a rectangle shape with a salmon background to visualize the container 26 // note that the rectangle is positioned relative to its container, not the page 27 var rectangle = 28 new RectangleShape(0, 0, shapes.Width, shapes.Height, null, new SolidBrush(Color.Salmon)); 29 shapes.Add(rectangle); 30 31 // dock text to the top of the shapes collection - align left 32 const int bottomMargin = 20; 33 var fragment = new Fragment(text, Font.TimesRoman, 16); 34 var multilineText = new MultilineTextShape 35 { 36 Dock = DockStyle.Top, 37 Margin = {Bottom = bottomMargin} 38 }; 39 multilineText.Fragments.Add(fragment); 40 shapes.Add(multilineText); 41 42 // save result 43 using (FileStream file = new FileStream("dockmultilinetext.pdf", FileMode.Create, FileAccess.Write)) 44 { 45 document.Write(file); 46 }

As a result we get the multiline text on the page with the default formatting:

00.png

Control layout

The following snippets show how to control the layout of the text.

C#- Align right

1 multilineText.HorizontalAlignment = HorizontalAlignment.Right;

02.png

C# - Center

1 multilineText.HorizontalAlignment = HorizontalAlignment.Center;

01.png

C# - Justify

1 multilineText.Justified = true;

03.png

C# - Line spacing

1 multilineText.LineSpacing = 5;

04.png

C# - Indentation

1 multilineText.FirstLineIndentation = 20;

05.png

C# - Hang indentation

1 multilineText.HangIndentation = 20;

06.png