Sei sulla pagina 1di 89

TallPDF.NET 3.

0
Developer Guide
Version: 1.2 Date: November 24, 2008

TallPDF.NET 3.0 - Developer Guide

Legal Note
Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, email addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, email address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of TallComponents BV. TallComponents BV may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from TallComponents BV, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. Acrobat and PDF are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Windows NT, 2000, XP, and Server 2003, Vista, .NET Framework and Internet Information Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All other trademarks are the property of their respective owners. 2001-2008 TallComponents BV. All rights reserved. TallPDF.NET is a trademark of TallComponents BV.

Pag. 2/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Contents
1. Introduction....................................................................................................................10 1.1. 1.2. 1.3. 1.4. 1.5. 1.6. 1.7. 2. 2.1. 2.2. 2.3. 2.4. 2.5. 2.6. 3. 3.1. 3.2. 3.3. 3.4. 3.5. 3.6. 3.7. 4. 4.1. 4.2. 4.3. 4.4. 4.5. 5. 5.1. 5.2. 6. 6.1. 6.2. 6.3. 6.4. 6.5. 6.6. Features ..................................................................................................................10 Standard vs Professional..........................................................................................10 Whats new in 3.0? ...................................................................................................10 Upgrading from TallPDF.NET 2.0 ............................................................................... 11 Please send us feedback! ......................................................................................... 11 Online Resources..................................................................................................... 11 Naming convention .................................................................................................. 11 Getting Started............................................................................................................ 12 Development environment ....................................................................................... 12 Hello World Console Application C# ....................................................................... 14 Hello World Console Application VB.NET ................................................................ 15 Hello World ASP.NET Application C#.......................................................................16 Hello World ASP.NET Application VB.NET................................................................ 17 Further reading ........................................................................................................18 Document ................................................................................................................... 19 Create and Save....................................................................................................... 19 DocumentInfo .......................................................................................................... 19 Security.................................................................................................................. 20 ViewerPreferences .................................................................................................. 20 Actions .................................................................................................................... 21 JavaScripts .............................................................................................................. 21 Sections ................................................................................................................. 22 Sections......................................................................................................................23 Page Size and Margins............................................................................................ 24 Headers and Footers ................................................................................................25 Columns ................................................................................................................. 26 Page Boxes..............................................................................................................27 Areas...................................................................................................................... 28 Positioning .............................................................................................................. 31 Flow Constraints ......................................................................................................32 Text ............................................................................................................................34 Formatting...............................................................................................................34 Layout .....................................................................................................................34 Preserve White Space...............................................................................................35 Hyphenation or Line Breaking...................................................................................35 Cross-References .....................................................................................................35 NumberedItem.........................................................................................................36

Paragraphs .....................................................................................................................30

Pag. 3/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

6.7. 7. 7.1. 7.2. 7.3. 7.4. 8. 8.1. 8.2. 8.3. 9. 9.1. 9.2. 9.3. 9.4. 9.5. 9.6. 9.7. 9.8. 9.9. 9.10. 9.11. 9.12. 9.13. 9.14. 10. 10.1. 10.2. 10.3. 10.4. 10.5. 10.6. 10.7. 11. 11.1. 11.2. 11.3. 11.4. 11.5. 11.6. 11.7. 12.

Headings................................................................................................................ 38 Borders and Background......................................................................................... 42 Flow Constraints ..................................................................................................... 42 How to Size Cells .................................................................................................... 42 Further Reading ...................................................................................................... 44 Images........................................................................................................................45 Size.........................................................................................................................45 Image Source...........................................................................................................45 Multi-frame images................................................................................................. 46 Drawings and Shapes ................................................................................................. 48 Drawing.................................................................................................................. 48 Shape .................................................................................................................... 48 ContentShape......................................................................................................... 49 ImageShape ............................................................................................................50 TextShape ...............................................................................................................50 MultilineTextShape..................................................................................................50 SimpleXhtmlShape ..................................................................................................50 PageShape ..............................................................................................................50 ShapeCollection ...................................................................................................... 51 Pens and Brushes................................................................................................. 51 PathShape ...........................................................................................................52 Field Shapes ........................................................................................................54 BarcodeShape......................................................................................................54 Docking ...............................................................................................................55 Label and Caption Properties ................................................................................56 Bookmark Property of Heading..............................................................................56 Fragment with HasContextFields ........................................................................... 57 Fragment that Refers to a Heading ........................................................................58 Fragment that Refers to a Paragraph .....................................................................59 Fragment as Part of a Heading...............................................................................59 CrossreferenceSection..........................................................................................59 Restrictions..........................................................................................................61 Section Events .....................................................................................................61 ParagraphCollection Events ................................................................................. 62 Paragraph Events ................................................................................................ 62 TextParagraph Events .......................................................................................... 62 RowCollection Events ...........................................................................................63 Example: Firehose Generation from SQL ................................................................63 Generate PDF from XML ...............................................................................................65

Tables ............................................................................................................................ 41

Context Fields .............................................................................................................56

Event-Driven Generation ..............................................................................................61

Pag. 4/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

12.1. 12.2. 12.3. 12.4. 13. 13.1. 13.2. 14. 14.1. 14.2. 14.3. 14.4. 15. 15.1. 15.2. 16. 16.2. 16.3. 16.4. 16.5. 16.6. 17. 17.1. 17.2. 17.3. 17.4. 17.5. 17.6. 17.7. 17.8. 17.9. 17.10.

XML Format Specification .....................................................................................65 Working with XSL ................................................................................................ 68 Special Characters ...............................................................................................70 XML Parse Exceptions........................................................................................... 71 Inherit from a TallPDF.NET Class............................................................................74 Use Specialized Class in XML................................................................................74 GoToAction ..........................................................................................................76 UriAction..............................................................................................................76 FormAction........................................................................................................... 77 JavaScriptAction ................................................................................................... 77 Fonts ...................................................................................................................78 Restrictions..........................................................................................................79 XHTML vs HTML ....................................................................................................81 Fonts ...................................................................................................................81 Forms ..................................................................................................................81 Supported XHTML Elements ..................................................................................81 Restrictions..........................................................................................................85 First Steps........................................................................................................... 86 New Namespaces ................................................................................................ 86 Renamed Classes .................................................................................................87 Renamed Enumerations........................................................................................87 Renamed Properties ............................................................................................ 88 Removed Items.................................................................................................... 88 Margins and Paddings......................................................................................... 88 DocumentInfo ..................................................................................................... 88 Events, Delegates and Event Arguments ............................................................... 89 Updating XML...................................................................................................... 89 Convert XHTML to PDF................................................................................................. 80 Actions .......................................................................................................................76

Extend TallPDF.NET ......................................................................................................74

Convert RTF to PDF.......................................................................................................78

Upgrading from TallPDF.NET 2.0 .................................................................................. 86

Pag. 5/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

List of Code Samples


Code sample 2-1. Hello World Console Application in C# .......................................................... 14 Code sample 2-2. Hello World Console Application in VB.NET................................................... 15 Code sample 2-3. ASP.NET Web Application in C# ....................................................................16 Code sample 2-4. ASP.NET Web Application in VB.NET ............................................................. 17 Code sample 3-1. Create a new document, add content (omitted) and save it to disk in C#......... 19 Code sample 3-2. . Create a new document, add content (omitted) and save it to disk in VB.NET 19 Code sample 3-3. . Set document info in C#............................................................................. 19 Code sample 3-4. . Set document info in VB.NET...................................................................... 19 Code sample 3-5. . Set security in C#...................................................................................... 20 Code sample 3-6. . Set security in VB.NET............................................................................... 20 Code sample 3-7. Setting viewer preferences in C# ................................................................. 20 Code sample 3-8. Setting viewer preferences in VB.NET.......................................................... 20 Code sample 3-9. Add a BeforePrintAction to a document in C#................................................ 21 Code sample 3-10. Declare a document-level JavaScript function in C# .................................... 22 Code sample 3-11. Declare a document-level JavaScript function in VB.NET.............................. 22 Code sample 4-1. Create a new document and add a section in C# ...........................................23 Code sample 4-2. Create a new document and add a section in VB.NET ....................................23 Code sample 4-3. Set the page size and margins of a section in C# ......................................... 24 Code sample 4-4. Set the page size and margins of a section in VB.NET ...................................25 Code sample 4-5. Add headers and footers in C# .................................................................... 26 Code sample 4-6. Add columns in C# ......................................................................................27 Code sample 4-7. Add columns in VB.NET................................................................................27 Code sample 4-8. Set the crop box in C# ................................................................................ 28 Code sample 4-9. Set the crop box in VB.NET ......................................................................... 28 Code sample 4-10. Stamp Confidential on each page using a foreground area in C#............... 29 Code sample 5-1. Add paragraph objects to a section in C# ...................................................... 31 Code sample 6-1. Mix text formatting in C#..............................................................................34 Code sample 6-2. Generate multi-level headings .....................................................................39 Code sample 7-1. Build a table in C# ....................................................................................... 41 Code sample 8-1. Construct an image from a relative file path (C#)...........................................45 Code sample 8-2. Construct an image from an absolute file path (C#).......................................45 Code sample 8-3. Construct an image from a URL (C#) .............................................................45 Code sample 8-4. Construct an image from a Bitmap caller disposes (C#)............................. 46 Code sample 8-5. Construct an image from a Bitmap callee disposes (C#) ............................ 46 Code sample 8-6. Construct an image from a memory stream (C#) .......................................... 46 Code sample 9-1. Add a drawing in C#.................................................................................... 48 Code sample 10-1. Add an image with a label and caption in C#...............................................56 Code sample 10-2. Add a text line below an image that uses context fields for formatting .........56 Code sample 10-3. Add a heading and format the bookmark .................................................... 57

Pag. 6/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Code sample 10-3. Add a CrossreferenceSection to a document in C#...................................... 60 Code sample 10-4. Handle the CrossreferenceSection.ComposeEntry event in C# .................... 60 Code sample 11-1. Generate in event-driven mode by selecting the Document.Write overload (C#) .............................................................................................................................................61 Code sample 11-2. Create a SqlDataReader in C# .....................................................................63 Code sample 11-3. Prepare Table.Rows in C# ...........................................................................63 Code sample 11-4. Handle PrintRow Event in C#...................................................................... 64 Code sample 11-5. Handle PrintFirstRow Event in C# ............................................................... 64 Code sample 11-6. After generation, close the SQL connection ................................................ 64 Code sample 12-1. Hello World TallPDF.NET XML ......................................................................65 Code sample 12-2. Invoke the conversion of XML to PDF in C# ..................................................65 Code sample 12-3. Assign a value property............................................................................. 66 Code sample 12-4. Assign a double value using a unit specifier .............................................. 66 Code sample 12-5. Assign a value using the names of a static property of static field ............... 66 Code sample 12-6. Properties of reference type are specified as child elements....................... 66 Code sample 12-7. Fragment.Font specified as an XML attribute ...............................................67 Code sample 12-8. Assign an instance of SolidBrush to a property of type Brush ......................67 Code sample 12-9. Collection properties are implicit in XML.....................................................67 Code sample 12-10. Some collection properties require an explicit type attribute..................... 68 Code sample 12-11. Multiple collection properties of the same type......................................... 68 Code sample 12-12. Specify an enum property as an XML attribute.......................................... 68 Code sample 12-13. Properties of type System.String can be specified as text nodes ............... 68 Code sample 12-14. Application specific XML ......................................................................... 69 Code sample 12-15. XSL transforming XML to TallPDF.NET XML ................................................ 69 Code sample 12-16. Invoke the XSL transformation in C# .........................................................70 Code sample 12-17. AttibuteNotFoundException ...................................................................... 71 Code sample 12-18. ElementNotFoundException...................................................................... 71 Code sample 12-19. EnumConstantNotFoundException ............................................................72 Code sample 12-20. PropertyCannotParseException ................................................................72 Code sample 12-21. MissingReadMethodException .................................................................72 Code sample 12-22. MissingAddMethodException...................................................................73 Code sample 13-1. Create a specialized Heading......................................................................74 Code sample 13-2. Use the specialized Heading ......................................................................74 Code sample 13-3. Use specialized class in XML ......................................................................74 Code sample 15-1. Using the RtfParagraph in C# ......................................................................78 Code sample 15-2. Using the RtfParagraph in XML ...................................................................78 Code sample 16-1. Import XHTML in C#................................................................................... 80 Code sample 16-2. Include XHTML in TallPDF.NET XML ............................................................ 80 Code sample 17-1. TallPDF.NET 2.0 code for registering and handling generation events .......... 89 Code sample 17-2. TallPDF.NET 3.0 code for registering and handling generation events .......... 89

Pag. 7/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

List of Tables
Table 9-1. Public properties specific to ContentShape............................................................. 49 Table 9-2. Public properties specific to TextShape ...................................................................50 Table 9-3. Public properties specific to ShapeCollection .......................................................... 51 Table 10-1. Context fields for the Heading.Bookmark property.................................................. 57 Table 10-2. Heading.Bookmark samples.................................................................................. 57 Table 10-3. Context fields for fragments that do not refer to a paragrap ....................................58 Table 10-4. Fragment.Text samples .........................................................................................58 Table 10-5. Context fields for fragments that refer to a heading ................................................58 Table 10-6. Context field samples for fragments that refer to a heading. ...................................58 Table 10-7. Context fields for fragments that refer to a paragraph.............................................59 Table 10-8. Context field samples for fragments that refer to a heading. ...................................59 Table 11-1. Events fired by Section.......................................................................................... 62 Table 11-2. Events fired by ParagraphCollection...................................................................... 62 Table 11-3. Events fired by Paragraph ..................................................................................... 62 Table 11-4. Events fired by TextParagraph................................................................................63 Table 11-5. Events fired by RowCollection ................................................................................63 Table 16-1 Supported XHTML elements....................................................................................85 Table 17-1. All TallPDF.NET 3.0 namespaces .............................................................................87 Table 17-2. Renamed classes ..................................................................................................87 Table 17-3. Renamed enumerations........................................................................................ 88 Table 17-4. Renamed properties............................................................................................. 88 Table 17-5. Removed items .................................................................................................... 88 Table 17-6. Margin and Padding properties have been grouped............................................... 88 Table 17-7. Document info properties have been grouped into class DocumentInfo .................. 89

Pag. 8/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

List of Figures
Figure 2-1. Visual Studio .NET code IntelliSense....................................................................... 13 Figure 2-2. Select the TallPDF.NET 3.0 XML Schema file............................................................ 13 Figure 2-3. Visual Studio .NET XML IntelliSense ....................................................................... 13 Figure 4-1. A section renders its paragraphs into one or more pages.........................................23 Figure 4-2. Page size and margins.......................................................................................... 24 Figure 4-3. Headers and Footers..............................................................................................25 Figure 4-4. Columns .............................................................................................................. 26 Figure 4-5. Page boxes ...........................................................................................................27 Figure 5-1. Paragraph class hierarchy ......................................................................................30 Figure 5-2. Paragraph positioning relative to the cursor ...........................................................32 Figure 5-3. Paragraph flow without constraints ........................................................................33 Figure 5-4. Do-not-break flow constraint..................................................................................33 Figure 5-5. Keep-with-next flow constraint ...............................................................................33 Figure 6-1. Default layout........................................................................................................34 Figure 6-2. Justified text .........................................................................................................34 Figure 6-3. First-line indentation .............................................................................................35 Figure 6-4. Hanging indentation..............................................................................................35 Figure 6-5. Line spacing..........................................................................................................35 Figure 6-6. Auto-format a cross-reference................................................................................36 Figure 6-7. Layout options voor the bullet/number part of a numbered item..............................37 Figure 6-8. Context fields for the number part of a numbered item ...........................................37 Figure 6-9. Result after generating multi-level headings.......................................................... 40 Figure 7-1. Paragraph, Table, Rows en Cells. ............................................................................ 41 Figure 7-2. Table border, padding and margin......................................................................... 42 Figure 9-1. Partial Shape class hierarchy ................................................................................ 49 Figure 9-2. Nesting of shapes ................................................................................................. 51 Figure 9-3. The pattern of a pen is defined by a phase and a dashes-array. ...............................52 Figure 9-4. PathShape class hierarchy ....................................................................................53 Figure 9-5. BarcodeShape class hierarchy ...............................................................................54

Pag. 9/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

1. Introduction
This developer guide helps you understand the TallPDF.NET 3.0 class library. It walks through the main concepts and illustrates them with code samples. This guide is not a type reference. This is included in the evaluation download.

1.1.

Features

TallPDF.NET is a 100% managed (verifiable) .NET class library for dynamic generation of PDF documents. It consists of just a single assembly that can be xcopy-deployed. It has no dependencies other than the .NET framework. Central to TallPDF.NET is a consistent and highly intuitive object model consisting of classes like Document, Section, TextParagraph, Table, Header, Footer, etc. The focus of the development team is always to ease the task of integrating our class libray in a larger application. These are TallPDF.NETs primary features: Generate PDF programmatically or from XML Declarative flow-layout model that creates pages on the fly Generate bookmarks Generate internal and external links Mix flow and grid layout Generate tables and nest other content (including tables) in table cells Embed raster images (BMP, PNG, TIFF, JPG and GIF) Create form fields and JavaScript actions (Professional edition only) Auto-number headings and caption and cross-references Embed and subset TrueType fonts (Professional edition only) Text formatting: justification, alignment, text color, text decoration (underline, strikethrough) Basic support for importing XHTML and RTF (Professional edition only) Embed existing PDF pages Weak and strong encryption (Professional edition only) Embed simple or complex drawings consisting of primitive shapes such as lines, bezier curves and text

1.2.

Standard vs Professional

TallPDF.NET is available in two editions; Standard and Professional. TallPDF.NET Professional offers additional features including TrueType font support, document security and XHTML and RTF import.

1.3.

Whats new in 3.0?


XhtmlParagraph: It now is possible to convert XHTML to PDF. There are however a
number of constraints. See Chapter Convert XHTML to PDFConvert XHTML to PDF.

Version 3.0 of TallPDF.NET introduces the following new features:

RtfParagraph: It now is possible to convert RTF to PDF. See Chapter Convert RTF to
PDFConvert RTF to PDF.

Pag. 10/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

PageShape: The page shape allows including pages from existing PDF documents in the generated PDF. This page can be used as background (stationary), foreground (overlay, classification) or content. Color spaces: Grayscale and CMYK are added in addition to RGB. These can be used on
brushes, pens, text, shape, borders, etc.

Actions: It now is possible to include actions in a document. Supported actions are GoToAction (Link to a page in same or other PDF), UriAction (navigates to a webpage), Form actions (submit and reset) and JavaScript action. Field shapes: It is now possible to include new field shapes allowing you to generate
forms.

IEnumerable: All collection classes now implement IEnumerable. .NET 2.0 build (supports x64).

1.4.

Upgrading from TallPDF.NET 2.0

In order to accommodate new features and to fix inconsistencies in the API, we have introduced a number of breaking changes. Chapter Upgrade from TallPDF.NET 2.0 discusses upgrading in detail.

1.5.

Please send us feedback!

Please help us improve this document. If you have any questions, suggestions or find anything in this document is incorrect or missing then let us know at support@tallcomponents.com.

1.6.

Online Resources
Visit our web site: http://www.tallcomponents.com. Sample applications running live on www.tallcomponents.com. A collection of samples is available online. Each sample demonstrate a key feature of TallPDF.NET including the use of tables, images, area's, columns etc. From time to time our developers publish valuable information for developers as TechArticles. Each article addresses a common issue that many developers experience. If you have an idea for an article please contact our support team. Quickly find answers to frequently asked questions. Download the latest version of TallPDF.NET 3.0 Professional or Standard edition. This includes the .NET 1.1 and .NET 2.0 assemblies, the Type Reference, this Developer Guide and a sample collection. The version history lists changes from version to version. If you are experiencing problems please make sure you are using the latest version; your problem may already have been solved.

1.7.

Naming convention

We try to adhere as much as possible to Microsofts Design Guidelines for Developing Class Libraries.

Pag. 11/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

2. Getting Started
2.1. Development environment
TallPDF.NET has been compiled and tested with Microsoft Visual Studio.NET 2003 and 2005 and Microsoft .NET Framework 1.1 and 2.0. TallPDF.NET is a 100% managed .NET component and consists of just a single assembly: TallComponents.PDF.Layout.dll. TallPDF.NET can be used with any .NET application, including console applications, WinForms applications, ASP.NET web applications, ASP.NET web services and Windows services. 2.1.1. NET Framework 1.1 and 2.0 TallPDF.NET 3.0 is compiled against version 1.1 and 2.0 of the .NET framework. Both builds are included in the distribution. 2.1.2. 2.1.3. 64-bit Dependencies The .NET 2.0 build of TallPDF.NET 3.0 can be used on 64-bit machines. TallPDF.NET does not depend on any third-party product other than the Microsoft .NET platform. It consists of just a single assembly. The Microsoft .NET framework may be redistributed. It can be included in the installer for any product. For more information please read "Redistributing the Microsoft .NET Framework" at the Microsoft MSDN website. 2.1.4. Deployment TallPDF.NET is fully compatible with the XCopy deployment principle of .NET. This means that installing TallPDF.NET is as simple as copying the single assembly to the installation folder of your application. For web applications this would be the /bin folder inside the virtual folder of your web site. Although it is possible, there is no need to install TallPDF.NET in the GAC (Global Assembly Cache). 2.1.5. Classic ASP and COM TallPDF.NET does not support the legacy technologies COM and ASP out of the box. However, the .NET Framework allows you to call .NET assemblies from a COM component. See "Calling a .NET Component from a COM Component" for more information. 2.1.6. Visual Studio .NET IntelliSense (C#/VB.NET) The TallPDF.NET 3.0 installation includes the XML document file TallComponents.PDF.Layout.xml which is generated from our C# comments. If this file is in the same folder as the TallComponents.PDF.Layout.dll that is referenced from your project, TallPDF.NET documentation is added to Visual Studio .NET IntelliSense as shown in the following figure.

Pag. 12/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Figure 2-1. Visual Studio .NET code IntelliSense 2.1.7. Visual Studio .NET IntelliSense (XML) The TallPDF.NET 3.0 installation includes the TallPDF.NET 3.0 XML schema file TallComponents.PDF.Layout.xsd. Depending on the Visual Studio .NET edition that you use, copy this file to one of the following two location: <program files>\Microsoft Visual Studio .NET 2003\Common7\Packages\schemas\xml <program files>\Microsoft Visual Studio 8\Xml\Schemas Now you can select it as the targetSchema in the Properties view of Visual Studio .NET after which IntelliSense support is added.

Figure 2-2. Select the TallPDF.NET 3.0 XML Schema file

Figure 2-3. Visual Studio .NET XML IntelliSense

Pag. 13/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

2.2.
1.

Hello World Console Application C#


Start Visual Studio .NET 2003 or 2005.

To create a Console Application in C# that generates a PDF document, do the following: 2. Select menu item File > New > Project. 3. From the New project dialog, select project type Visual C# and project template Console application. 4. Enter a name for the project and the folder to store the project, then click Ok. 5. 7. A default project is created. Select the Browse tab, select TallComponents.PDF.Layout.dll and click Ok. 6. Select menu item Project > Add Reference 8. Open Program.cs or main.cs from the solution explorer. 9. Replace the code in this file with the code below. 10. Save, compile and run the application. 11. Open the newly generated PDF document.
using System; using System.IO; using TallComponents.PDF.Layout; using TallComponents.PDF.Layout.Paragraphs; class Hello { static void Main( string[] args ) { // create a document Document doc = new Document(); // add a section Section section = new Section(); doc.Sections.Add( section ); // add a text paragraph TextParagraph textParagraph = new TextParagraph(); section.Paragraphs.Add( textParagraph ); // add a text fragment Fragment fragment = new Fragment(); fragment.Text = "Hello world!"; textParagraph.Fragments.Add( fragment ); // save document as PDF to disk using ( FileStream fs = new FileStream( hello.pdf, FileMode.Create ) ) { doc.Write( fs ); } } }

Code sample 2-1. Hello World Console Application in C#

Pag. 14/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

2.3.
1.

Hello World Console Application VB.NET


Start Visual Studio .NET 2003 or 2005.

To create a Console Application in VB.NET that generates a PDF document, do the following: 2. Select menu item File > New > Project. 3. From the New project dialog, select project type Visual Basic and project template Console application. 4. Enter a name for the project and the folder to store the project, then click Ok. 5. 7. A default project is created. Select the Browse tab, select TallComponents.PDF.Layout.dll and click Ok. 6. Select menu item Project > Add Reference 8. Open Module1.vb from the solution explorer. 9. Replace the code in this file with the code below. 10. Save, compile and run the application. 11. Open the newly generated PDF document.
Imports System.IO Imports TallComponents.PDF.Layout Imports TallComponents.PDF.Layout.Paragraphs Module HelloWorld Sub Main() ' create a document Dim doc As New Document ' add a section Dim section As New Section doc.Sections.Add(section) ' add a text paragraph Dim textParagraph As New TextParagraph section.Paragraphs.Add(textParagraph) ' add a text fragment Dim fragment As New Fragment fragment.Text = "Hello world!" textParagraph.Fragments.Add(fragment) ' save document as PDF to disk Using fs As FileStream = New FileStream("hello.pdf", FileMode.Create) doc.Write(fs) End Using End Sub End Module

Code sample 2-2. Hello World Console Application in VB.NET

Pag. 15/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

2.4.
1.

Hello World ASP.NET Application C#


Start Visual Studio .NET 2003 or 2005.

To create an ASP.NET Application in C# that generates a PDF document, do the following: 2. Select menu item File > New > Project. 3. From the New project dialog, select project type Visual C# and project template ASP.NET Web Application. 4. Enter a name for the project and the folder to store the project, then click Ok. 5. 7. A default project is created. Select the Browse tab, select TallComponents.PDF.Layout.dll and click Ok. 6. Select menu item Project > Add Reference 8. Open Default.aspx and delete all code except the first line: the @Page directive. 9. Open Default.aspx.cs and replace all code with the code below. 10. Save, compile and run the application. 11. The PDF opens in the web browser.
using System; using TallComponents.PDF.Layout; using TallComponents.PDF.Layout.Paragraphs; namespace WebApplication1 { public class MyPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // create document Document doc = new Document(); // add a section Section section = new Section(); doc.Sections.Add(section); // add a text paragraph TextParagraph textParagraph = new TextParagraph(); section.Paragraphs.Add(textParagraph); // add a text fragment Fragment fragment = new Fragment(); fragment.Text = "Hello world!"; textParagraph.Fragments.Add(fragment); // save the PDF directly to the browser doc.Write(Response); } } }

Code sample 2-3. ASP.NET Web Application in C#

Pag. 16/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

2.5.
1.

Hello World ASP.NET Application VB.NET


Start Visual Studio .NET 2003 or 2005.

To create an ASP.NET Application in C# that generates a PDF document, do the following: 2. Select menu item File > New > Project. 3. From the New project dialog, select project type Visual Basic and project template ASP.NET Web Application. 4. Enter a name for the project and the folder to store the project, then click Ok. 5. 7. A default project is created. Select the Browse tab, select TallComponents.PDF.Layout.dll and click Ok. 6. Select menu item Project > Add Reference 8. Open Default.aspx and delete all code except the first line: the @Page directive. 9. Open Default.aspx.vb and replace all code with the code below. 10. Save, compile and run the application. 11. The PDF opens in the web browser.
Imports TallComponents.PDF.Layout Imports TallComponents.PDF.Layout.Paragraphs Public Class MyPage Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load ' create a document Dim doc As New Document ' add a section Dim section As New Section doc.Sections.Add(section) ' add a text paragraph Dim textParagraph As New TextParagraph section.Paragraphs.Add(textParagraph) ' add a text fragment Dim fragment As New Fragment fragment.Text = "Hello world!" textParagraph.Fragments.Add(fragment) ' save the PDF directly to the browser doc.Write(Response) End Sub End Class

Code sample 2-4. ASP.NET Web Application in VB.NET

Pag. 17/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

2.6.

Further reading
Topic "Redistributing the Microsoft .NET Framework" at the Microsoft MSDN site. Topic "How to deploy an ASP.NET Web application using Xcopy deployment" at the Microsoft Support site. Topic "Global Assembly Cache" at the Microsoft MSDN site. Topic "Calling a .NET Component from a COM Component" at the Microsoft MSDN site. TechArticle 013 : Common PDF streaming issues.

Pag. 18/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

3. Document
The Document class is the top-level class of the TallPDF.NET object model.

3.1.

Create and Save

A typical PDF generation scenario consists of the following basis steps: 1. instantiate a Document; 2. add content and configure document settings; 3. save the document to any stream (typically disk, memory or HTTP response). This is shown in the following code snippets:
// create document Document doc = new Document(); // CODE OMITTED CONTENT IS ADDED HERE // save to disk using ( FileStream file = new FileStream( "out.pdf", FileMode.Create, FileAccess.Write)) { document.Write( file ); }

Code sample 3-1. Create a new document, add content (omitted) and save it to disk in C#
' create a document Dim doc As New Document ' CODE OMITTED CONTENT IS ADDED HERE ' save to disk Using file As FileStream = New FileStream( _ "out.pdf", FileMode.Create, FileAccess.Write) doc.Write( file ) End Using

Code sample 3-2. . Create a new document, add content (omitted) and save it to disk in VB.NET 3.1.1. Write Overloads Document.Write has a number of overloads. Depending on what overload you use, the PDF document is generated in either pull or push mode. This is explained in more detail in Chapter 11, Event-Driven Generation.

3.2.

DocumentInfo

Property DocumentInfo lets you set document level information such as the author and title. This is shown in the next code:
Document doc; doc.DocumentInfo.Author = "Chris Sharp"; doc.DocumentInfo.Title = "TallPDF.NET 3.0 Developer Guide";

Code sample 3-3. . Set document info in C#


Dim doc As New Document doc.DocumentInfo.Author = "Chris Sharp" doc.DocumentInfo.Title = "TallPDF.NET 3.0 Developer Guide"

Code sample 3-4. . Set document info in VB.NET

Pag. 19/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

3.3.

Security

(This applies to the Professional edition only.) The Security property lets you assign passwords and limit user privileges. The following code creates a document that requires a password to open and cannot be printed:
Document doc = new Document(); PasswordSecurity sec = new PasswordSecurity(); sec.Print = false; sec.OwnerPassword = "gjh456j45"; sec.UserPassword = "egryt646g"; doc.Security = sec;

Code sample 3-5. . Set security in C#


Dim doc As New Document Dim sec As New PasswordSecurity() sec.Print = False sec.OwnerPassword = "gjh456j45" sec.UserPassword = "egryt646g" doc.Security = sec

Code sample 3-6. . Set security in VB.NET A typical scenario is to set the user password to the empty string and the owner password to a non-empty string. This will not prompt the user for a password when she opens the document, but a password is required to change security settings. A common question is how to generate a PDF document that cannot be saved. Unfortunately. The PDF format does not foresee in this feature. By default the Security property is null (or Nothing) meaning that the document has no security settings.

3.4.

ViewerPreferences

The ViewerPreferences property allows you to control the way that a PDF reader application displays the PDF initially. E.g. you can set the initial zoom or hide toolbars or set the reader to fullscreen mode. Here are some typical code samples:
Document doc = new Document(); ViewerPreferences vp = new ViewerPreferences(); vp.PageLayout = PageLayout.TwoColumnLeft; doc.ViewerPreferences = vp;

Code sample 3-7. Setting viewer preferences in C#


Dim doc As New Document Dim vp As New ViewerPreferences ' display pages in 2 columns - odd page left vp.PageLayout = PageLayout.TwoColumnLeft doc.ViewerPreferences = vp

Code sample 3-8. Setting viewer preferences in VB.NET

Pag. 20/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

3.5.

Actions

PDF allows you to associate actions with events. Chapter Actions discusses this topic in more detail . For now it suffices to say that the following properties allow you to associate actions with document-level events:
AfterPrintAction: This action will be executed by the PDF reader application after the PDF document has been printed. AfterSaveAction: This action will be executed by the PDF reader application after the

PDF document has been saved.


BeforeCloseAction: This action will be executed by the PDF reader application just before the PDF document is closed. BeforePrintAction: This action will be executed by the PDF reader application just before the PDF document is printed. BeforeSaveAction: This action will be executed by the PDF reader application just before the PDF document is saved. OpenActions: This sequence of actions will be executed by the PDF reader during opening the PDF document.

Note that these actions are not executed by TallPDF.NET. They are only associated with events and the actions are executed by the PDF reader application when the corresponding event occurs. The following code sample generates a PDF document so that a text field is filled with the current date just before it is printed. This way, you can always see on the print out when it was printed. (How to add fields to a PDF document is discussed in Section Field Shapes.)
Document document = new Document(); JavaScriptAction action = new JavaScriptAction( string.Format( "this.getField('printed').value = 'Printed: {0}'", DateTime.Now)); document.BeforePrintAction = action; Section section = document.Sections.Add(); Drawing drawing = new Drawing(200, 100); section.Paragraphs.Add(drawing); TextFieldShape textField = new TextFieldShape(10, 50, 150, 30, "printed"); drawing.Shapes.Add(textField); using (FileStream file = new FileStream( @"..\..\out.pdf", FileMode.Create, FileAccess.Write)) { document.Write(file); }

Code sample 3-9. Add a BeforePrintAction to a document in C#

3.6.

JavaScripts

(This applies to the Professional edition only.) The property JavaScripts lets you declare document level JavaScript. This typically contains common functions and constants that can be reused from other JavaScript actions. See JavaScript actions for more a more detailed discussion. The following code sample shows how to declare a JavaScript function at document level:

Pag. 21/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

JavaScript javaScript = new JavaScript("function foo() { return 10; }"); document.JavaScripts.Add( javaScript );

Code sample 3-10. Declare a document-level JavaScript function in C#


Dim javaScript As New JavaScript("function foo() { return 10; }") doc.JavaScripts.Add(javaScript)

Code sample 3-11. Declare a document-level JavaScript function in VB.NET

3.7.

Sections

The property Sections lets you add Section objects to a document. A document has atleast one Section. A section contains the actual content as paragraph objects. Sections are discussed in more detaill in the next Chapter.

Pag. 22/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

4. Sections
A document consists of one ore more sections. The content of a section is defined by one or more paragraphs. The paragraph are rendered into one or more pages. The section defines the settings for all these pages. These setting include headers and footers, page size and margins and columns. The figure below shows how sections relate to pages.

Figure 4-1. A section renders its paragraphs into one or more pages The following code snippets show how to create a new document and add sections to the document.
// create document Document doc = new Document(); // add a section Section section = new Section(); doc.Sections.Add(section);

Code sample 4-1. Create a new document and add a section in C#


' create a document Dim doc As New Document ' add a section Dim section As New Section doc.Sections.Add(section)

Code sample 4-2. Create a new document and add a section in VB.NET

Pag. 23/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

4.1.

Page Size and Margins

All pages that are rendered from the same section have the same size and margins. The size is set through the PageSize property of Section. PageSize offers standard page formats through static (or shared) properties like PageSize.Letter and PageSize.A4. The margins of the pages can be set through the Margins properties of Section. The paragraphs will be flowed inside these margins. The top margin and the bottom margin define the space reserved for the header and footer, respectively.

Figure 4-2. Page size and margins The following code snippets show how to set the page size and the margins of a section.
Section section = document.Sections.Add(); section.PageSize = PageSize.A4; section.Margin.Left = new Unit(1.25, UnitType.Inch); section.Margin.Right = new Unit(1.25, UnitType.Inch); section.Margin.Top = new Unit(1, UnitType.Inch); section.Margin.Bottom = new Unit(1, UnitType.Inch);

Code sample 4-3. Set the page size and margins of a section in C#

Pag. 24/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Dim section As Section section = doc.Sections.Add(); section.PageSize = PageSize.A4 section.Margin.Left = New Unit(1.25, UnitType.Inch) section.Margin.Right = New Unit(1.25, UnitType.Inch) section.Margin.Top = New Unit(1, UnitType.Inch) section.Margin.Bottom = New Unit(1, UnitType.Inch)

Code sample 4-4. Set the page size and margins of a section in VB.NET

4.2.

Headers and Footers


EvenHeader: The content of this header will be repeated at the top of each even page. OddHeader: The content of this header will be repeated at the top of each odd page. EvenFooter: The content of this footer will be repeated at the bottom of each even

The Section class has 4 properties that allow you to define headers and footers:

page.
OddFooter: The content of this footer will be repeated at the bottom of each odd page.

This is illustrated in the following figure:

Figure 4-3. Headers and Footers The content of both the header and the footer is defined by a collection of paragraphs that will be flowed from top to bottom in the header and footer areas. A header renders from the very top of the page down until the top margin of the section as shown in Figure . Because normally you want to have some whitespace above the header content, you should set the Header.Margin.Top property as shown in the code sample below.

Pag. 25/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Document doc = new Document(); Section section = new Section(); doc.Sections.Add(section); Header oddHeader = new Header(); oddHeader.TopMargin = new Unit(0.2, UnitType.Inch); section.OddHeader = oddHeader; TextParagraph textParagraph = new TextParagraph(); textParagraph.Fragments.Add(new Fragment("odd header")); oddHeader.Paragraphs.Add(textParagraph);

Code sample 4-5. Add headers and footers in C#

4.3.

Columns

Associated with a section is an array of columns. These are accessed through the Section.Columns property. By default, a section has 1 column. You can specifiy the width of each column and the spacing between each column pair (if any). Column settings are made per section. Paragraph of a multi-column section flow from one column to the next. This is illustrated in the next figure.

Figure 4-4. Columns The following code samples show how to add and configure columns.

Pag. 26/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Document doc = new Document(); Section section = doc.Sections.Add(); section.Columns.Count = 3; section.Columns[0].Width = section.Columns[1].Width = section.Columns[2].Width = section.Columns[0].Spacing section.Columns[1].Spacing

200; 100; 100; = 20; // spacing to the right of column 0 = 20; // spacing to the right of column 1

Code sample 4-6. Add columns in C#


Dim doc As New Document() Dim section As New Section doc.Sections.Add(section) section.Columns.Count = 3 section.Columns(0).Width = section.Columns(1).Width = section.Columns(2).Width = section.Columns(0).Spacing section.Columns(1).Spacing

200 100 100 = 20 ' spacing to the right of column 0 = 20 ' spacing to the right of column 1

Code sample 4-7. Add columns in VB.NET

4.4.

Page Boxes

In PDF you can define different boxes per page. The most common box is the media box which simply represents the entire page. Probably it is the only box you are interested in. You set the media box implicitly by setting Section.PageSize. The following figure illustrates the other boxes.

Figure 4-5. Page boxes

Pag. 27/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

4.4.1.

Section.CropBox

The CropBox is the area that should be shown to PDF users and can be printed. It contains the desired 'normal' content of the page. Within the MediaBox, but outside the crop box, cutting marks could be present. Defaults to the media box values. The following code samples show how to set the crop box.
Document doc = new Document(); Section section = doc.Sections.Add(); section.PageSize = new PageSize(612, 792); section.CropBox = new Rectangle(20, 20, 572, 752);

Code sample 4-8. Set the crop box in C#


Dim section As New Section doc.Sections.Add(section) section.PageSize = New PageSize(612, 792) section.CropBox = New Rectangle(20, 20, 572, 752)

Code sample 4-9. Set the crop box in VB.NET 4.4.2. Section.BleedBox The bleed box defines the area outside the cropbox, which is 'blank' and intended for postprinting operations (cutting, folding...). This way cutting machines have some margin for error, without either loosing content (eg. footer: page number) or including production markers (cutting lines, color calibration areas).

4.5.

Areas

An area is a rectangular region on a page. The content of an area consists of a collection of paragraphs. An Area is a generalization of header and footer. In fact, classes Header and Footer inherit from Area.Each section has a collection of foreground areas and a collection of background areas. They appear respectively in front of and behind the main content. An area is repeated on each page that matches the properties of the area. A background area is typically used to add a stationary for a page (company logo, graphical borders), or a watermark. A foreground area can be used for stamping content (Confidential, Draft, etc). The following code sample adds a foreground area that displays Confidential across each page. Drawing and shapes are discussed in detail in Chapter Drawing and Shapes.

Pag. 28/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Document document = new Document(); Section section = document.Sections.Add(); // area spans the entire page Area area = new Area( 0, section.PageSize.Height, section.PageSize.Width, section.PageSize.Height); section.ForegroundAreas.Add(area); // drawing spans the entire area Drawing drawing = new Drawing(area.Width, area.Height); area.Paragraphs.Add(drawing); // add text Confidential TextShape textShape = new TextShape(); textShape.Text = "Confidential"; textShape.Font = Font.Courier; textShape.FontSize = 72; textShape.TextColor = RgbColor.Red; textShape.Opacity = 128; // 50% textShape.Rotation = -45; // clockwise textShape.X = 130; textShape.Y = 180; drawing.Shapes.Add(textShape); // add some dummy content for (int i = 0; i < 100; i++) { TextParagraph text = new TextParagraph(); text.Fragments.Add(new Fragment("A background area is typically used to add a stationary for a page (company logo, graphical borders), or a watermark. A foreground area can be used for stamping content (Confidential, Draft, etc).")); text.SpacingAfter = 10; section.Paragraphs.Add(text); } // save PDF to disk using (FileStream file = new FileStream( "out.pdf", FileMode.Create, FileAccess.Write)) { document.Write(file); }

Code sample 4-10. Stamp Confidential on each page using a foreground area in C# 4.5.1. CrossreferenceSection CrossreferenceSection is a class that specializes Section. An instance of this class can be added to the Document.Sections collection just as a normal Section. The CrossreferenceSection lets you generated sections such as a Table of Contents, a List of Tables or List of Figures. See Section 10.7, CrossreferenceSection for more details.

Pag. 29/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

5. Paragraphs
Paragraphs are the primary content building blocks of a document. All paragraph classes inherit from the abstract base class Paragraph. This base class has common properties such as HorizontalAlignment, SpacingBefore, SpacingAfter and KeepWithNext. Paragraph specializations are Drawing, Image, Table, HorizontalLine, ParagraphCollection, RtfParagraph, XhtmlParagraph, TextParagraph, NumberedItem, BookmarkParagraph and Heading. Paragraph Drawing Image Table HorizontalLine ParagraphCollection RtfParagraph XhtmlParagraph TextParagraph NumberedItem BookmarkParagraph Heading Figure 5-1. Paragraph class hierarchy The content inside Section, Area and Cell1 objects is defined as a collection of Paragraph objects. Paragraph is an abstract class from which a number of paragraphs derive. This Chapter discusses the commonality of all these classes. The following chapters discuss specific paragraphs such as TextParagraph, Image, Table and Drawing in more detail. The following code samples show how to instantiate different paragraph objects and add them to a section.

Defined in Chapter 7, Tables.

Pag. 30/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Document doc = new Document(); Section section = new Section(); doc.Sections.Add(section); TextParagraph textParagraph = new TextParagraph(); // ... add fragment objects section.Paragraphs.Add(textParagraph); Image image = new Image("some.jpg"); // ... set image properties section.Paragraphs.Add(image); Table table = new Table(); // ... add rows, cells, etc. section.Paragraphs.Add(table); Heading heading = new Heading(); // ... set heading properties such as level section.Paragraphs.Add(heading);

Code sample 5-1. Add paragraph objects to a section in C#

5.1.

Positioning

At what position a paragraph is rendered follows from the render process that precedes it; this is obviously beyond the control of an individual paragraph. However, when a paragraph is about to be rendered, there are a number of properties that control the position of the paragraph relative to the current position. These are:
Paragraph.SpacingBefore adds additional white space between this paragraph and

its predecessor.
Paragraph.SpacingAfter adds additional white space between this paragraph and its successor. (Admittedly, this doesn't control the position of the current paragraph but that of the next.) Paragraph.LeftIndentation adds additional white space between the left edge of this paragraph and the left page margin. Paragraph.RightIndentation adds additional white space between the right edge of this paragraph and the right page margin. Paragraph.HorizontalAlignment aligns the paragraph with respect to the left and

right margins of the page. Figure 5-2 illustrates these position properties.

Pag. 31/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Figure 5-2. Paragraph positioning relative to the cursor

5.2.

Flow Constraints
Paragraph.DoNotBreak instructs the layout engine to not break this paragraph across

It is possible to apply flow contraints to paragraphs. These properties are: pages. Note that this property only applies to paragraphs that can be broken (text and tables)
Paragraph.KeepWithNext instructs the layout engine to keep atleast some of this paragraph on the same pages as some of the next paragraph. Paragraph.StartOnNewPage instructs the layout engine to start this paragraph on a

new page. The DoNotBreak and KeepWithNext constraints are typically applied to headings (not by default). The KeepWithNext should also be applied to a Figure or Table that is followed by a caption. The StartOnNewPage constraint makes sense for e.g. a chapter heading. The following three figures illustrate the DoNotBreak and KeepWithNext flow constraints.

Pag. 32/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Figure 5-3. Paragraph flow without constraints

Figure 5-4. Do-not-break flow constraint

Figure 5-5. Keep-with-next flow constraint

Pag. 33/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

6. Text
Most likely, the major part of your document will consist of text. The primary class for adding text is TextParagraph. TextParagraph is a specialization of paragraph. Therefore, all members of paragraph are members of TextParagraph as well. So you can align it, apply text flow constraints and add it to a section, area, table cell, header and footer.

6.1.

Formatting

TextParagraph is a specialization of Paragraph. It is the primary class for generating a block of text that spans one or more line. A text paragraph consists of one or more fragments. A fragment consists of text and format options like font and text color. If a paragraph consists of text that is formatted with a single font, font size and text color, you need only a single fragment. If you want to mix formatting, you need to add multiple fragments. The following code sample shows how to instantiate a text paragraph and add some text:
Document document = new Document(); Section section = document.Sections.Add(); TextParagraph text = new TextParagraph(); text.Fragments.Add(new Fragment("You can mix", Font.Helvetica)); text.Fragments.Add(new Fragment("bold", Font.HelveticaBold)); text.Fragments.Add(new Fragment("and", Font.Helvetica)); text.Fragments.Add(new Fragment("italic.", Font.HelveticaOblique)); section.Paragraphs.Add( text );

Code sample 6-1. Mix text formatting in C#

6.2.

Layout

In addition to the layout options inherited from paragraph, you can set the following properties that control the layout of the text paragraph:
TextParagraph.Justification: If set, the word spacing is increased to fill each line.

This is illustrated in Figure 6-2.


TextParagraph.FirstLineIndentation: The amount by which the first line only is

indented. This is illustrated in Figure 6-3.


TextParagraph.HangIndentation: The amount by which all lines except the first are

indented. This is illustrated in Figure 6-4.


TextParagraph.LineSpacing: The extra space between lines. This is illustrated in

Figure 6-5.

Figure 6-1. Default layout

Figure 6-2. Justified text

Pag. 34/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Figure 6-3. First-line indentation

Figure 6-4. Hanging indentation

Figure 6-5. Line spacing

6.3.

Preserve White Space

By default, each sequence of white space characters is substituted by a single space. You can cancel this behavior by setting the PreserveWhiteSpace option. This is especially useful when you include programming code in your document where you want to preserve spaces, tabs and line breaks. Set the TabSize property to specify the number of spaces that substitute each tab. Note that if you set the Fragment.PreserverWhiteSpace property, then TextParagraph.Justification property has no effect.

6.4.

Hyphenation or Line Breaking

By default, TallPDF.NET breaks text at whitespace. In some cases however this is not desired. Custom hyphenation or line breaking can be achieved by subscribing to the TextParagraph.LineBreak event. The arguments of the event include the word to be broken and the current breaking position. Also the maximum position before which the word has to be broken is given. You can also specify wether a hyphen symbol should be used.

6.5.

Cross-References

It is possible to add a cross-reference from a fragment to a paragraph. To do this add a GoToAction to the Actions property of Fragment. Alternatively, you can use the ID assigned to the Paragraph.ID and assign it to the GoToAction (This is primarily useful in XML code.) Referencing other paragraphs only works in Push-mode (not event-driven.) You can embed context fields in the fragment text that will be resolved to attributes of the paragraph. Among these attributes are caption, label and the number of the page where the target paragraph is rendered.

Pag. 35/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

You can also specify different types of destination, like links to external documents (RemoteDestination) or in-document links (InternalPageDestination). These handlers also work in event driven generation mode. Typical uses of this feature are: Cross-references Table of Content Entries List of Figures, Tables, etc. Auto-Numbering Figures, Tables, etc.

Figure 6-6. Auto-format a cross-reference

6.6.

NumberedItem

NumberedItem is a specialization of TextParagraph. You can use numbered items to compose

a numbered or bulleted list. With respect to TextParagraph, it has an extra fragment collection called NumberFragments. This collection is used to format the number or bullet part of the item. Mostly, this collection will contain only a single fragment. However, if you want to use a mix of fonts or colors in the number part, you can do so. 6.6.1. Positioning the bullet or number part NumberedItem has a number of extra layout properties that let you control the position of the number part with respect to the body of the item. The following figures make this clear.

NumberAlignment = Left

Pag. 36/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

NumberAlignment = Center

NumberAlignment = Right

Figure 6-7. Layout options voor the bullet/number part of a numbered item 6.6.2. Number format Each numbered item is assigned one or more numbers. An item at level 0 is assigned a single number, an item at level 1 is assigned 2 numbers, etc. The render engine maintains a counter for each level and increments this counter after each assignment. When a counter is incremented, all counters at higher levels are automatically reset. Counters are 1-based. An item may reset the counter of its own level by setting its RestartNumbering property. A fragment may include these numbers in its number fragment by using context fields (see Chapter 10, Context Fields for more details). The following shows a typical item list with two levels. The table that follows shows examples of how the bold-faced, red item may be formatted and resolved. first item at level 0 second item at level 0 o o o o Context field
#0 #0.#1 #0/#1 #a0 #A0.a1 #A0 (i1) #I0-#a1 \xb7 (font Symbol)

first item at level 1 second item at level 1 third item at level 1 fourth item at level 1 Resolves to
2 2.3 2/3 b B.c B (iii) II-c Bullet symbol

third item at level 0

Figure 6-8. Context fields for the number part of a numbered item

Pag. 37/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

6.7.

Headings

Heading is a specialization of NumberedItem. The differences between heading and numbered item are: A heading appears in the bookmarks tree of the PDF reader application. Headings have their own set of counters that do not interfere with that of the numbered items, proper. All fragments in the Fragments collection refer automatically to the heading itself. 6.7.1. Bookmark appearance A heading automatically appears as a bookmark in the navigation pane of the PDF viewer. You control the text of this bookmark by setting the Bookmark property to some text that typically includes fields. Example: "#l #0.#1 #c" resolves to something like "Section 3.2 Bookmark" 6.7.2. Context fields All fragments in the Fragments collection refer automatically to the heading itself. This means that fields like #c, #l and #0 will automatically resolve to attributes of this heading. What you will typically do is set the Caption property to the title of this heading and include the #c field in a fragment. The reason for this is that whenever you refer to the heading, e.g. from the TOC, you use fields instead of fragment text. So in order to avoid redundancy you set the text in the Caption and Label properties and refer from your fragments using the #c and #l fields. The following code sample demonstrates using the Heading class.

Pag. 38/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Document document = new Document(); Section section = document.Sections.Add(); string[] chapters = new string[] {"Vector formats", "Raster formats"}; foreach ( string chapter in chapters ) { Heading heading = new Heading(0); heading.SpacingBefore = 8; heading.SpacingAfter = 4; heading.Label = "Chapter"; heading.Caption = chapter; heading.Fragments.Add(new Fragment("#l #0 - #c", Font.HelveticaBold, 16)); heading.Bookmark = "#0. #c"; section.Paragraphs.Add(heading); string[] topics = new string[] { "X", "Y", "Z" }; foreach ( string topic in topics ) { heading = new Heading(1); heading.SpacingBefore = 4; heading.Caption = topic; heading.Fragments.Add(new Fragment("#0.#1 #c", Font.HelveticaBold, 12)); heading.Bookmark = "#0.#1. #c"; section.Paragraphs.Add(heading); for (int k = 0; k < 2; k++) { TextParagraph text = new TextParagraph(); text.Fragments.Add(new Fragment("A background area is typically used to add a stationary for a page (company logo, graphical borders), or a watermark. A foreground area can be used for stamping content (Confidential, Draft, etc).")); text.SpacingAfter = 10; section.Paragraphs.Add(text); } } }

Code sample 6-2. Generate multi-level headings See Figure 6-9 for how the generated PDF document looks in Acrobat 8.0.

Pag. 39/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Figure 6-9. Result after generating multi-level headings

Pag. 40/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

7. Tables
A table is a specialization of Paragraph. Therefore, all members of paragraph are members of table as well. So you can align it, apply text flow constraints and add it to a section, header, footer and table cell. A table consists of one or more rows. A rows consists of one or more cells. A cell may span more than one column. A cell consists of one or more paragraphs. Because a table is a paragraph, it is possible to nest tables. Paragraph

Table Row Cell Paragraph Paragraph Cell

Row Figure 7-1. Paragraph, Table, Rows en Cells. The following code snippet shows how to create a table, including rows, cells and paragraphs.
Document doc = new Document(); Section section = new Section(); doc.Sections.Add(section); // add a table Table table = new Table(); section.Paragraphs.Add(table); // add a row Row row = table.Rows.Add(); // add a cell Cell cell = row.Cells.Add(); // add text to the cell TextParagraph text = new TextParagraph(); cell.Paragraphs.Add(text);

Code sample 7-1. Build a table in C#

Pag. 41/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

7.1.

Borders and Background

You can apply both a background and a border to each table, row and cell. A background is represented by a brush. Therefore a backgound can be a solid color, a hatched pattern, etc. A border is represented by four pens that correspond to the four respective edges. The background or border(edge) can be null, meaning it does not exist. 7.1.1. Padding, Margins and Border Width The extra space outside a border is set by a left, right, top and bottom margin. The extra space inside a border is set by a left, right, top and bottom padding. These attributes are part of the table, row or cell. The following figure makes this clear.

Figure 7-2. Table border, padding and margin

7.2.

Flow Constraints

In addition to the flow constraints that can be applied to any paragraph, there are some extra flow contraints that can be applied to a table. These are Table.RepeatFirstRow and Row.DoNotBreak. If RepeatFirstRow is set, then the first row will be repeated on each page if the table spans multiple pages. If Row.DoNotBreak is set, the row is kept together and not broken across pages.

7.3.

How to Size Cells

There are a number of properties that control the width of the table columns. Although table columns have no explicit representation in the DOM, they are a natural consequence of the fact that all cells that have the same position in a row have an equal width. Or stated otherwise, the vertical edges of these cells are aligned. Cells that span multiple columns are special in this regard but they do fit into this view. The column widths are established in a multi-step process. This process and the rules that govern it, will now be discussed in detail. The following properties control this process:
Cell.FitToContent - an attempt is made to not break paragraphs Cell.Fixed - the cell has a fixed width Cell.PreferredWidth - the preferred width; ignored if fit-to-content Table.ForceWidth - if true, the preferrences of the cells are overruled Table.PreferredWidth - if ForceWidth is true, the table has this width, otherwise

ignored

Pag. 42/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

7.3.1.

Step 1: Minimum Cell Width

In the first step, the minimum width of each cell is determined. Cell width includes border, margin and padding (see Borders and Background). The minimum cell width has a lower bound equal to the minimum width of the included paragraphs. This width depends on the type of paragraph. The minimum width of a text paragraph is the width of the largest word. The width of both a drawing and image equals their Width property. The minimum width of a table follows from the sizing process that is described in this section. The following cases exist:
Cell.Fixed property is set

The minimum width equals the preferred width of the cell. If the minimum width of the included paragraphs is larger than the preferred value, the minimum width is set to this value.

Otherwise
The minimum width equals the the minumum width of the included paragraphs. 7.3.2. Step 2: Preferred Cell Width
Cell.FitToContent property is set The preferred width is so that each paragraph in the Cell.Paragraphs collection fits on a single line. So if the collection contains 3 paragraphs, the preferred width is so that 3 unbroken lines result.

In the next step, the preferred width of each cell is determined. The following cases exist:

Otherwise The preferred width equals the PreferredWidth property, unless this is smaller than the minimum width as determined in the previous step. 7.3.3. Step 3: Minimum and Preferred Column Width In the previous two steps the minimum and preferred width of each individual cell are determined. The largest minimum width of all cells in a column becomes the minimum width of that column. Similarly, the largest preferred width of all cells in a column becomes the preferred width of that column. 7.3.4. Step 4: Actual Column Width Now that each column has a minimum and preferred width, the actual column widths can be determined. This is done as follows. In most cases the preferred width of each column also becomes the actual width. However, in a number of cases the preferred width can or will not be respected. These are:

Table width is forced


If the ForceWidth property of a table is set, then the table overrules the cells. Depending on whether the forced table width is either larger or smaller than the preferred width, the columns need to grow or shrink. These cases are described next in 'Grow Columns' and 'Shrink Columns', respectively.

Total preferred width is too large


If the page width does not allow the preferred column widths, then the columns shrink to the maximum available space as described next in 'Shrink Columns'. 7.3.5. either Step 5: Grow Columns ... The table has a forced width that is larger than the preferred width as determined by the collection of cells. Therefore, some cells need to grow relative to their preferred width. In a first attempt, only the none-fit-to-content cells grow. If the first attempt is not sufficient, then also the fit-to-content cells grow. Growth is distributed evenly.

Pag. 43/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

7.3.6.

... or Step 5: Shrink Columns

The table has a forced width that is smaller than the preferred width as determined by the collection of cells or the latter is larger than the available space. In this case, all cells shrink in an equally distributed manner. A cell never shrinks beyond its minimum width. Note that for a fixed cell, its preferred width is also its mimimum width, so it will not shrink below its preferred width. 7.3.7. Cells that Span Multiple Columns The previous steps describe the process of establishing the size of each column. This involves minimum and preferred widths of cells inside these columns. How do cells that span multiple columns factor into this? Steps 1, 2 and 3 as described above are really carried out from left to right. So these steps are first performed for the first column. Then they are performed for the next column, etc. Then, steps 4 and 5 follow for all columns. In the first 3 steps, a multiple-column cell only contributes to a column if that column is the last of all spanned columns. In that case, its minimum and preferred width are reduced by the sum of the preferred and minimum width of the previous columns. 7.3.8. Table Exceeds Page Width In a special case even the minimum width of all cells exceeds the page width. In this case the table will simply cross the right margin and possibly even the right edge of the paper.

7.4.

Further Reading
Online Tech Article How table and cell sizing works.

Pag. 44/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

8. Images
The Image class is a specialization of paragraph. So all members of paragraph are members of image as well. Like any paragraph, an image can be added to a section, table cell, area, header and footer. Image is a very simple class. It allows you to add a raster images like a BMP or JPEG image to the document.

8.1.

Size

you can set the Width and Height properties to control the size. Furthermore, if the KeepAspectRatio property is set (default), the height property is calculated from the width and vice versa. If you do not explicitly set the size, the maximum width is used. If an image does not fit in the available/given space, by default an exception is generated. Set the property FitPolicy to FitPolicy.Shrink to force resizing the image in this case. If both the height and width are set, the image will be stretched to fit in the given area. The KeepAspectRatio flag is honored when resizing, and the image will be best-fit inside the specified area.

8.2.

Image Source

An Image object can be constructed from a file path, a URL, a System.IO.Stream and a System.Drawing.Bitmap. 8.2.1. Path You set the path of the image either through the constructor or through the 'Path' property. The path can either be a file on disk or a URL. If the path points to a file on disk, it can be either virtual (ASP.NET), absolute or relative. The following code samples demonstrate different scenarios.
Image image = new Image("tc-logo.gif");

Code sample 8-1. Construct an image from a relative file path (C#)
Image image = new Image(@"c:\images\tc-logo.gif");

Code sample 8-2. Construct an image from an absolute file path (C#)
Image image = new Image("http://www.tallcomponents.com/img/tc-logo.gif");

Code sample 8-3. Construct an image from a URL (C#) 8.2.2. System.Drawing.Bitmap Sometimes you want to use a bitmap that is created in memory using the GDI+ image classes. In this case you can construct an Image object from a System.Drawing.Bitmap object. Depending on what constructor overload is used, it is the responsibility of either the caller or callee to dispose the bitmap object. If the caller disposes, then the bitmap should not be disposed before Document.Write returns. The following code samples demonstrate different scenarios.

Pag. 45/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

using (Bitmap bitmap = new Bitmap(tc-logo.gif")) { Image image = new Image(bitmap); section.Paragraphs.Add(image); using (FileStream file = new FileStream("out.pdf", FileMode.Create)) { document.Write(file); } }

Code sample 8-4. Construct an image from a Bitmap caller disposes (C#)
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(tc-logo.gif"); Image image = new Image(bitmap, true); section.Paragraphs.Add(image); using (FileStream file = new FileStream("out.pdf", FileMode.Create)) { document.Write(file); }

Code sample 8-5. Construct an image from a Bitmap callee disposes (C#) 8.2.3. System.IO.Stream In some cases you want to construct the image from a System.IO.Stream instance. A typical scenario is when the image is stored as a binary blob in a database. In this case you get the data from the database, wrap this in a MemoryStream and construct the Image from this stream. Depending on what constructor overload is used, it is the responsibility of either the caller or callee to close the stream object. If the caller is responsible then the stream should not be closed before Document.Write returns. The following code sample demonstrates a typical scenarios.
Document document = new Document(); Section section = document.Sections.Add(); using ( SqlConnection connection = new SqlConnection( "..." ) ) { connection.Open(); string query = "SELECT data FROM images WHERE id=3"; SqlCommand cmd = new SqlCommand( query, connection ); byte[] blob = (byte[]) cmd.ExecuteScalar(); Image image = new Image( new MemoryStream(blob) ); section.Paragraphs.Add(image); } using (FileStream file = new FileStream("out.pdf", FileMode.Create)) { document.Write(file); }

Code sample 8-6. Construct an image from a memory stream (C#)

8.3.

Multi-frame images

For all constructor overloads that were discussed above, an additional overload exists that takes an extra integer argument. This is used as the frame index in case the image has multiple frames. This is typically the case in multi-page TIFF images. There is also a FrameIndex property

Pag. 46/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

to select the frame after construction. Finally there is a FrameCount property that returns the number of frames in the image.

Pag. 47/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

9. Drawings and Shapes


A drawing is a specialization of Paragraph. Therefore all members of paragraph are members of drawing as well and you can add it to a section, header, footer, area and table cell.

9.1.

Drawing

A drawing is a canvas on which shapes are placed at exact locations. You access the collection of shapes through the Shapes property which is of type ShapeCollection. You compose a drawing by adding shapes to this collection. The following code snippet shows how to add a drawing to a section and how to add shapes to a drawing.
Document doc = new Document(); Section section = new Section(); doc.Sections.Add( section ); // add a new drawing of size 200 x 200 pt Drawing drawing = new Drawing( 200, 200 ); section.Paragraphs.Add( drawing ); // add a pie shape with a red outline and blue interior PieShape pie = new PieShape(); pie.Pen = new Pen( System.Drawing.Color.Red, 2 ); pie.Brush = new SolidBrush( System.Drawing.Color.Blue ); drawing.Shapes.Add( pie );

Code sample 9-1. Add a drawing in C#

9.2.

Shape

All shapes inherit directly or indirectly from Shape. It has members that control positioning and docking. Docking is explained in more detail in Section 9.14, Docking. A shape is positioned using the X and Y properties. X and Y are interpreted in the coordinate space of the container. The container is either a ShapeCollection or a Drawing. Figure 9-1 shows the partial shape class hierarchy. The sub hierarchies of the abstract classes BarcodeShape, PathShape and FieldShape are discussed later. Note that because ShapeCollection is a shape as well, it is possible to build a hierarchy of shapes. Especially interesting is that you can inherit a class called, let's say, ChartShape from ShapeCollection. This new class will use other shapes to build a chart and expose convenient properties that are specific to a chart. We call such a specialized shape a Custom Shape. This mechanism allows you to extend TallPDF.NET and build your own custom shape library.

Pag. 48/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Shape ContentShape

ImageShape TextShape MultilineTextShape

SimpleXhtmlShape

PageShape

BarcodeShape

PathShape

ShapeCollection

LinkShape

NoteShape

FieldShape

Figure 9-1. Partial Shape class hierarchy

9.3.

ContentShape

ContentShape is an abstract base class that adds the properties in Table 9-1 to specify rotation. Public properties Rotation RotationOffsetX, RotationOffsetY Amount of clockwise rotation in degrees. The horizontal and vertical offset of the rotation center relative to Shape.X and Shape.Y. These let you set the point to rotate around.

Table 9-1. Public properties specific to ContentShape This class organization reflects that the classes LinkShape, NoteShape and FieldShape cannot be rotated since they inherit directly from Shape.

Pag. 49/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

9.4.

ImageShape

An image shape allows you to add a raster image like a BMP or JPG bitmap. It is possible to set the width and rotate the image around its lower-left corner. By default the aspect ratio of the image is kept. In this case the Height property returns the image height as calculated from the width and the aspect ratio of the original image. If you set KeepAspectRatio to false, you can specify the height explicitly and the image will in general appear distorted.

9.5.

TextShape

TextShape lets you draw a single line of text. The X and Y properties are inherited from Shape and correspond to the lower-left corner. It is possible to set the color, font and font size of the text. Furthermore, you can rotate the text since it inherits from ContentShape. Finally, it is also possible to retrieve the extend of the text through the read-only properties Width and Height. You should access these properties after setting Font, FontSize and Text. The following table lists the public properties of TextShape. Public properties Text Width,Height TextColor, Font, FontSize, Italic, Bold Direction BoundingBox The text that is displayed. Read-only properties that reflect the size of the text with the current settings. Appearance properties.

Read direction (left-to-right or right-to-left). The bounding box after rotation is applied.

Table 9-2. Public properties specific to TextShape

9.6.

MultilineTextShape

MultilineTextShape lets you draw multiline text with mixed formatting. Just like TextParagraph it has a property Fragments. Each fragment has properties that specify both content and appearance. All fragments will be displayed concatenated and broken across lines as needed. As opposed to the TextShape you can set the Width. This determines where lines wrap. In addition you can set the Height property but this is only useful if the multiline text shape is autosized. This is the case if and only if there is exactly one fragment that has a zero font size. As opposed to most other shapes, the inherited X and Y properties coincide with the top-left corner. The property "MeasuredHeight" returns the height after all content has been rendered using the specified formatting properties and width.

9.7.

SimpleXhtmlShape

SimpleXhtmlShape specialized MultilineTextShape. Basically, you can pass XHTML data which is then transformed into the Fragments collection of the base class.

9.8.

PageShape

PageShape allows you to use a page from an existing PDF document on as a drawing primitive. The shape will retain all original data so the page can be sized without loosing any detail. To include the page at original size in the document: Create a Section with the the same page size as the original Page.

Pag. 50/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Set all margins to zero. Add a Drawing paragraph to the section and make it span the entire page. Add the PageShape to the Drawing and make it span the entire Drawing. Ofcourse, you can vary the above steps to achieve any imposition scenario.

9.9.

ShapeCollection

There is a special shape called ShapeCollection which is a group of shape objects. Because a ShapeCollection is a Shape, it allows nesting of shapes to any depth. The following table shows the properties that are specific to ShapeCollection. Public properties (typical collection members omitted) Width, Height VirtualWidth, VirtualHeight Width and Height of the shape collection with respect to the parent coordinate space. This parent is either a ShapeCollection or a Canvas. These are the width and height of the shape collection as seen by the child shapes. If these are different than Width and Height, a scaling is applied. VirtualWidth and VirtualHeight decouple the dimensions of the child shapes from the actual size of the parent shape collection. Clip the child shapes to the Width and Height.

Clip

Table 9-3. Public properties specific to ShapeCollection Each shapes collection corresponds to a rectangle. This rectangle has its lower left corner at (X,Y) and its upper-right corner at (X+Width,Y+Height). This rectangle clips the child shapes if an only if ShapeCollection.Clip is set. Each ShapeCollection collection, including the top-most, introduces a new coordinate system for all child shapes. The origin of this new coordinate system coincides with the lower-left corner of the shapes collection. The upper-right right corner of the shapes collection is seen by the child shapes as (VirtualWidth,VirtualHeight). The top-most ShapeCollection collection inherits the Width and Height of the containing Drawing class. Setting the Width and Height of the top-most ShapeCollection collection has no effect.

Figure 9-2. Nesting of shapes

9.10. Pens and Brushes


Before we discuss the PathShape and its derived classes, you should understand pens and brushes. A pen is used to draw a line or curve. A brush is used to fill areas. You can attach a pen and a brush to a PathShape. So if you add a rectangle shape to a drawing, the four lines are

Pag. 51/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

drawn using a pen and the area inside is filled using a brush. The same holds for circles, ellipses and pies. 9.10.1. Pen A pen is defined by a width, color, pattern and the cap and join styles. Width and color are obvious. The pattern is an array of integers that specifiy alternating lengths of ink followed by no-ink. The array is applied repeatedly to draw the full length of the line to which the pen is applied. You can also specifiy at which position in the array to start drawing.

Figure 9-3. The pattern of a pen is defined by a phase and a dashes-array. The cap and join styles define how line ends are connected and how open line ends are drawn, respectively. 9.10.2. Brush Brush is an abstract base class. The following concrete implementations are available: SolidBrush fills the area with a single color. This brush has a single property Color. GradientBrush is an abstract class for gradient filled areas with 2 colors: o AxialGradientBrush A brush that paints a gradient fill that changes from one color to another along a straight line. RadialGradientBrush A brush that paints a gradient fill that changes from one color to another between an inner and an outer circle.

9.11.

PathShape

PathShape allows you to build an arbitrary open or closed shape consisting of lines and bezier curves. PathShape has a property PathShapeCollection to which you can add LineShape and BezierShape objects. The Shape.X and Shape.Y properties of the segments are ignored. Instead, the end point of the previous segment is the start point of the next. The start point of the first segment is the position of the containing PathShape. PathShape uses both a pen and a brush. Figure 9-4 shows the PathShape class hierarchy.

Pag. 52/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

PathShape LineShape BezierShape RectangleShape EllipseShape ArcShape

PieShape Figure 9-4. PathShape class hierarchy 9.11.1. LineShape LineShape is a straight line. It starts at (Shape.X,Shape.Y) and it ends at LineShape.X1,LineShape.Y1). LineShape uses a pen but does not use a brush. 9.11.2. BezierShape A bezier shape has a starting point (Shape.X,Shape.Y) and an end point (BezierShape.X3,BezierShape.Y3). The start and end point are controled by (BezierShape.X1,BezierShape.Y1) and (BezierShape.X2,BezierShape.Y2), respectively. BezierShape uses a pen but does not use a brush. 9.11.3. ArcShape An arc shape is a segment of an ellipse outline. (Shape.X,Shape.Y) is the center point of this ellipse. ArcShape.Start and ArcShape.Sweep mark the starting and sweeping angle. Angle 0 corresponds to the right-most point. The sweeping angle is counter-clockwise. 360 corresponds to a full ellipse. The ellipse has a horizontal radius, Rx, and a vertical radius, Ry. ArcShape uses a pen but does not use a brush. 9.11.4. RectangleShape Draws a rectangle with a lower-left corner at (Shape.X,Shape.Y). The width and height are set using the RectangleShape properties Width and Height. RectangleShape uses both a pen and a brush. 9.11.5. PieShape PieShape specializes ArcShape: a pie is formed by drawing two straight lines from the center to the start and end point of the arc. PieShape uses both a pen and a brush. 9.11.6. EllipseShape EllipseShape draws an ellipse with its center at (Shape.X,Shape.Y) and horizontal and vertical radi of EllipseShape.Rx and EllipseShape.Ry, respectively. EllipseShape uses both a pen and a brush.

Pag. 53/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

9.12. Field Shapes


Field shapes are used to add PDF forms fields to the generated document. The field shapes can be combined with the 'normal' drawing shapes to create complete forms. For example the TextShape can be used to add the caption for the forms' field shapes, and rectangles can be used to draw groups of check boxes, etc. FieldShape is the abstract base class (derived from Shape) all other field shapes. The following paragraphs discuss the specific field shapes in turn. 9.12.1. TextFieldShape Generates a single line text entry field. By setting the 'Password' property to true, the value of the field will be hidden. 9.12.2. RadioButtonFieldShape Creates a radio button. In a radio button group (identified by the FullName) there can be only one selected radio button. 9.12.3. CheckBoxFieldShape Creates a checkbox, which can be either selected or not. 9.12.4. ListBoxFieldShape Creates a list, of which a item can be selected. 9.12.5. DropDownListFieldShape Creates a drop-down box from which an item can be selected. 9.12.6. PushButtonFieldShape Creates a button which allows to send the form content to a server, reset the form content or perform another action. When sending the form to a server several submit formats can be selected such as HTTP (get/put), FDF, PDF and XFDF. 9.12.7. SignatureFieldShape This shape adds an unsigned digital signature field to the generated document.

9.13. BarcodeShape
BarcodeShape is the abstract base of a number of barcode shapes. The class hierarchy is shown in Figure 9-5. BarcodeShape OneDimensionalBarcodeShape Code128BarcodeShape Code2of5InterleavedBarcodeShape Code3of9BarcodeShape Figure 9-5. BarcodeShape class hierarchy

Pag. 54/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

9.14. Docking
Sometimes you do not want to or you cannot specify exact positions. Instead you want shapes to be stacked or docked in some direction. The top-level class Shape has a property Dock of type DockStyle. The default value is DockStyle.None meaning that the shape is positioned at exact coordinates. Setting the Dock property to any of the other values turns on docking behavior that is similar to how Winforms controls can be docked.

Pag. 55/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

10. Context Fields


Context fields are specially formatted pieces of text that are substituted during rendering. For example, you may assign "See #l #0 on page #p" to the text property of a fragment. (#l, #0 and #p are the fields.) If the fragment has its GoToAction or Reference pointing to a table that has its Label property set to "Table" and is rendered on page 6, then the fragment appears in PDF as "See Table 3 on page 6". The following sub-sections discuss the different cases in which context fields can be used.

10.1.

Label and Caption Properties

The Label property of a Paragraph reflects the nature of the content. Typical examples are Table and Code Sample. The Caption property is normally a single line summarizing the content of the Paragraph. For example, if a table shows the telephone region numbers of say Spain, then a typical Caption would be Telephone region numbers of Spain. In TallPDF.NET you can set these properties so that you can include this text through a reference field in e.g. a cross references or a List of Tables without duplicating these values. The following code shows how to add an image and set its Caption and Label properties.
Image image = new Image( "c:\images\portraits\vincentvangogh.jpg" ); image.Label = "Figure"; image.Caption = "Self-portrait of Vincent van Gogh"; image.Width = section.PageSize.Width * 0.8; image.HorizontalAlignment = HorizontalAlignment.Center; image.KeepWithNext = true; section.Paragraphs.Add( image );

Code sample 10-1. Add an image with a label and caption in C# Next, you want to add a line below this image that is formatted like: Figure 3. Self-portrait of Vincent van Gogh. Without duplication the caption or the label values, you would use the following code:
TextParagraph text = new TextParagraph(); Fragment fragment = new Fragment("#l #0. #c"); Fragment.Reference = image; text.Fragments.Add(fragment); section.Paragraphs.Add(text);

Code sample 10-2. Add a text line below an image that uses context fields for formatting

10.2. Bookmark Property of Heading


The Bookmark property of class Heading is of type string and specifies the format of the heading as respresented in the bookmark/outline tree of the PDF reader application. The following table shows the different reference fields you may use and how they are interpreted. Reference field
#c #l #<i> #a<i>

Replaced by Caption property of the Heading object. Label property of the Heading object. The i-level heading number of the Heading object (1, 2, etc.). The i-level heading number of the Heading object formatted alphabetically, lowercase (a, b, etc.).

Pag. 56/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

#A<i>

The i-level heading number of the Heading object formatted alphabetically, uppercase (A, B, etc.). The i-level heading number of the Heading object formatted as roman numerals, lowercase (i, ii, etc.). The i-level heading number of the Heading object formatted as roman numerals, uppercase (I, II, etc.).

#i<i>

#I<i>

Table 10-1. Context fields for the Heading.Bookmark property The following code sample adds a heading and format the bookmark title.
Heading heading = new Heading(0); // level 0 heading.SpacingBefore = 8; heading.SpacingAfter = 4; heading.Label = "Chapter"; heading.Caption = "Conceptual Overview"; heading.Fragments.Add(new Fragment("#l #0 - #c", Font.HelveticaBold, 16)); heading.Bookmark = "#0. #c"; section.Paragraphs.Add(heading);

Code sample 10-3. Add a heading and format the bookmark The following table shows some specific samples. This
#l #0 - #c #0.#1 #c #I0.#1 #c #0.#a1 #c

Resolves to Chapter 3 - Advantages 2.3 Advantages II.3 Advantages 2.c Advantages

Table 10-2. Heading.Bookmark samples

10.3. Fragment with HasContextFields


This case applies to the fields in the Text property of a Fragment object that has its HasContextFields property set and has its Reference field set to null. Context field
#p #P #c<i> #l<i> #<i> #a<i>

Replaced by Current page number (1-based). Total number of pages. <i> ranges from 0 to 9. The caption of the last i-level heading. <i> ranges from 0 to 9. The label of the last heading at level i. <i> ranges from 0 to 9. The last heading number at level i (1, 2, etc.). <i> ranges from 0 to 9. The last heading number at level i formatted alphabetically, lowercase. (a, b, etc.) <i> ranges from 0 to 9. The last heading number at level i formatted alphabetically, uppercase. (A, B, etc.) <i> ranges from 0 to 9. The last heading number at level i formatted as roman numerals, lowercase. (i, ii, etc.) <i> ranges from 0 to 9. The last heading number at level i formatted as roman

#A<i>

#i<i>

#I<i>

Pag. 57/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

numerals, uppercase. (I, II, etc.) Table 10-3. Context fields for fragments that do not refer to a paragrap The following table shows some typical samples. This
Page #p Page #p of #P #l0 #0 #l0 #0.#1 #c1 #I0.#1 #c1 #0.#a1 #c1

Resolves to Page 11 Page 11 of 73 Chapter 3 Section 2.3 Bookmarks II.3 Bookmarks 2.c Bookmarks

Table 10-4. Fragment.Text samples

10.4. Fragment that Refers to a Heading


This case applies to the Text property of a Fragment of which either the Reference property or the GoToAction points to a Heading. Context field
#c #l #p #<i> #a<i>

Replaced by Caption of the heading. Label of the heading. The number of the page where the heading is rendered. The i-level heading number of the heading (1, 2, etc.). The i-level heading number of the heading formatted alphabetically, lowercase (a, b, etc.). The i-level heading number of the heading formatted alphabetically, uppercase (A, B, etc.). The i-level heading number of the heading formatted as roman numerals, lowercase (i, ii, etc.). The i-level heading number of the heading formatted as roman numerals, uppercase (I, II, etc.).

#A<i>

#i<i>

#I<i>

Table 10-5. Context fields for fragments that refer to a heading The following table shows some typical sample. This See #l #0, #c See also #l #0.#1 on page #p Resolves to See Chapter 3, Advantages See also Section 2.3 on page 11

Table 10-6. Context field samples for fragments that refer to a heading.

Pag. 58/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

10.5. Fragment that Refers to a Paragraph


This case applies to the Text property of a Fragment that has a GoToAction or Reference that points to another paragraph such as a Table or Image. Note that in that case you always specify 0 as the level since paragraphs other than Heading paragraphs do not have a level. Context field
#c #l #p #0 #a0

Replaced by Caption property of the Paragraph object. Label property of the Paragraph object. Number of the page on which the Paragraph is rendered. Label number of the Paragraph object. Label number of the Paragraph object formatted alphabetically, lowercase (a, b, etc.). Label number of the Paragraph object formatted alphabetically, uppercase (A, B, etc.). Label number of the Paragraph object formatted as roman numerals, lowercase (i, ii, etc.). Label number of the Paragraph object formatted as roman numerals, uppercase (I, II, etc.).

#A0

#i0

#I0

Table 10-7. Context fields for fragments that refer to a paragraph The following table shows some typical sample. This
#l #0 - #c See #l #0 on page #p

Resolves to Figure 3 Big losses See Table 3 on page 11

Table 10-8. Context field samples for fragments that refer to a heading.

10.6. Fragment as Part of a Heading


This case applies to the Text property of a Fragment that is part of a Heading. These fragments are treated as if they have a Reference that points to the enclosing Heading paragraph. See Heading Reference.

10.7. CrossreferenceSection
The CrossreferenceSection lets you generate sections such as a Table of Contents, a List of Tables or a List of Figures. The CrossreferenceSection was already introduced shortly in Chapter 4, Sections. Because it relies heavily on the concepts introduced in this Chapter, we will discuss it in more detail now. The mechanism of the CrossreferenceSection is based on the ComposeEntry event. This event is fired for each paragraph in the document. The event handler decides whether and how an entry has to be added to the CrossreferenceSection. E.g. if you want to generate a table of contents, then you would ignore all paragraphs that are not of type Heading. The following code sample shows how to generate a simple table of contents.

Pag. 59/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

CrossreferenceSection toc = new CrossreferenceSection(); toc.ComposeEntry += new ComposeEntryEventHandler( renderTocEntry ); doc.Sections.Add( toc );

Code sample 10-4. Add a CrossreferenceSection to a document in C# The code below references the event handler renderTocEntry. Its implementation is shown in the next code sample:
static void renderTocEntry( CrossreferenceSection section, ComposeEntryEventArgs args ) { // check to see if the paragraph is a heading if not, ignore Heading heading = args.CurrentParagraph as Heading; if ( !( args.CurrentParagraph is Heading ) ) return; // only includes level 0 and level 1 entries int level = heading.Level; if ( level > 1 ) return; // add an entry for this heading TextParagraph text = new TextParagraph(); section.Paragraphs.Add( text ); // the entry is a clickable link to the heading Fragment fragment = new Fragment(); fragment.Actions.Add( new GoToAction( args.CurrentParagraph ) ); text.Fragments.Add( fragment ); // the content of the entry is formatted using context fields switch (level) { case 0: fragment.Text = "#0 #c - #p"; fragment.FontSize = 12; break; case 1: fragment.Text = "#0.#1 #c - #p"; fragment.FontSize = 10; break; } }

Code sample 10-5. Handle the CrossreferenceSection.ComposeEntry event in C#

Pag. 60/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

11. Event-Driven Generation


It is possible to add content in an event-driven manner. While the PDF document is being generated, events are fired. In the event handlers you provide content to be rendered. Using this model, TallPDF.NET will flash out pages while generating. Consequently the memory consumption is limited to the resources of a single page. This make TallPDF.NET the ideal component for generating large documents in a heavy-load environment. By default, TallPDF.NET does not generate in event-driven mode. To generate in event-driven mde, you should call the Document.Write overload that takes an extra boolean as follows:
Document document = ...; System.Web.HttpResponse httpResponse = ...; FileStream file = ...; // NOT event-driven document.Write( file ); document.Write( file, false ); document.Write( httpResponse ); document.Write( httpResponse, false ); // event-driven document.Write( file, true ); document.Write( httpResponse, true );

Code sample 11-1. Generate in event-driven mode by selecting the Document.Write overload (C#)

11.1.

Restrictions

If you choose to generate the PDF document in an event-driven manner, you should be aware of a number of restrictions. These restrictions are a consequence of the forward-only, non-cached nature of the generation process. They should be considered as a trade-off between functionality and speed/memory footprint. Cell.ColSpan is ignored. If a cell should span multiple columns, set its PreferredWidth property to a larger value so that is spans multiple columns. Cell.FitToContent is ignored. You must set the PreferredWidth property to a predefined value. Each section starts on a new page. The Section.StartOnNewPage property is ignored. If you want to switch to a different page layout, you can do this by handling the QueryPageSettings event which is fired for each page. If you want to switch to different headers/footers, you can do this by handling the StartPage and EndPage events which are fired for each page. You can not cross-reference paragraphs from fragments. Context fields are not resolved. You cannot use the CrossreferenceSection class to generate a table of contents or a list of figures/tables.

11.2.
Event

Section Events
Fired when Just before a new page will be added Do this in your handler Provide the page settings such as the size of the different page boxes (media

The following events are fired by the Section class. QueryPageSettings

Pag. 61/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

box, bleed box, etc.). StartPage EndPage Table 11-1. Events fired by Section Just after a new page has been added Just before a new page will be added. Define areas on this page. Add some final content.

11.3.
Event

ParagraphCollection Events
Fired when Just before the first paragraph on the current page is added. New content is required. Do this in your handler Provide a paragraph that should be the first on the current page. Provide a new paragraph.

The following events are fired by the ParagraphCollection class. PrintFirstParagraph

PrintParagraph

Table 11-2. Events fired by ParagraphCollection

11.4.
Event

Paragraph Events
Fired when Before a paragraph is broken across pages. Before a paragraph continues on the next page. After a paragraph has been fully rendered. After a paragraph has been rolled back due to a text flow contraint such as keep-with-next. After a paragraph has been tranformed. E.g. due to a vertical alignment setting of a table cell. Do this in your handler Application specific. Application specific.

The following events are fired by the Paragraph class. BreakParagraph ContinueParagraph

EndParagraph RollbackParagraph

Application specific. Application specific.

TransformParagraph

Application specific.

Table 11-3. Events fired by Paragraph

11.5.
Event

TextParagraph Events
Fired when When a text line needs to be broken. Do this in your handler Specifiy where to break the line. If you do not handle this event, lines are broken at whitespace occurrence which

The following events are fired by the TextParagraph class. LineBreak

Pag. 62/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

is perfectly reasonable. Table 11-4. Events fired by TextParagraph

11.6.
Event

RowCollection Events
Fired when Just before the first row on the current page is added to the current table. Note that this even is fired n times if the table spans n pages. A new row is required. Do this in your handler Provide a row that should be the first on the current page.

The following events are fired by the RowCollection class. PrintFirstRow

PrintRow

Provide a new row.

Table 11-5. Events fired by RowCollection

11.7.

Example: Firehose Generation from SQL

Generating a PDF document from data stored inside a SQL database can very well be done in an event-driven manner. This way you can fully profit from the performance benefits of the forwardonly SqlDataReader. 11.7.1. Create a SqlDataReader A SqlDataReader provides a forward-only, read-only pointer over data retrieved from a SQL database. The following code sample shows you how to create a SqlDataReader instance. (The pubs database is installed together with the .NET Framework SDK.)
SqlConnection connection = new SqlConnection( @"server=(local)\NetSDK;database=pubs;Trusted_Connection=yes"); SqlCommand command = new SqlCommand(@"select * from Authors", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader();

Code sample 11-2. Create a SqlDataReader in C# 11.7.2. Prepare Table.Rows The next step is to setup the Table.Rows class for generating rows that correspond to the records in the database. First pass the reader to the Data member of the RowCollection class. The Data member allows you to associate any data with the RowCollection collection. This data will be available in the event handler that will provide the rows. Next, the event handlers are connected to the RowCollection class.
Table table = new Table(); table.Rows.Data = reader; table.Rows.PrintRow += new PrintRowEventHandler(PrintRow); table.Rows.PrintFirstRow += new PrintRowEventHandler(PrintFirstRow);

Code sample 11-3. Prepare Table.Rows in C# 11.7.3. Handle PrintRow Event When the Document.Write method is called with the pull argument set to true, the event handler PrintRow will be called somewhere during the generation process. The following shows how to pull the content from the SqlDataReader and pass it on to the generation process.

Pag. 63/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

bool PrintRow( object sender, PrintRowEventArgs args ) { SqlDataReader reader = args.Data as SqlDataReader; if ( null != reader && reader.Read() ) { args.Row = new Row(); addCell( args.Row, reader.GetValue(2).ToString() + " " + reader.GetValue(1).ToString() ); addCell( args.Row, reader.GetValue(4).ToString() ); addCell( args.Row, reader.GetValue(5).ToString() ); args.MoreContent = true; // we have more content } args.MoreContent = false; // no more content }

Code sample 11-4. Handle PrintRow Event in C# addCell is a helper method that adds a cell to the row instance and is rather trivial. 11.7.4. Handle PrintFirstRow Event The PrintFirstRow event is fired to allow the handler to add one or more header rows. This event is fired for each page that the table spans. The following shows how to provide a single header row.
void PrintFirstRow(object sender, PrintRowEventArgs args) { args.Row = new Row(); addCell(args.Row, "Author"); addCell(args.Row, "Address"); addCell(args.Row, "City"); // Only one line, no more content args.MoreContent = false; }

Code sample 11-5. Handle PrintFirstRow Event in C# 11.7.5. Finalize After generation, the connection to the database is closed:
try { Document document = new Document(); //... //... document.Write( reader, true ); } finally { //... if ( null != connection ) connection.Close(); }

Code sample 11-6. After generation, close the SQL connection

Pag. 64/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

12. Generate PDF from XML


The central idea of TallPDF.NET is that you can build an instance of a TallPDF Document and that you can save that instance to PDF. Instead of building a Document instance programmatically, you can also load it entirely or in parts from XML. There is no difference between a document instance loaded from XML and one that has been constructed programmatically. So, in addition to building PDF programmatically, you can also generate PDF from XML. For this we have defined a proprietary XML format that reflects the programmatic object model in a very obvious way. NOTE: The evaluation download includes the TallPDF.NET XML schema as an xsd document. Section 2.1.7 describes how to use this XSD to enable IntelliSense in Visual Studio .NET while editing TallPDF.NET XML. The following is a simple XML document that conforms to the TallPDF.NET format:
<document xmlns="http://www.tallcomponents.com/schemas/tallpdf/v3"> <section> <paragraph type="textparagraph"> <fragment>Hello World</fragment> </paragraph> </section> </document>

Code sample 12-1. Hello World TallPDF.NET XML You invoke the conversion of this XML to PDF as follows:
FileStream file = new FileStream("out.pdf", FileMode.Create); XmlDocument xml = new XmlDocument(); xml.Load("helloworld.xml"); Document document = new Document(); document.Write(new XmlNodeReader(xml.DocumentElement), file);

Code sample 12-2. Invoke the conversion of XML to PDF in C# TallPDF.NET does not only read from an XmlElement; it also reads from any XmlReader implementation. The XmlReader is the no-caching, forward-only alternative. See also Working with XSL. Note that you can not only read the top-level class 'Document' from XML, you can read each TallPDF.NET layout class from XML. This allows you to mix a programmatic and XML approach. Because our XML reader do not expect an XmlDocument you can start reading at any location in a given XML document.

12.1.

XML Format Specification

The TallPDF.NET XML format can be derived from the definitions of the TallPDF.NET layout classes using a number of rules. This is not by coincidence; all TallPDF.NET classes inherit from a common class, TallComponents.PDF.Layout.Object, where the Read method is implemented. This method transforms XML to TallPDF.NET objects using the reflection mechanisms of .NET. Note that this guarantees a 100% correspondence between the programmatic and XML approach. This section discusses the rules that map the TallPDF.NET classes on XML. This section assumes that you understand the TallPDF.NET document object model and have a basic understanding of XML. The mapping is case-insensitive. We distinguish the following XML node types: Top Element

Pag. 65/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Child Elements Attributes Text Nodes 12.1.1. Top Element The top element is the element that is passed to the read method of the TallPDF.NET object. The top element is not necessarily the document element, but it may be. The name of the top element can be anything . 12.1.2. Child Element Child elements correspond to public, writeable properties of the class that corresponds to the parent element. We should distinguish between value (e.g. Drawing.Width), object (e.g. Document.OddFooter) and collection properties (e.g. Table.Rows). These case are discussed separately. 12.1.3. Value Type Properties Properties that have a value type such as are Fragment.FontSize (double) or Section.StartOnNewPage (bool) are specified by an attribute on the corresponding element. The name of the property matches the name of the attribute in XML. Example:
<fragment fontsize="10"/>

Code sample 12-3. Assign a value property Note that TallPDF.NET XML is case insensitive when it comes to element names and attribute names. Properties of type double (widths, heights, margins, padding etc.) can be specified in any unit supported by the Unit class. Internally, the value will be converted to points and assigned to the property. See Unit.Parse in the Type Reference for a complete list of all supported units. Example:
<!-- A4 Landscape --><pagesize width="297mm" height="210mm"/>

Code sample 12-4. Assign a double value using a unit specifier Objects like Font that have named static properties or fields of the same type can be assigned by entering the name of the static property or field.value. Example:
<fragment textcolor="AquaBlue">

Code sample 12-5. Assign a value using the names of a static property of static field 12.1.4. Reference Type Properties Properties that have a reference type such as Cell.Border are usually represented by a child element as opposed to an attribute. The name of the element matches the the name of the property. Example:
<cell> <border> <top width="1" color="Black"/> </border> </cell>

Code sample 12-6. Properties of reference type are specified as child elements An exception is a property of reference type that has static properties or static fields of the same type. In that case, you can specify the property as an attribute. Example:

Pag. 66/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

<fragment font="Helvetica"/>

Code sample 12-7. Fragment.Font specified as an XML attribute 12.1.5. Special Attribute "type" Some properties can be assigned values of different types. For example, Border.Background is of the type Brush. Brush itself is an abstract that has specializations such as SolidBrush. In that case, you must explicitly specify the type of object you wish to assign.Example:
<border> <background type="solidbrush" color="red"/> </border>

Code sample 12-8. Assign an instance of SolidBrush to a property of type Brush In this case, a new instance of SolidBrush is assigned to Border.Background and its Color property is set to Red. For TallPDF.NET you can simply use the class name as opposed to the fully qualified name. If you are using your own classes that derive from TallPDF.NET classes, then you will need to specify the fully qualified name. Note that fully qualified class names are case sensitive in TallPDF.NET XML. 12.1.6. Collection Properties The TallPDF.NET document object model has several collection properties such as Section.Paragraphs, Table.Rows and TextParagraph.Fragments. It is not required to include these collections as elements in the XML. TallPDF.NET will automatically look for the collection property that can contain the child element as an item. The name of the child element matches the singular form of the name of the collection property. Example:
<table> <!-- no need to include rows --> <row> <!-- no need to include cells <cell> <!-- paragraphs go here... </cell> </row> <row> <!-- no need to include cells <cell> <!-- paragraphs go here... </cell> </row> </table>

--> -->

--> -->

Code sample 12-9. Collection properties are implicit in XML In the previous example, the property name is equal to the name of the type. If this is not the case, you must specify the type explicitly as in the next example.

Pag. 67/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

<section> <!-- add a new instance of type TextParagraph to Section.Paragraphs --> <paragraph type="textparagraph"> <!-- more --> </paragraph> <!-- add a new instance of type Table to Section.Paragraphs --> <paragraph type="table"> <!-- more --> </paragraph> </section>

Code sample 12-10. Some collection properties require an explicit type attribute The name of the element indicates the collection that the object will be added to. Heading for example has 2 collection properties, Fragments and NumberFragments, both of type Fragment. Example:
<paragraph type="heading" level="0" label="Chapter" caption="XML"> <!-- add new Fragment instance to Heading.NumberFragments --> <numberfragment text="#l #0"/> <!-- add new Fragment instance to Heading.Fragments --> <fragment text="#c"/> </paragraph>

Code sample 12-11. Multiple collection properties of the same type 12.1.7. Enum Property If the property is of type enumeration, then the attribute value should match one of the enum fields. For example:
<pen linecapstyle="butt"/>

Code sample 12-12. Specify an enum property as an XML attribute 12.1.8. Text Properties Properties of type string that are called Text are treated somewhat differently. In addition to specifying a string property simply as an attribute, a string property can also be specified as a text node. This allows you to span multiple lines and to use the CDATA construct in order to include characters that have a special meaning in XML. Example:
<fragment> <![CDATA[ Properties of type string named Text are treated specially. In addition to using an attribute named text, you can specify it as a text node. This is a natural choice since this property is typically set to a large piece of text, spanning multiple lines. Furthermore, it makes it possible to use the CDATA construct. This allows us to use characters reserved by XML like > and & without escaping them. This is especially relevant when the text is read from an external source. ]]> </fragment>

Code sample 12-13. Properties of type System.String can be specified as text nodes

12.2. Working with XSL


TallPDF.NET defines its own proprietary format. In general you will have XML data in some other forma , e.g. as generated by the FOR XML statement of SQL. In that case you will write an XSL(T) style sheet that transforms your XML to XML that is understood by TallPDF.NET. Normally, you write such a transformation only once per XML schema.

Pag. 68/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

The following snippets show, respectively, a custom XML document, an XSL document that translates it to TallPDF.NET XML and finally a C# code that invokes the transformation. Note that this document does not discuss writing XSL documents since this is a general technique independent of our component.
<?xml version="1.0" encoding="utf-8"?> <Customers> <Customer id="1"> <Name>Chris Sharp</Name> </Customer> <Customer id="2"> <Name>Mike Jones</Name> </Customer> </Customers>

Code sample 12-14. Application specific XML The following XSL transforms the above XML to TallPDF.NET XML.
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.tallcomponents.com/schemas/tallpdf/v3"> <xsl:output method="xml" encoding="utf-8"/> <xsl:template match="/"> <!-- the document is declared at root level --> <document> <section> <!-- Static content: this will appear in every document regardless of the data --> <paragraph type="textparagraph"> <fragment font="helveticabold" fontsize="14"> Simple XSL Transformation </fragment> </paragraph> <!-- Dynamic content: go through the data and render content from that --> <xsl:apply-templates select="/Customers/Customer"/> </section> </document> </xsl:template> <xsl:template match="/Customers/Customer"> <!-- Dynamic content: render a paragraph for each customer --> <paragraph type="textparagraph"> <fragment font="helveticabold" fontsize="10"> <xsl:value-of select="@id"/>. </fragment> <fragment font="helvetica" fontsize="10"> <xsl:value-of select="Name"/> </fragment> </paragraph> </xsl:template> </xsl:stylesheet>

Code sample 12-15. XSL transforming XML to TallPDF.NET XML The following code invokes the transformation in order to generate PDF.

Pag. 69/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

#if DOTNET2 Stream converted = new MemoryStream(); // Load the XML XmlReader xml = new XmlTextReader("data.xml"); // Load XSL XslCompiledTransform xsl = new XslCompiledTransform(); xsl.Load("transform.xsl"); // Do the transformation xsl.Transform(xml, null, converted); // Set back the position pointer in the stream to the beginning converted.Position = 0; XmlReader reader = new XmlTextReader(converted); #else // Load the XML XmlDocument xml = new XmlDocument(); xml.Load("data.xml"); // Load XSL XslTransform xsl = new XslTransform(); xsl.Load("transform.xsl"); // Do the transformation XmlReader reader = xsl.Transform(xml, null); #endif // Construct the PDF document from the transformed XML Document doc = new Document(); doc.Read(reader); // Write the PDF to disk using (FileStream file = new FileStream( "out.pdf", FileMode.Create, FileAccess.ReadWrite)) { doc.Write(file); }

Code sample 12-16. Invoke the XSL transformation in C#

12.3. Special Characters


A number of characters like the ampersand (&), less-than (<) and greater-than (>) are reserved in XML. If you want to include these in your generated PDF, you have the following options depending on where the special character occurs. The following is invalid:
<paragraph type="heading" bookmark="Chapter #0 <#c>"/>

It should be rewritten as:


<paragraph type="heading" bookmark="Chapter #0 &lt;#c&gt;"/>

Properties of type string can be specified as a text node. Because of this you can use the CDATA construct in addition to character-escaping. The following is invalid:

Pag. 70/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

<fragment> it is true that 10 < 12 </fragment>

It should be rewritten as:


<fragment> <![CDATA[ it is true that 10 < 12 ]]> </fragment>

12.4. XML Parse Exceptions


During conversion of XML to PDF, a number of exceptions can be raised due to errors in the XML file or due to non-conformance of extended classes (see Code-Behind XML Elements). This sections lists all those exceptions and shows examples of typical mistakes. Note that these exceptions exist in addition to the Microsoft .NET Framework exceptions. 12.4.1. AttibuteNotFoundException This exception is raised when an XML element has an attribute that does not correspond to a property. Invalid XML
<document> <section color="Red"> <paragraph type="textparagraph"> <fragment text="Hello World"/> </paragraph> </section> </document>

Exception.Message Type TallComponents.PDF.Layout.Section does not have a public property called color.

Code sample 12-17. AttibuteNotFoundException 12.4.2. ElementNotFoundException This exception is raised when an XML element has a child element that does not correspond to a property. Invalid XML
<document> <section> <bindingsetting/> <paragraph type="textparagraph"> <fragment text="Hello World"> </fragment> </paragraph> </section> </document>

Exception.Message Type TallComponents.PDF.Layout.Section does not have a public property called bindingsetting.

Code sample 12-18. ElementNotFoundException 12.4.3. EnumConstantNotFoundException This exception is raised when an attribute corresponds to an enumeration property but the value of the attribute does not correspond to any of the enumeration constants.

Pag. 71/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Invalid XML
<document> <section> <paragraph type="textparagraph" horizontalalignment="top"> <fragment text="Hello World"/> </paragraph> </section> </document>

Exception.Message Enumeration TallComponents.PDF.Layout.Paragraph +HorizontalAlignment does not have a constant called top.

Code sample 12-19. EnumConstantNotFoundException 12.4.4. PropertyCannotParseException This exception is raised when an attribute corresponds to a property but the value of the attribute cannot be parsed into a valid property value. Invalid XML
<document> <section oddfooter="pagenumber"> <paragraph type="textparagraph"> <fragment text="Hello World"/> </paragraph> </section> </document>

Exception.Message Type TallComponents.PDF.Layout.Footer does not have a Parse method, nor does it have a public static (shared) property called pagenumber.

Code sample 12-20. PropertyCannotParseException 12.4.5. MissingReadMethodException This exception is raised when a child element cannot be read from XML because it does not have a public Read method that takes XmlReader as an argument. Invalid XML
<document> <section> <paragraph type="textparagraph"> <fragment text="Hello World"> <textcolor> </textcolor> </fragment> </paragraph> </section> </document>

Exception.Message Type System.Drawing.Color does not have a public method called Read that takes an XmlReader as an argument.

Code sample 12-21. MissingReadMethodException 12.4.6. MissingAddMethodException This exception is raised when a child element can not be added to a collection because the latter does not have an Add method that takes the element as an argument.

Pag. 72/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Invalid XML
<document> <section> <paragraph type="fragment"> <fragment text="Hello World"/> </paragraph> </section> </document>

Exception.Message Type TallComponents.PDF.Layout.Paragraphs does not have a public method called Add that takes a TallComponents.PDF.Layout.Fragment as an argument.

Code sample 12-22. MissingAddMethodException

Pag. 73/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

13. Extend TallPDF.NET


TallPDF.NET exposes its functionality through a set of cohesive .NET classes,You can extend all these classes by inheriting from them. These specialization can then be used both programmatically and from XML.

13.1.

Inherit from a TallPDF.NET Class

The following class definition shows how you can create a special Heading called H1 that encapsulates all settings that are specific to level-1 headings.
using TallComponents.PDF.Layout.Paragraphs; namespace MyCompany.TallPDF { public class H1 : Heading { public H1() : base(0) { Label = "Chapter"; Bookmark = "#l #0 #c"; Fragments.Add(new Fragment("#l #0 #c",Font.HelveticaBold, 14)); } public string Text { get { return Caption; } set { Caption = value; } } } }

Code sample 13-1. Create a specialized Heading The following client code shows how H1 would typically be used:
Document document = new Document(); Section section = document.Sections.Add(); H1 h1 = new H1(); h1.Text = "Extend TallPDF.NET"; section.Add(h1);

Code sample 13-2. Use the specialized Heading

13.2. Use Specialized Class in XML


Given the specialized class H1, you can now use it in XML as follows:
<document> <section> <paragraph type="MyCompany.TallPDF.H1"> Hello Extended World </paragraph> </section> </document>

Code sample 13-3. Use specialized class in XML Note that the content of the text node is assigned to the Text property of H1. See also Section 12.1.8, Text Properties.

Pag. 74/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

NOTE: It is necessary to force the CLR to load the assembly that defines H1 before you do the conversion. Otherwise, the CLR will not be able to create a new instance of your custom type through the .NET reflection mechanisms. You can do this by referring a type inside this assembly or by loading the assembly explicitly by calling Assembly.LoadFrom("path to my assembly.dll" ).

Pag. 75/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

14. Actions
In order to make a document responsive to user input, you can add actions. These actions are provided through the Action class and its specializations. The following actions are supported by TallPDF.NET: GoToAction: Jump to a paragraph in the same document or to a page in the same or another PDF document JavaScriptAction: Perform scripted operations against the document (Professional edition only) UriAction:Jump to a URI FormAction: Submit or clear form data Actions can be assigned to the following properties: Document.AfterOpen: Executed after the document has been opened Document.BeforePrint Document.AfterPrint Document.BeforeSave Document.AfterSave Document.BeforeClose LinkShape,MouseUpActions PushButtonFieldShape.MouseUpActions Fragment.Actions Paragraph.Actions

14.1.

GoToAction

The GoToAction jumps to a Paragraph inside the current document or to a page in the current or external PDF document. The destination is set by assigning a Destination object to the GoToAction.Destination property. The following types of Destination exist. 14.1.1. ParagraphDestination The ParagraphDestination points to another paragraph in the same document. The referenced paragraph may either be specifed by object reference or by using the an identifier (this is useful when using XML to define the document). 14.1.2. InternalPageDestination The InternalPageDestination points to a page inside the same document. The page is specified by index. Due to the flow layout model, the exact page where content will be rendered is not know beforehand so the usefullness of this destination is limited. 14.1.3. RemoteDestination The RemoteDestination points to a page in an external PDF document. It is specifed by the path of the PDF document and a page index. You can also specify additional settings such as zoom factor and the exact scroll position after jumping to the location.

14.2. UriAction
The UriAction jumps to a given URI. This is typically a web site address.

Pag. 76/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

14.3. FormAction
FormAction is the abstract base class of the following actions:

ResetFormAction: reset all form fields in the document to their default value SubmitFormAction: Submits the form data to a given destination. The URL and submit
options such as the format can be specified as properties of this action.

14.4. JavaScriptAction
This action execute JavaScript against the current document. A PDF document is fully scriptable on the client side. Typical usage includes setting a text field value after clicking a button or showing/hiding a field after entering/leaving a form field. Here is the full JavaScript reference. 14.4.1. Document Level JavaScript It is possible to define document-level JavaScript. You typically define functions and constants at this level. You can then call and use these from JavaScriptAction objects.

Pag. 77/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

15. Convert RTF to PDF


You can use the RtfParagraph to include RTF in the generated PDF document. Because this class inherits from Paragraph you can mix it with other content elements and include it in the main content, table cells, headers, footers and areas. Elements in the original document that are preserved are: Formatted text (font, decoration, formatting, size) Tables Images Not supported features are: Nested tables Page headers/footers Reference fields (page numbers, cross references) Drawing objects (line drawings) Text flow around objects (images) Floating objects The following code snippets show how to use the RtfParagraph.
using TallComponents.PDF.Layout; using TallComponents.PDF.Layout.Paragraphs; : public void ConvertRTF2PDF(string rtfFile) { Document doc = new Document(); Section sec = doc.Sections.Add(); RtfParagraph rtf = new RtfParagraph(); rtf.Path = rtfFile; using (FileStream file = new FileStream( rtfFile + ".pdf", FileMode.Create )) { doc.Write( file ); } }

Code sample 15-1. Using the RtfParagraph in C#


<document> <section> <paragraph type="rtfparagraph" path="YourPathHere.rtf"/> </section> </document>

Code sample 15-2. Using the RtfParagraph in XML Alternatively, the content of the RTF file can be set as a stream or as string. This is convenient when reading the content from a dedicated source such as a database, or remote service.

15.1.

Fonts

As opposed to the rest of TallPDF.NET, fonts in RTF are specified by the font family name. The Windows Fonts folder will be scanned by TallPDF.NET. Consequently all fonts available to Windows, are also available to the RtfParagraph.

Pag. 78/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

When running in a context such as ASP.NET it might not be allowed to access the Windows Fonts folder due to security restrictions. In that case you can set the FontPath-property to point to an accessible folder containing True-type fonts.

15.2. Restrictions
The RtfParagraph supports basic RTF 1.3 only. So extended RTF formats such as Microsoft Word are not supported. RtfParagraph inherits from ParagraphCollection. After parsing the RTf, this collection is filled with paragraph instances that reflect the RTF. You should not post-process these instances.

Pag. 79/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

16. Convert XHTML to PDF


As of version 3.0 TallPDF.NET has limited XHTML + CSS2 import support. This is available through the XhtmlParagraph class. XhtmlParagraph is a specialization of paragraph. Therefore, all members of paragraph are members of XhtmlParagraph as well. You can add it to a section, table cell, header or footer. The following code snippets show how to use the XhtmlParagraph.
Document document = new Document(); Section section = document.Sections.Add(); // create an XhtmlParagraph with static content XhtmlParagraph xhtml1 = new XhtmlParagraph(); Xhtml1.Text = "<html><body><b><i>Hello world</i></b></body></html>"; section.Paragraphs.Add(xhtml1); // create an XhtmlParagraph from a URL XhtmlParagraph xhtml2 = new XhtmlParagraph(); Xhtml2.Path = @"http://www.yourserver.com/xhtml/path/file.htm"; section.Paragraphs.Add(xhtml2); // convert to PDF and save using (FileStream fs = new FileStream("out.pdf", FileMode.Create)) { document.Write(fs); }

Code sample 16-1. Import XHTML in C# 16.1.1. External resources Often resources like images or CSS definitions have to be included. When the xhtml document is loaded from a file/web location, the path of the xhtml document is used as a base path. To be able to specify a base path when using the static/stream input, the 'BasePath' property has been introduced. All resources will be loaded (relative) to this location. Setting this property overrules the xhtml-document path when using the file/web-location. The following XML-document definition generates a PDF-document using some xhtml content, in which a image is loaded from a remote destination.
<document> <section> <paragraph type="xhtmlparagraph" basepath="http://www.tallcomponents.com"> <html> <body> <h1>Hello world</h1> <p>Loading image:</p> <img src="/img/tc-logo.gif"/> </body> </html> </paragraph> </section> </document>

Code sample 16-2. Include XHTML in TallPDF.NET XML

Pag. 80/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

16.2. XHTML vs HTML


The XhtmlParagraph expects XHTML as opposed to HTML. While XHTML is well-formed XML, HTML generally is not. Common differences are: All elements must be closed. Use either <b>...</b> or <img... />). Opening and closing tags must be correctly balanced:
<b>bold <i> bolditalic</b>italic</i>

should be:
<b>bold <i> bolditalic</i></b><i>italic</i>

All attribute values have to be enclosed in quotes:


<table border=3 width=300>

should be
<table border="3" width="300">

16.3. Fonts
As opposed to the rest of TallPDF.NET, fonts have to be specified in the XhtmlParagraph (XHTMLcontent) using the font family name. The Windows Fonts folder will be scanned by TallPDF.NET. Consequently all fonts available to Windows, are also available to the XhtmlParagraph. When running in a context such as ASP.NET it might not be allowed to access the Windows Fonts folder due to security restrictions. In that case you can set the FontPath-property to point to an accessible folder containing True-type fonts.

16.4. Forms
XhtmlParagraph also converts input elements to PDF form elements. The following form elements ("<input type="">) are currently supported:
TEXT: Single line text field PASSWORD: Single line password field CHECKBOX: On/off controlRADIO: Mutual exclusive selection SUBMIT: Send the content to an end-point RESET: Clear the form and reset all fields to their initial values TEXTAREA:-Mulitline text field

The following restrictions apply: Inline form elements are not supported. Place the form elements in a table to allow similar positioning. There can be only one form per document. Elements HIDDEN and BUTTON are not supported.

16.5. Supported XHTML Elements


Table 16-1 lists the support status of each XHTML element. The following status symbols are used: : Fully supported

x
P Tag

: Not support and will not be supported : Not yet supported : Partially supported Status Description

Pag. 81/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Tag
<!--...--> <!DOCTYPE> <a> <abbr> <acronym> <address> <applet> <area> <b> <base>

Status Description Defines a comment X Defines the document type Defines an anchor X X Defines an abbreviation Defines an acronym Defines an address element X X

Deprecated. Defines an applet


Defines an area inside an image map Defines bold text

This property works on Uri's, images and CSS imports that are no absolute reference (do not start with http(s)://). This property should be a absolute reference as the PDF document has no static base path...
<basefont> <bdo> <big> <blockquote> <body <br> <button>

Defines a base URL for all the links in a page.

Deprecated. Defines a base font


Defines the direction of text display Defines big text Defines a long quotation Defines the body element Inserts a single line break

P -

Defines a push button

Images on the button are not yet supported.


<caption> <center> <cite> <code> <col> <colgroup> <dd> <del> <dir>

Defines a table caption

Deprecated. Defines centered text


Defines a citation Defines computer code text Defines attributes for table columns Defines groups of table columns Defines a definition description Defines deleted text

Deprecated. Defines a directory list

Pag. 82/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Tag
<div>

Status Description P Defines a section in a document

Floating <div> not supported.


<dfn> <dl> <dt> <em> <fieldset> <font> <form>

Defines a definition term Defines a definition list Defines a definition term Defines emphasized (italic) text X Defines a fieldset

Deprecated. Defines text font, size, and color


P Defines a form

Only one form in a document restriction as input types are not grouped. Please read the 'Form' chapter for further details.
<frame> <frameset> <h1> to <h6> <head> <hr>

X X

Defines a sub window (a frame) Defines a set of frames Defines header 1 to header 6 Defines information about the document

Defines a horizontal rule

The length of the rule is not honored/applied correctly.


Defines a html document Defines italic text

<html> <i> <iframe> <img>

X P P

Defines an inline sub window (frame) Defines an image

Inline images not supported.


<input>

Defines an input field

Button and Hidden fields are not supported. Inline elements not supported. To allow text beside the field put these in a table.
<ins> <isindex> <kbd> <label> <legend> <li>

Defines inserted text -

Deprecated. Defines a single-line input field


Defines keyboard text

Defines a label for a form control Defines a title in a fieldset Defines a list item

Pag. 83/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Tag
<link>

Status Description P X Defines a resource reference

Only the StyleSheet type is supported.


<map> <menu> <meta> <noframes> <noscript> <object> <ol> <optgroup> <option> <p> <param> <pre> <q> <s> <samp> <script> <select> <small> <span> <strike> <strong> <style> <sub> <sup> <table> <tbody> <td>

Defines an image map

Deprecated. Defines a menu list


X X Defines meta information Defines a noframe section Defines a noscript section Defines an embedded object Defines an ordered list X Defines an option group Defines an option in a drop-down list Defines a paragraph X Defines a parameter for an object Defines preformatted text Defines a short quotation

Deprecated. Defines strikethrough text


Defines sample computer code X Defines a script Defines a selectable list Defines small text Defines a section in a document

Deprecated. Defines strikethrough text


Defines strong text Defines a style definition Defines subscripted text Defines superscripted text Defines a table Defines a table body Defines a table cell

Pag. 84/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Tag
<textarea> <tfoot>

Status Description Defines a text area P

Only appended at the end of the table, not repeated on every page end.
Defines a table header Defines a table header

Defines a table footer

<th> <thead> <title> <tr> <tt> <u> <ul> <var> <xmp>

Defines the document title Defines a table row Defines teletype text

Deprecated. Defines underlined text


Defines an unordered list (Bullet) Defines a variable

Deprecated. Defines preformatted text

Table 16-1 Supported XHTML elements

16.6. Restrictions
Some inline style tags ("style=" -properties) and external style tags (from CSS style sheet) are not honored. CSS context selectors are not supported. Table layout behaves some different from HTML. We recommend specifying cell widths in absolute units (don't use percentages). Only a single form per document is supported. Layers (absolutely positioned or floating <div> tags) are not supported. Javascript and Dynamic content (HTML generated through JavaScript, events etc.) are not supported. The <tfoot> tag is not supported.

Pag. 85/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

17. Upgrading from TallPDF.NET 2.0


TallPDF.NET 3.0 is not code compatible with TallPDF.NET 2.0. Changes have been made to make the object model more intuitive and make the component more compliant with Microsofts Design Guidelines for Developing Class Libraries. For TallPDF.NET 2.0 customers migrating to TallPDF.NET 3.0 this means some code modifications are required. This document helps you make these changes.

17.1.

First Steps

Before starting to upgrade ensure to have a backup of your current project. Next remove the bin (binary) and obj (object) folders from your project folder (these will be automatically regenerated during the build). This is best practice as sometimes resources (executables or libraries) are locked by a web server or active tool. Visual studio will not be able to update the library during the build in that case. (Usually no problem as the correct version is already in place) To start upgrading code from 2.0 to 3.0, you should begin by removing the reference to the TallPDF.NET 2.0 (tallpdf.dll) assembly and add a reference to the TallPDF.NET 3.0 assembly (TallComponents.PDF.Layout.dll). Make sure you use the correct edition and build for your project. TallPDF.NET 3.0 is available in Standard and Professional editions, compiled for .NET 1.1 and .NET 2.0. We recommend switching to .NET 2.0 if possible. ASP note: Delete the tallpdf.dll from the bin-folder when you migrate your project. Leaving both the old (=TallPDF.NET 2.0) and adding the new (=TallPDF.NET 3.0) libraries in the bin-folder will result in a failing configuration. The system will not know what library to use when shared code is used. This is an issue as both versions share the same base namespace (TallComponents.PDF.Layout).

17.2. New Namespaces


In TallPDF.NET 3.0, all namespaces start with TallComponents.PDF.Layout, except namespace TallComponents.PDF.Licensing which holds the licensing related classes. In TallPDF.NET 3.0, new namespaces have been introduced in order to achieve a better organization of classes. The table below summerizes these namespace. Namespace TallComponents.PDF.Layout TallComponents.PDF.Layout.Actions TallComponents.PDF.Layout.Brushes TallComponents.PDF.Layout.Colors TallComponents.PDF.Layout.Css TallComponents.PDF.Layout.Fonts TallComponents.PDF.Layout.JavaScript Description All types that do not fall in any or multiple of the categories below. All action classes and related types. All brush classes. Base class Color plus derived color classes such as RgbColor and CmykColor. Holds class CssStyleSheet only. Holds class Font only. JavaScript class plus related types. Used to build JavaScript actions and document-level JavaScript.

Pag. 86/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

TallComponents.PDF.Layout.Metadata TallComponents.PDF.Layout.Navigation TallComponents.PDF.Layout.Paragraphs TallComponents.PDF.Layout.Pens TallComponents.PDF.Layout.Security TallComponents.PDF.Layout.Shapes TallComponents.PDF.Layout.Shapes.Annotations TallComponents.PDF.Layout.Shapes.Barcodes TallComponents.PDF.Layout.Shapes.Fields Table 17-1. All TallPDF.NET 3.0 namespaces

Classes that allows you to embed metadata in the generated PDF. Destination classes, ViewerPreferences and related types. All Paragraph related classes. Class Pen and DashPattern and related enums. Base class Security and derived class PasswordSecurity. All class related to shapes that do not fall in the following sub namespaces. Classes LinkShape and NoteShape and related types. Shapes for drawing barcodes. Shapes for adding form fields.

17.3. Renamed Classes


The following table summarizes renamed classes (prefix TallComponents.PDF.Layout has been omitted). Old Layout.ListOfParagraphs Layout.Paragraphs Layout.Sections Layout.Shapes Layout.Fragments Layout.Rows Layout.Cells Layout.Security Table 17-2. Renamed classes New Layout.CrossreferenceSection Layout.Paragraphs.ParagraphCollection Layout.SectionCollection Layout.Shapes.ShapeCollection Layout.Paragraphs.FragmentCollection Layout.Paragraphs.RowCollection Layout.Paragraphs.CellCollection Layout.Security.PasswordSecurity

17.4.
Old

Renamed Enumerations
New Paragraph.HorizontalAlignment (not nested) Navigation.PageMode (not nested) Navigation.PageLayout (not nested) Compression.Jpeg (enum field) Compression.Zip (enum field)

The following table summarizes renamed enumerations and enumeration fields. Paragraph.HAlignment (nested) ViewerPreferences.PageMode (nested) ViewerPreferences.PageLayout (nested) Compression.DCT (enum field) Compression.Flate (enum field)

Pag. 87/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Table 17-3. Renamed enumerations

17.5.
Old

Renamed Properties
New Paragraph.HorizontalAlignment Paragraph.VerticalAlignment MultiLineTextShape.HorizontalAlignment EndPageEventArgs.BackgroundAreas *.Width (of type double)

Paragraph.Alignment Paragraph.VAlignment MultiLineTextShape.Alignment EndPageEventArgs.Areas *.DWidth Table 17-4. Renamed properties

17.6. Removed Items


Old Document.QueryDocumentSettings event Link class Image.Text property ImageShape.Text property *.DWidth property Table 17-5. Removed items New Set the Document properties accordingly. Replaced by Action classes. Convert base64 data to a stream using System.Convert.FromBase64String. Convert base64 data to a stream using System.Convert.FromBase64String. Replaced by Width (of type double).

17.7.
Old

Margins and Paddings


New Margin.Left Margin.Right Margin.Top Margin.Bottom Padding.Left Padding.Right Padding.Top Padding.Bottom

Margin and Padding properties have been grouped as shown in the table below. LeftMargin RightMargin TopMargin BottomMargin LeftPadding RightPadding TopPadding BottomPadding

Table 17-6. Margin and Padding properties have been grouped

17.8. DocumentInfo
Document info properties have been grouped as shown in the table below. Old New

Pag. 88/89

TallComponents BV www.tallcomponents.com

TallPDF.NET 3.0 - Developer Guide

Document.Author Document.Creator Document.Keywords Document.Producer Document.Subject Document.Title

Document.DocumentInfo.Author Document.DocumentInfo.Creator Document.DocumentInfo.Keywords Document.DocumentInfo.Producer Document.DocumentInfo.Subject Document.DocumentInfo.Title

Table 17-7. Document info properties have been grouped into class DocumentInfo

17.9. Events, Delegates and Event Arguments


In TallPDF.NET 3.0, both delegates for events and event arguments are no longer nested in classes. In addition to this, event handlers no longer return values. The sender argument has changed to a strong-typed object to avoid a type cast. Consequently some minor changes to your code are required. This is illustrates by the following TallPDF.NET 2.0 and TallPDF.NET 3.0 snippets.
section.Paragraphs.PrintParagraph += new Paragraphs.PrintParagraphEventHandler( PrintParagraph ); bool PrintParagraph( object sender, PrintParagraphEventArgs args ) { ...// your code here return false; // true means more content available }

Code sample 17-1. TallPDF.NET 2.0 code for registering and handling generation events
mySection.Paragraphs.PrintParagraph += new PrintParagraphEventHandler( PrintParagraph ); void PrintParagraph(Paragraph sender, PrintParagraphEventArgs args ) { ...// your code here ... args.MoreContent = false; }

Code sample 17-2. TallPDF.NET 3.0 code for registering and handling generation events

17.10. Updating XML


Updating XML and XSL documents designed for TallPDF.NET 2.0 to 3.0 is in most respects the same as updating code. For updating XML, a conversion XSL is included in the download of the TallPDF.NET 3.0 archive. Use this conversion XSL to convert the TallPDF.NET 2.0 compliant XML into TallPDF.NET 3.0 compliant XML. This conversion XSL does not update existing XSL documents that convert custom XML data to TallPDF.NET 2.0 compliant XML.

Pag. 89/89

TallComponents BV www.tallcomponents.com

Potrebbero piacerti anche