PDF4NET

PDF enable Your .NET application
Create, edit, fill, merge, split and encrypt PDF files from your .Net application.
PDFView4NET
View, convert, print, fill and annotate PDF files from your .Net application.


Getting Started

This section of the documentation helps you get started with PDF4NET application development.

In this section

Overview

Covers the features of PDF4NET class library.

System Requirements

Provides information about the PDF4NET's system requirements.

Installation

Provides information regarding the installation of PDF4NET product.

Licensing

Provides information regarding the licensing modes of PDF4NET product.

© 2003 - 2007 O2 Solutions. All rights reserved.


Overview

PDF4NET is a .NET library for generating pdf documents on the fly from any .NET application. The library does not rely on any Adobe products for creating pdf files. It hides the complex structure of pdf files behind a simple object model that allows creation of complex pdf files with a few lines of code. The PDF4NET library follows the GDI+ model, thus reducing the learning time and increasing productivity. It uses a grid based layout approach allowing precise positioning of content on document's pages. The library also creates and fills PDF e-forms and merges or splits PDF documents.
The final pdf file is compressed, making the library apropriate for web applications. The library can be used both from WinForms and WebForms (ASP.NET) applications without any restrictions. Also, the same package includes a Compact .NET Framework edition of the library. The library is written entirely in C#, being 100% managed.
The PDF4NET library is licensed per developer and can be distributed ROYALTY FREE, reducing project costs.

Here is the classic “Hello world” example:

…
PDFDocument doc = new PDFDocument( );
PDFPage page = doc.AddPage( );
page.Canvas.DrawText( “Hello world”, new PDFFont( FontFace.Helvetica, 12 ),
     new PDFPen( PDFColor( 255, 0, 0 ), 1 ),
     new PDFBrush( new PDFColor( 0, 0, 255 ) ), 10, 20 );
doc.SaveToFile( “helloworld.pdf” );
// or
// Response.ContentType = "application/pdf";
// doc.SaveToStream( Response.OutputStream ); // for ASP.NET apps
…

The example above creates a PDF file with on page, and draws the string “Hello World” on the page. The used font is Helvetica, and its size is 12. The drawn string is stroked with red color and filled with blue. The text is positioned at 10 points from left margin and at 20 points from top margin of the page (see the Hello World sample).

Features

The main features of PDF4NET library are outlined below:

 | Standard .NET Framework Edition | Compact .NET Framework Edition
PDF Document Features
PDF Linearization (fast web view) |  |
Digitally sign the document (.Net 2.0 only) |  |
Document information |  |
XMP Metadata |  |
Custom document properties |  |
RGB/CMYK/Gray color modes |  |
Compressed document content |  |
Save to file/stream |  |
Automatic page numbering |  |
Import of damaged PDF files (some of them) |  |
Add/Edit/Remove document attachments |  |
Add/Edit/Remove document level JavaScript |  |
PDF Editing Features
Add new content/pages to existing pdf files |  |
Merge multiple pdf files to disk or to stream |  |
Split pdf files to single pages |  |
Apply security to existing pdf files |  |
Extract pages from pdf files and include them in new documents |  |
Place multiple pages on a single page (page imposition) |  |
Support for encrypted PDF files |  |
PDF Forms
Create and modify PDF forms (Acroforms only) |  |
Fill PDF forms (Acroforms) |  |
Read values from PDF form fields (Acroforms) |  |
Support for pushbuttons, single and multi lines text fields, checkboxes, radio buttons, comboboxes and listboxes (Acroforms) |  |
Fill static XFA forms (Adobe Designer 7 static forms) |  |
Read values from XFA forms (Adobe Designer 7 static forms) |  |
Support for pushbuttons, single and multi lines text fields, numeric fields, datetime fields, checkboxes, radio buttons, choice fields, image fields and barcode fields (XFA forms) |  |
Support for encrypted forms |  |
Form fields flattening |  |
Import/Export of form data in FDF, XFDF and XML |  |
Page features
Standard and custom page sizes |  |
Portrait/Landscape orientations |  |
User defined measure units |  |
User defined coordinate system |  |
Absolute positioning (grid based layout) |  |
Document layout
Headers |  |
Footers |  |
Page templates |  |
Layers and sub-layers |  |
Graphics
DeviceRGB, DeviceCMYK, DeviceGray, Indexed, CalGray, CalRGB, Lab, ICC, Separation and DeviceN colorspaces |  |
PANTONE colors |  |
Lines, polylines, arcs, pies, bezier, ellipses, rectangles |  |
Polygons, polypolygons, chords, rounded rectangles, paths |  |
Pen styles and solid brushes |  |
Hatched and gradient brushes |  |
Transparency and blend modes |  |
Images |  |
Clipping regions |  |
Form XObjects |  |
Images
JPEG, GIF, BMP, EMF, PNG |  | *
Images from file/stream/System.Drawing.Bitmap |  | **
Rotated images |  |
Transparent images |  |
Color key masking |  |
Image masking |  |
DEFLATE image compression |  |
TIFF to PDF conversion |  |
CCITT G4 compression for B/W images |  |
Alpha channel transparency |  |
Native EMF support |  |
Text features
Single line text |  |
Multiline text |  |
Rotated text |  |
HTML formatted text |  |
Underline, strikethrough, overline |  |
Hyperlinks |  |
Left, center, right horizontal alignment |  |
Top, middle, bottom vertical alignment |  |
Justified text |  |
Fonts
Base 14 Postscript fonts |  |
CJK fonts |  |
Type1 fonts |  |
TrueType fonts with subsetting |  |
Unicode TrueType fonts |  |
TrueType fonts from System.Drawing.Font |  |
PDF Security
AES & RC4 encryption |  |
40/128 bit encryption |  |
User and owner password |  |
Restricted document operations |  |
Hyperlinks
Bookmarks |  |
Internal cross-references |  |
External cross-references |  |
PDF Actions
Actions support at document and page level |  |
Actions support at bookmark level |  |
GoTo actions |  |
Remote GoTo actions |  |
Javascript actions |  |
Launch actions |  |
Named actions |  |
URI actions |  |
SubmitForm and ResetForm actions |  |
Annotations
3D annotations |  |
Text annotations (including extraction of text annotations from PDF documents) |  |
Free text annotations |  |
Rubber stamp annotations |  |
File attachment annotations |  |
Movie annotations |  |
Line/Circle/Square annotations |  |
Link annotations |  |
Barcodes
1D Barcodes (Codabar, Code 11, Code 128 A/B/C, Code 25, Code 25 Interleaved, Code 39, Code 93, COOP 25, EAN-13, EAN-8, IATA 25, ISBN, ISMN, ISSN, JAN-13, Matrix 25, MSI/Plessey, Planet, Postnet, RM4SCC, SCC-14, SSCC-18, UPC-A, UPC-E, Singapore Post, Royal Dutch TPG Post, PZN, Deutsche Post Identcode, Deutsche Post Leitcode, USPS FIM, UCC/EAN128, USPS Horizontal Bars, USPS Package Identification Code, FedEx Ground 96, Pharmacode, Code 32) |  |
2D Barcodes (Codablock F, Code 16K, DataMatrix, MicroPDF417, PDF417) |  |
Miscellaneous
Royalty free distribution |  |
* - JPEG & BMP only; ** - file only

© 2003 - 2007 O2 Solutions. All rights reserved.


What's new

Getting Started

What's new in version 3.3.5

Version 3.3.5 of PDF4NET library is a hotfix version, it includes several bug fixes, while keeping total backwards compatibility with previous versions. This new version supports only .Net Framework 1.1 or higher.

3.3.5.0 Bux fixes:

• XFA buttons with "Visible not printable" become "Visible printable" after saving the file with PDF4NET - fixed.

• Text cannot be wrapped when the box width is less than a character width - fixed

• Added IconName property to PDFRubberStampAnnotation class

• When clipping regions are used, together with reused brushes, the color of new objects appear as green - fixed

• Font Bbox for Mhei-Medium Bold is not defined correctly - fixed.

• PDF files created with Aspose.Words cannot be open - fixed.

• File metadata stored in DocumentInformation as custom keys is not overwritten when the file is saved with new metadata - fixed.

• Euro sign is not displayed correctly when filling XFA forms that use MyriadPro font for text fields - fixed.

3.3.4.0 Bux fixes:

• XFA forms that use bind=none at subform level are not filled correctly - fixed.

• Adobe Acrobat/Reader do not handle correctly the signature fields when they use separate field and widget objects - fixed

• Import data in a XFA form fails when an invalid value is imported in a choice field - fixed

• Some PDF files with invalid links cannot be loaded - fixed

• Extracted CCITT images that use Black = 1, White = 0, are not saved correctly when Bitmap.Save method uses Tiff image format - fixed.

• Launch actions cannot be saved in fast web view mode - fixed.

• When form fields are flattened, if the field no value, but it has a default value, the default value is not displayed - fixed.

• In some situations field fore color is not retrieved correctly due to approximations - fixed.

• Fields created on rotated pages are not rotated by default - fixed.

• Some PDF files with attachments cannot be loaded - fixed.

• Rotated multiline textbox fields are not filled correctly - fixed

3.3.3.0 Bux fixes:

• Colorspace resource entry from imported pages is not saved correctly - fixed.

• Content is not displayed correctly on rotated pages when media box bottom left corner is not located at (0,0) - fixed

• Fields.Count returns the original number of fields after the form has been flattened

• Multilevel fields with space prefixed partial names cannot be located in Fields collection - fixed

• In some situation the icon of button fields is not saved - fixed.

• Image extraction does not work when the page includes form XObjects - fixed.

• Image extraction does not work when the image includes an array of decoding filters - fixed.

• Some B/W CCITT images cannot be extracted - fixed.

• Strings located in objects stored in an object stream are not decoded correctly when the PDF file is encrypted - fixed.

• PDF forms with checkboxes that do not have an export value cannot be loaded - fixed.

• PDF files with object stream compression that include the document catalog in the object stream cannot be loaded - fixed

• SaveToFile method cannot save PDF files with digital signatures - fixed

• Imported Type1 fonts without /Widths entry are not saved correctly and the PDF file cannot be open - fixed

• Filling Unicode characters in XFA forms (when the field's font was not embedded) caused an exception when the form was saved - fixed

• Digital signature appearance is not preserved when the PDF form is flattened - fixed

3.3.2.0 Bux fixes:

• Added CreationDate and ModDate to document information.

• Added support for mirroring the content of any form XObject.

• Added support for forcing XFA form regeneration on form open.

• In some situations, after drawing imported content on a page, the remaining content is not drawn correctly if the file is saved in fast web view mode - fixed.

• In some situations the ExtGState dictionaries are not read correctly - fixed.

• CIDSystemInfo dictionary for unicode TrueType fonts is not encrypted when the document is encrypted - fixed.

• Newly created textbox fields with 0 font size do not display the field content - fixed.

• Added support for preserving separation info when doing page imposition - fixed.

• Circular references in form Xobjects generate a stack overflow - fixed.

• Patterns included in resources dictionary as direct objects cannot be imported - fixed.

3.3.1.0 Bux fixes:

• Graphic state is not restored correctly after drawing a textbox with an underlined font - fixed.

• Fields' position is shifted down left when the page media box has negative lower left coordinates - fixed.

• GoTo actions with invalid destinations (page number instead of page reference) generate an exception when the file is saved - fixed.

• GoTo actions without a destination page generate an exception when the file is saved - fixed.

• Imposition does not work correctly when the source file has resources defined at document level - fixed.

• PDF forms have unpredictable behavior when % character is included in field's export value - fixed.

• When a radio button item is selected and its export value includes characters that need to be escaped, the radio button item is not displayed - fixed.

• PDF forms that include checkboxes without visual appearance cannot be loaded - fixed.

• Annotations with borders that include a dash array cannot be loaded - fixed.

• Fields rotated with -90 are not saved correctly - fixed.

• When multiple metafiles that use the same font are drawn in a document, the font data is embedded multiple times - fixed.

• PDF files with empty metadata streams cannot be loaded - fixed.

• Landscape pages rotated with 270 degrees are not stamped correctly - fixed.

• Annotations that use wrong value types for predefined keys are not saved correctly - fixed.

• Fields collection returns a field by name when the end part of supplied name (A.B.C) matches the name of a field (C) in the document - fixed.

• Links created with PDFCanvas.DrawArea* methods are not saved correctly when the file is encrypted - fixed.

• TrueType fonts are subset when they are used with dropdown and listbox fields - fixed.

3.3.0.0 New features:

• Support for extracting images from PDF files.

• Support for extracting layers from PDF files.

• PDFImage objects now support explicit colorspaces.

3.3.0.0 Bux fixes:

• Coordinates of imported destination are not saved correctly - fixed.

• FitText method fails when the width of a word is larger than box width and the word has a single character - fixed.

• Backslashes are trimmed from the PDF file name included in a FDF file - fixed.

• Outline's top position is not set correctly when the destination page is rotated with 90/270 degrees - fixed.

• In some situations when DrawHTMLTextBox is called multiple times with the same font an invalid PDF file is generated - fixed.

• Link annotations with Launch actions no longer work after the PDF file has been loaded and saved with PDF4NET - fixed.

• Newly created textbox fields with TrueTypeFont do not work properly when the same TrueType font is used to display static text on page - fixed.

• Imported files that contain named destinations with destination arrays instead of destination dictionaries cannot be saved - fixed.

3.2.4.0 Bux fixes:

• Markup annotations are not displayed correctly on rotated pages - fixed.

• PDF files with JS actions included directly in the names array cannot be loaded - fixed.

• Stamp annotations are not displayed correctly (they are not rotated) on rotated pages - fixed.

• FDF files that include radio and checkbox fields with extended ASCII characters in field value are not imported correctly in the PDF form - fixed.

• Imposition does not work for pages without resource dictionaries - fixed.

• Save method throws an exception when the imported document has a GoTo action as OpenAction - fixed.

• Damaged files that throw an exception after a partial load (in PDFDocument constructor, when extracting pages) leave the file locked - fixed.

• Comb fields that use MacRoman encoded fonts are not displayed correctly - fixed.

• Visible area of imported pages is not computed correctly when the page is rotated - fixed.

• Invalid imported go to actions generate an exception when the file is saved - fixed.

3.2.3.0 New features:

• Support for creating and importing link annotations.

3.2.3.0 Bux fixes:

• Form Xobjects created from imported content that does not include content streams cannot be saved - fixed.

• Acrobat 3 Revision 3 encrypted files cannot be decrypted - fixed.

• Some Type1 fonts are not saved correctly - fixed.

• PDF files that include images without decode dictionaries cannot be saved - fixed.

• XMP metadata canot be saved in linearized mode - fixed.

• When a null brush is used to display text, an exception is thrown when the file is saved if the font is underlined - fixed.

• Code 93 barcodes are not generated correctly for values that include space or Z characters - fixed.

• Viewer preferences are not loaded when a PDF file is imported - fixed.

3.2.2.0 Bux fixes:

• Code 128A and 128B barcodes throw an exception when they are drawn on the page - fixed.

• LastModified date is changed for free text annotations, even if the annotation is not modified - fixed.

• PDF layers cannot be saved in linearized mode - fixed.

• Imposition does not work for pages with multiple content stream segments and PDF operators are split over 2 segments - fixed.

• PDF files with incomplete catalog objects cannot be loaded - fixed.

• Some JavaScript streams are not loaded - fixed.

• Uncompressed Type1 fonts are not saved correctly - fixed.

• Invalid definition is created for Type2 functions - fixed.

• Actions' destination is not saved correctly in linearized mode - fixed.

• ReadOnly fields are not imported from FDF/XFDF files - fixed.

3.2.1.0 Bux fixes:

• When a PDFDocument is saved multiple times, the first save generates a valid file but the next generates a damaged file - fixed.

• PDF files with invalid page objects cannot be loaded - fixed.

• In some situation bookmarks that include the new line character cannot be loaded - fixed.

• Imported content is not extracted correctly from pages that use the same names for different resources - fixed.

• Redundant objects are generated for digital signatures when PDF file is saved without linearization - fixed.

• Form fields flattening does not work for fields with custom visibility settings - fixed.

• Imported content is not extracted correctly from pages that split PDF operators over multiple content stream segments - fixed.

• Some ASCII85 encoded streams are not decoded correctly - fixed.

• PDF files with font dictionaries that include invalid ToUnicode key cannot be loaded - fixed.

• TrueType fonts cannot be used in ASP.NET applications under medium trust level - fixed.

• PDF files display the error "wrong number of operands for setcolor operation" when clipping regions are used - fixed.

• In some situations the shadings extracted from a PDF file are not saved correctly - fixed.

• PDF files that include text annotations with custom icons cannot be loaded - fixed.

• Draw*Link methods do not place correctly the links on rotated pages - fixed.

• Code 128C barcodes are not displayed correctly when checksum is 0 - fixed.

3.2.0.0 New features:

• DeviceRGB, DeviceCMYK, DeviceGray, Indexed, CalGray, CalRGB, Lab, ICC, Separation and DeviceN colorspaces.

• PANTONE colors.

3.2.0.0 Bux fixes:

• When a PDF file with layers is loaded, the layer information is discarded when the file is saved - fixed.

• Removed verification from XFARadioButton fields to allow to set only values defined on the field. Now when the field value is set to a value that is not defined on the field for checked/unchecked states, the field is considered unchecked (similar to Reader/Acrobat)

• Form fields are not displayed on the page when the logical unit is changed to other unit than point - fixed.

• PDFExtendedColor and PDFSeparationColor have been moved to O2S.Components.PDF4NET.Graphics.Colorspaces namespace.

• The 24x24 DataMatrix symbol has an incorrect number of data codewords - fixed.

• Some PDF files with embedded attachments cannot be loaded - fixed.

• XMP metadata is not written correctly when accented characters are used in content - fixed.

• Spaces are trimmed from field names, if they appear at the beginning or the end of the name - fixed.

• When a page that includes fields is removed, the document cannot be saved, an exception is thrown - fixed.

• Font size attribute is not preserved for radiobutton fields when a PDF file is loaded into a PDFDocument object - fixed.

• Renaming radiobutton fields generates redundant objects in PDF file - fixed.

3.1.1.0 New features:

• Added support for overprint drawing.

3.1.1.0 Bux fixes:

• Imported content is not extracted correctly from PDF pages that do not include any resources - fixed.

• Link annotations that include extended ASCII characters in URL are not saved correctly - fixed

• XFA forms with multiple top level subforms on the same PDF page cannot be loaded - fixed.

• Some PDF forms throw an exception if Save method is called twice and the forms are modified between Save calls - fixed.

3.1.0.0 New features:

• 12 new barcode symbologies: Singapore Post, Royal Dutch TPG Post, PZN, Deutsche Post Identcode, Deutsche Post Leitcode, USPS FIM, UCC/EAN128, USPS Horizontal Bars, USPS Package Identification Code, FedEx Ground 96, Pharmacode, Code 32.

3.1.0.0 Bux fixes:

• .NET 2.0: PDF encryption and digital signatures do not work on FIPS enabled computers - fixed.

• Textbox fields with comb attribute are not displayed correctly, comb bars are not shown - fixed

• Checkboxes and radiobuttons that include extended ASCII chars in the export value cannot be selected - fixed.

• Checksum for Code128C barcodes is not computed correctly - fixed.

• Checksum for RM4SCC barcodes is not computed correctly - fixed.

3.0.1.0 New features:

• Added support for mirroring imported content along both X and Y axes.

• Added support for extracting markup annotations as native PDF4NET annotation objects.

3.0.1.0 Bux fixes:

• Text is not visible when field height is less than font size - fixed

• PDF forms with CJK fields are not flattened correctly - fixed.

• Bookmark actions are not preserved when a PDF file is loaded and saved - fixed.

• Imported free text annotations are not saved correctly when the page is rotated - fixed.

• Imported list box fields are not saved correctly when the page is rotated - fixed.

• Non-linearized PDF files are not encrypted correctly when EncryptMetadata is false - fixed.

• Bookmarks are not encrypted correctly in non-linearized PDF file - fixed.

• Imported links on page are not preserved when the file is saved in linearized mode - fixed.

• Some PDF files with embedded Unicode fonts (DescendantFonts array contains a font definition instead of an indirect reference) are not imported and saved correctly - fixed.

• In some situations, PDF files with imported content, that included inline images, are saved incorrectly - fixed.

• Textboxes do not display the text when vertical alignment is Middle or Bottom, clipping mode is ClipWords and the text is larger than the box - fixed.

• In some situations flattened or merged PDF files display the error "Cannot find font - using Helvetica instead" when they are opened in Adobe Reader - fixed.

3.0.0.0 New features:

• Digitally sign PDF files with X.509 certificates (.Net 2.0 only).

• Embed 3D artwork in PDF files with support for projections, rendering modes, lighting schemes, backgrounds, cross sections, nodes and activation.

• AES-128 encryption.

• Added ReadOnly property at AcroForm level, to set/unset all fields at once.

• Added WideToNarrowRatio property to Code 2 of 5 family of barcodes.

• Added support for PDF 1.5 encryption which allows to leave the metadata in clear (search engine friendly), while encrypting the rest of the document.

3.0.0.0 Bux fixes:

• Field tooltips are not loaded in some situations - fixed

• Invalid linearized PDF files are generated when using other cultures than en-US - fixed.

• When importing a PDF file, optional content is not loaded and the saved file does not display correctly in Acrobat/Reader 8 - fixed.

• Mouse up actions do not work with Acrobat/Reader 5 - fixed.

• XFA forms with field names that include dots (.) are not processed correctly - fixed.

• Code128B and Code128C barcodes are not displayed correctly when the checksum value is 99 or 100 - fixed.

• End symbol for Code2 of 5 Interleaved barcodes is not encoded correctly - fixed.

• Overline, strikethrough and underline font options can not be used simultaneously - fixed.

• Renaming of radiobutton fields generate an exception - fixed.

• XFA forms with radiobuttons with no default values can not be loaded - fixed.

• PDF files created with PDF4NET can not be merged with Adobe Acrobat in some situations - fixed.

• Page labels are not decrypted correctly when an encrypted PDF file is loaded - fixed.

• XFA forms with custom values in editable drop down lists can not be loaded - fixed.

• Appearance of free text annotations with rich content is not preserved - fixed.

• 4bpp bitmap images can not be embedded in a PDF file - fixed.

• XFA fields from master page are not loaded - fixed.

• In some situations an invalid border is generated for free text annotations - fixed.

• XFA form related collections do not return the first element when using foreach if the collection is not reset before looping - fixed.

• Imported PDF files with CalRGB and CalGray colorspaces are not saved correctly - fixed.

• Encrypted PDF files with unencrypted metadata can not be opened - fixed.

© 2003 - 2007 O2 Solutions. All rights reserved.


System Requirements

The PDF4NET library requires .NET Framework 1.1 or later to be installed on the target computer for standard .NET framework edition of PDF4NET. Compact .NET Framework edition of PDF4NET library requires a Windows CE.NET powered mobile device with Compact .NET Framework 1.0 or later installed. The .NET Framework redistributable is not included in the installation kit. It can be obtained from the Microsoft website.

© 2003 - 2007 O2 Solutions. All rights reserved.


Getting Started

Installation

In order to minimize the download time, the PDF4NET library is provided as a single msi package.

How to install

After downloading the archive, run the installation package and follow the installation instructions.

After the installation, the following files will be present on computer's disk:

bin\
o2s.components.pdf4net.dll - the PDF4NET class library compiled for .NET Framework 2.0.
NET11\o2s.components.pdf4net.dll - the PDF4NET class library compiled for .NET Framework 1.1.
o2s.components.pdf4net.compact.dll - the PDF4NET compact .NET class library.
samplesign.pfx - sample X.509 certificate.
*.pdf, *.jpg, *.emf, *.ttf, *.u3d - helper files for PDF4NET samples.

help\
pdf4net.chm
pdf4netref.chm - the PDF4NET online help files.

samples\ - over 40 samples showing how to use the PDF4NET library.

© 2003 - 2007 O2 Solutions. All rights reserved.


Licensing

Key points of the license agreement.

- The PDF4NET library is licensed per developer. One license can be used on multiple computers as long as it is used by the same developer, and it can not be used concurently or shared by other developers.
- When using the PDF4NET library for desktop development (native Windows applications), the library is licensed royalty free. You pay to use during the development time to create your final product. You do not need to pay any other fees when you distribute the PDF4NET library with your final product.
- When using the PDF4NET library for mobile development (compact .NET framework applications), the library is licensed royalty free. You pay to use during the development time to create your final product. You do not need to pay any other fees when you distribute the PDF4NET library with your final product.
- When using the PDF4NET library for server-side development (ASP.NET web applications), the library is licensed deployment free. You pay to used during the development time to create your final product. You do not need to pay any other fees when you deploy the PDF4NET library along with your final product on other servers.
- This license does NOT ALLOW you to distribute the PDF4NET library for use in development. This requires an OEM distribution license. If you want to do so, please contact us.

© 2003 - 2007 O2 Solutions. All rights reserved.


License Agreement

VERY IMPORTANT - READ CAREFULLY: This O2 Solutions Software License Agreement (hereinafter, this "LICENSE") is a legal agreement between you (either an individual or a single entity) and O2 Solutions, SRL. ("O2 Solutions"), for the software containing this LICENSE which has been obtained through O2 Solutions or its authorized distributor.

1. OWNERSHIP; LICENSE GRANT.

This is a license agreement and NOT an agreement for sale. O2 Solutions continues to own the copy of the SOFTWARE contained on the disk and all other copies that you are authorized by this LICENSE to make. Your rights to the SOFTWARE are specified in this LICENSE, and O2 Solutions retains all rights not expressly granted to you in this LICENSE. O2 Solutions hereby grants to you, and you accept, a non-exclusive, non-transferable license to use, copy and modify the SOFTWARE only as authorized below.

2. PERMITTED USES.

This LICENSE grants you the following rights:
A. The SOFTWARE is licensed per individual developer. You may make copies on more than one computer, as long as the use of the SOFTWARE is by the same developer.
B. Solely with respect to electronic documents included with the SOFTWARE, you may make a copy for each developer for which the Software has been licensed as described in Section 2.A, above; provided, that such copies shall be used only by such developer for internal purposes and are not to be republished or distributed to any other third party.
C. You may use the evaluation versions of the SOFTWARE for the limited purposes of demonstrations, trials and design time evaluations.

3. PROHIBITED USES.

You may not, without the prior written permission of O2 Solutions:
A. Disassemble, decompile or "unlock", decode or otherwise reverse translate or engineer, or attempt in any manner to reconstruct or discover any source code or underlying algorithms of SOFTWARE provided in object code form only.
B. Use, copy, modify, or merge copies of the SOFTWARE and any accompanying documents except as permitted in this LICENSE.
C. Transfer, rent, lease, or sublicense the SOFTWARE.

4. REDISTRIBUTABLE COMPONENTS.

A. The files o2s.components.pdf4net.dll and o2s.components.pdf4net.compact.dll are considered as REDISTRIBUTABLE DLLs.
B. In addition to the license and rights granted in Sections I and II, O2 Solutions grants you a nonexclusive, royalty-free right to reproduce and distribute the object code version of the SOFTWARE designated in the SOFTWARE as (i) those portions of the SOFTWARE which are identified in the documentation as REDISTRIBUTABLE DLLs ("DLLs"); provided: you distribute the REDISTRIBUTABLES in object code form only in conjunction with and as part of your software application product which adds significant and primary functionality; you do not use O2 Solutions' name, logo or trademarks to market your software application product; you include a valid copyright notice on your SOFTWARE; and
C. In addition to the other requirements set forth in this Section 4, you hereby agree to indemnify, hold harmless, and defend O2 Solutions from and against any and all liabilities, damages, losses, costs and expenses (including attorneys' fees) arising from or related to any claim, action, proceeding or allegation that arise or result from the use and distribution of any of your software application product(s) or components.

5. COPYRIGHT.

All title and copyrights in and to the SOFTWARE are owned by O2 Solutions. The SOFTWARE is protected by United States copyright laws and international treaty provisions. All rights are reserved worldwide. You must treat the SOFTWARE like any other copyrighted material, except that you may, in addition to the copies permitted in this LICENSE, make one copy of the SOFTWARE solely for backup or archival purposes. No part of the accompanying printed materials may be reproduced, transmitted, transcribed, stored in any retrieval system, or translated into any language by any means without the express prior written permission of O2 Solutions.

6. TERMINATION.

This LICENSE and your right to use the SOFTWARE will terminate immediately without notice from O2 Solutions if you fail to comply with the terms and conditions of this LICENSE. Upon termination, you agree to destroy the SOFTWARE, including all accompanying documents and copies. This is in addition to and not in lieu of any criminal, civil or other remedies available to O2 Solution

7. LIMITED WARRANTY

A. O2 Solutions does not warranty that the SOFTWARE will be error-free. Except with respect to REDISTRIBUTABLES, which are provided "AS IS," without warranty of any kind, O2 Solutions warrants that the SOFTWARE will perform substantially in accordance with the accompanying electronic documentation for a period of thirty (30) days from the date of receipt.
B. O2 Solutions' entire liability, in contract tort or otherwise, and your exclusive remedy under the performance warranty set forth in Section 7.A, shall be, at O2 Solutions' option, either (a) return of the purchase price paid, or (b) repair or replacement of the defective SOFTWARE. This limited warranty is void if failure of the SOFTWARE has resulted from accident, abuse, or misapplication. Any replacement SOFTWARE will be warranted for the remainder of the original thirty (30) day period.
C. EXCEPT AS EXPRESSLY SET FORTH IN THIS SECTION 7, O2 SOLUTIONS DISCLAIMS ALL OTHER WARRANTIES, EITHER EXPRESS OR IMPLIED, WHETHER ARISING BY STATUTE OR OTHERWISE IN LAW OR FROM A COURSE OF DEALING OR USAGE OR TRADE, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OF ACCURACY, COMPLETENESS, PERFORMANCE, CURRENCY, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE WITH REGARD TO THE SOFTWARE.

8. LIMITATION OF LIABILITIES.

O2 Solutions' liability, whether in contract, or otherwise, arising out of Licensee's use of, or in connection with, the SOFTWARE, or otherwise under this Agreement, shall not exceed the amount of the license fee paid by you to O2 Solutions. IN NO EVENT SHALL O2 SOLUTIONS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, EVEN IF O2 SOLUTIONS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

© 2003 - 2007 O2 Solutions. All rights reserved.


Developer's Guide

This section of the documentation helps you get a more specific view of PDF4NET features.

In this section

First PDF file

Covers the creation of a simple pdf file.

The Object Model

Provides information about the PDF4NET's object model.

Creating content

Covers the creation of the pdf file specific content.

TrueType / Type1 fonts support

Covers the external fonts support in PDF4NET library.

PDF editing

Covers the pdf editing (merge, split, encrypt, extract) capabilities of PDF4NET library.

Automatic page numbering

Covers the page numbering features of PDF4NET library.

Creating document's bookmarks tree

Provides information about the creation of bookmarks tree that is displayed in the Bookmarks navigation pane of Adobe's pdf viewers.

Linking to other content

Provides information about creating links in a pdf file.

PDF support for presentations

Covers the presentation features found in pdf files.

Document metadata

Covers the document metadata information and viewer preferences when opening the pdf file.

PDF security and encryption

Provides information about the pdf security and encryption support available in PDF4NET library.

PDF actions

Shows how to work with PDF actions in PDF4NET library.

Annotations

Presents the support for PDF annotations available in PDF4NET library.

Linearized PDF (Fast web view PDF)

Shows how to create linearized PDF files with PDF4NET.

Working with forms

Presents the PDF forms support available in PDF4NET library.

Barcodes

Presents the barcodes support available in PDF4NET library.

© 2003 - 2007 O2 Solutions. All rights reserved.


First PDF file

Creating pdf files with PDF4NET library is an easy task. Although it is a general purpose library, its simple and easy to use object model allows you to create pdf files with no effort.

The following steps will show how easy is and how few coding lines are needed to create a pdf file (the sample below uses C#. There is no difference using Visual Basic.NET).

Set up references

First, you need to set up the refenreces to PDF4NET library. Using Visual Studio.NET, add a reference to your project to O2S.Components.PDF4NET.dll assembly. Then, add the following lines at the beginning of your source file.
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

Create the document

The first thing to do in your code is to create the document, which is an instance of PDFDocument class.
PDFDocument doc = new PDFDocument( );

Create the first page of the document

The next thing to do is to create at least one page in the document. This is accomplished using the AddPage( ) member of document object. A page in the document is an instance of PDFPage class.
PDFPage page = doc.AddPage( );

Create the content of the page

After creating the page, we need to fill it with content. The content of a page is created using the Canvas property of the page object. The canvas encapsulates the drawing surface of the page, like a device context for the screen. Using the Canvas property, you can draw figures on a page or you can write text. In this sample, we'll write a simple text on the page.
page.Canvas.DrawText( “Hello world”, new PDFFont( FontFace.Helvetica, 12 ),
     new PDFPen( new PDFColor( 255, 0, 0 ), 1 ),
     new PDFBrush( new PDFColor( 0, 0, 255 ) ), 10, 20 );
When drawing text, we need a font, a pen and a brush. The pen is used to color the border of the text, and the brush is used to fill the interior of the text. The text is written at 10 points from the left margin and 20 point from the top margin of the page.

Saving the document

Once we created the content, we can save the document. The document can be saved to a file on disk
doc.SaveToFile( "HelloWorld.pdf" );
or it can be saved to a stream, like the response stream of an ASP.NET application
Response.ContentType = "application/pdf";
doc.SaveToStream( Response.OutputStream );

© 2003 - 2007 O2 Solutions. All rights reserved.


Compact .NET Framework support

PDF4NET library supports Compact .NET Framework through a separate assembly, included in the same installation kit and covered by the same license. Please refer to Overview page for details about the features supported by PDF4NET Compact .NET Edition.

© 2003 - 2007 O2 Solutions. All rights reserved.


The Object Model

The PDF4NET library exposes a simple but powerfull object model that gives a developer access to most of pdf features.
The object model is displayed in the diagram below:

The root of the object model is the document object. It has a collection of pages and a collection of outlines. It also has a default page number, template and transition. The outlines collection is composed of individual outline items. The pages collection consists of individual page objects. A page has a canvas and specific page number, template and transition. The canvas holds the list of graphic objects that drawn on the page.

© 2003 - 2007 O2 Solutions. All rights reserved.


Creating Content

A pdf document consists of several pages. Creating document content implies creating the content for each page.

Page content

The content of a page is created using the Canvas property of the page object. The Canvas encapsulates the drawing surface of the page. Using its properties and methods, the developer can add new content to a page. The content of the page mainly consists of text, images and graphic shapes. A page can also include links to other content.

The Canvas object exposes a rich set of functions to help the developer to create rich content. Using the canvas, the following graphic shapes can be drawn on a page:
- lines (a single line or a sequence of lines).
- bezier splines.
- rectangles.
- circles.
- ellipses.
- arcs.
- pies.
- polygons.
- images.
Also, a rich set of functions is available for drawing text on the page. The canvas allows to draw single line text or multi line text. For multiline text, it is automatically wrapped to fit the required width. All types of text can be aligned in different ways. Also, the text can be displayed rotated around a specified point.

When drawing on the page, the canvas uses several painting objects to create the graphics. The pen object are used to draw the lines and the countour of graphic shapes and text, the brush is used to fill the interior of closed shapes and text, and the font object is used to set the visual appearance of the text.

The default origin of the coordinate system (0, 0) is located at the top left corner of the page. The X axis grows from left to right, the Y axis grows from top to bottom. All the dimensions and postions are given in logical units. The default logical unit used by the library is the point (1/72 inches).

Repetitive content

An important feature of the PDF4NET library is the ability to setup templates to be applied on several pages. The content of a template is created in the same way the content of a page is created. The template has a canvas that is drawing surface. After creating the content of the template, it is applied automatically to each designated page. The developer can setup multiple templates for a document, each set of pages having its own template. The content of the template is applied on a page before the actual content of the page, so the template content is under the page content when the final pdf file is created. The template feature is implemented through the PDFPageTemplate class.

Page sizes

The PDF4NET library lets the user to create documents having pages of different sizes. Each page can have its own size (controlled by Width and Height properties) and orientation (lanscape or portrait). The library supports 14 standard page formats, but other sizes can be used by setting the corresponding properties.
The following standard sizes are predefined by the library:

Page format | Width (points) | Height (points)
A3 | 842 | 1190
A4 | 595 | 842
A5 | 420 | 595
B4 | 729 | 1032
B5 | 516 | 729
Letter | 612 | 792
Legal | 612 | 1008
Tabloid | 792 | 1224
Ledger | 1224 | 792
Statement | 396 | 612
Executive | 540 | 720
Folio | 612 | 936
Quarto | 610 | 780
10x14 | 720 | 1008

© 2003 - 2007 O2 Solutions. All rights reserved.


Logical units

The concept of logical unit has been introduced in order to facilitate the positioning of content within a page. All drawing functions now use logical units to position the content on the page. A logical unit defines the transformation between the transformation between user's measure unit and the default measure unit used within the pdf files which is the point. Now, you can specify the position of page content using inches, millimeters, centimeters, or any other unit that fits you best. The default logical unit used by the library is the point, so compatibility with previous versions is kept.

Defining a new logical unit

All the logical units used with PDF4NET library must inherit from PDFLogicalUnitBase class, which is the base class representing an abstract logical unit.

When inheriting from PDFLogicalUnitBase, 2 methods must be implemented: ToPDFUnitX( float unit ) and ToPDFUnitY( float unit ).

Method ToPDFUnitX( float unit ) defines the transformation between the user's measure unit and the pdf unit (the point) for the X axis. It says how many pdf units correspond to the number of units given as parameter when representing the logical unit on the X axis.

Method ToPDFUnitY( float unit ) defines the transformation between the user's measure unit and the pdf unit (the point) for the Y axis. It says how many pdf units correspond to the number of units given as parameter when representing the logical unit on the Y axis.

Defining different mappings for X and Y axes, allows a developer to have different physical lenghts for a unit on X and Y axes. Thus, a unit on X axis might represent 10 points, while a unit on Y axis might represent 100 points.

The example below shows how to define a new logical unit that maps to 10 points on X axis and to 100 points on Y axis.

class Unit : PDFLogicalUnitBase
{
    float ToPDFUnitX( float unit )
    {
        return unit * 10;
    }

    float ToPDFUnitY( float unit )
    {
        return unit * 100;
    }
}

Using logical units

The PDFDocument class allows to define a global logical unit used across the document. When a new page is added to the document, it inherits the logical unit to be used from the document, but the library allows to set a different logical unit for each page to fit best the drawing needs. Also, in order to provide more flexibility during the drawing process, the developer can change the logical unit while drawing on the page. You can accomplish this using the SetLogicalUnit( ) method of the Canvas object.

The following sample shows how to do it:

...
// create a new logical unit that represents the centimeter.
PDFCMLogicalUnit cm = PDFCMLogicalUnit( );
page.Canvas.SetLogicalUnit( cm );
// the following drawing operations use the centimeter to draw the content
//
// Draw a horizontal line, 10 cm in length, at 1 cm from the top and
// starting at 1 cm from the left of the page and ending at 11 cm from the
// left of the page.
page.Canvas.DrawLine( pen, 1, 1, 11, 1 );
// continue drawing here
...
...
// create a new logical unit that represents the inch
PDFInchLogicalUnit in = PDFInchLogicalUnit( );
page.Canvas.SetLogicalUnit( in );
// the following drawing operations use the inch to draw the content

// Draw a horizontal line, 3 inches in length, at 1 inch from the top and
// starting at 1 inch from the left of the page and ending at 4 inches
// from the left of the page.
page.Canvas.DrawLine( pen, 1, 1, 4, 1 );
// continue drawing here
...

Predefined units

The library defines classes that represent the following units:
- point - PDFPointLogicalUnit
- millimeter - PDFMMLogicalUnit
- centimeter - PDFCMLogicalUnit
- inch - PDFInchLogicalUnit

When a document is created, the default logical unit is the point. Also, when a page is created the default logical unit is the point. At this time, the page size, width and height, is given in points. When a new logical unit is assigned to the page, through LogicalUnit property, these values are recomputed automatically to represent the new units. In this case, changing the page size needs to be done after changing the logical unit for the page, and not before.

The following sample shows how to do it:

PDFDocument doc = new PDFDocument( );
PDFPage page = doc.AddPage( );
// at this time the logical unit of the page is the point
// the Width is set to 612 points and the Height is set to
// 792 points (standard letter values).
...
// Create a new logical unit
PDFInchLogicalUnit in = PDFInchLogicalUnit( );
page.LogicalUnit = in;
// now, the Width is 8.5 in, and Height is 11 in.
page.Width = 10;
page.Height = 10;
// now, the Width is 10 in, and Height is 10 in.
...

In the sample above, if the assignment

page.Width = 10;
page.Height = 10;

would have been done before setting the logical unit for the page, then the page size would have been considered to be 10 points x 10 points and setting the logical unit to inch would have converted the page size to 0.14 x 0.14 inches.

© 2003 - 2007 O2 Solutions. All rights reserved.


Coordinate systems

The PDF4NET library introduces a new feature that allows a developer to customize the coordinate system in order to fit the drawing requirements. The default coordinate system has its origin in the top left corner of the page, the X axis grows from left to right, and the Y axis grows from top to bottom. The new features allows the developer to set the origin of the coordinate system anywhere on the page, and set arbitrary directions for each axis. When changing the origin of the coordinate system, the new position is always given in the coordinates of the current system.

The following sample moves the origin of the coordinate system to bottom left corner of the page and changes the direction of the Y axis to bottom to top (this is the default pdf coordinate system).

...
// the initial coordinate system has the origin in top left corner
...
// move the origin to bottom left corner
page.Canvas.SetOrigin( 0, page.Height );
// change Y axis direction to grow from bottom to top
page.Canvas.SetAxesDirections( XAxisDirection.LeftToRight, YAxisDirection.BottomToTop ); ...

Left, Top positioned objects

For graphic objects that are positioned on the page using Left, Top, Right, Bottom coordinates the Left coordinate is always on the left of the page and the Right coordinate is always on the right of the page, no matter the direction of the X axis is, left to right, or right to left. When the direction of X axis is LeftToRight, the following relation is always true: Right >= Left. When the direction of X axis is RightToLeft, the following relation is always true: Left >= Right. For Y axis the situation is similar, Top is always at the top of the page and Bottom is at the bottom of the page, no matter the direction of the Y axis is, top to bottom, or bottom to top. When the direction of Y axis is TopToBottom, the following relation is always true: Bottom >= Top. When the direction of Y axis is BottomToTop, the following relation is always true: Top >= Bottom.

The width of these graphic objects is always from Left to Right, and the Height is always from Top to Bottom.

The above situation is detailed in the images below:

Default coordinate system Reversed coordinate system

The relative position of Left, Right, Top, Bottom coordinate is always the same, no matter the axes direction.

Text lines

When drawing text lines, the text alignment is always relative to the printing coordinate, no matter the directions of the axes.

The following images show how TopLeft text alignment is handled for different directions of the axes:

TopLeft text aligment for different axes directions.

Text boxes

When drawing text boxes, the alignment of the text is relative to the interior of the box, no matter the directions of the axes and the text box follows the rules for the graphic objects shown above.

The images below show how the drawing of text boxes is handled for different directions of axes.

Textbox alignment for different axes directions.

© 2003 - 2007 O2 Solutions. All rights reserved.


HTML formatting

The PDF4NET library provides HTML formatting features for displayed text, enhancing existing text display capabilities.

Support classes and methods

New classes and methods have been added to support HTML formatted text, both for single text lines and text boxes. The following classes provide support for HTML formatted text:
PDFHTMLText - works the same way like PDFText but parses its text in order to display the correct formatting.
PDFHTMLTextBox - works the same way like PDFTextBox but parses its text in order to display the correct formatting.
A series of methods have been added to PDFCanvas class to support the drawing of HTML text. The following methods provide support for HTML formatted text:
DrawHTMLText( ) - works the same way like its counterparts DrawText( ) methods but parses its text in order to display the correct formatting.
DrawHTMLTextBox( ) - works the same way like its counterparts DrawTextBox( ) methods but parses its text in order to display the correct formatting.

Supported HTML tags

The HTML must be well formed, all tags must be closed. The text must be a valid XML document. Also, the tags are case sensitive and lower case must be used.
All the attributes must be quoted, otherwise an exception will be raised. E.g: <font color="#000000">test</font> is valid while <font color=#000000>test</font> will raise an exception.
Overlapping of tags is not allowed, e.g.: <b><i>test</b></i> will not work, while <b><i>test</i></b> is correct.
The following HTML tags are supported:

<b> - marks a block of text as bold.

<i> - marks a block of text as italic.

<u> - marks a block of text as underline.

<st> - marks a block of text as strikethrough.

<o> - marks a block of text as overline.

<br/> - forces a new line in the text box.

<font> - sets the display font for a block of text. The following attributes are supported:
- color - sets the color of the text. Supports both named colors and hex coded colors.
- fillcolor - sets the color of the text interior. Supports both named colors and hex coded colors. This attribute is identical to "color" attribute.
- strokecolor - sets the color of the text border. Supportsbothnamed colors and hex coded colors.
- face - sets the name of the font used to display the text. The following values are accepted for this attribute: Helvetica, Courier, TimesRoman, Symbol, ZapfDingbats.
- size - sets the size, in points, of the font used to display the text. This attribute accepts as value any float value.

The <st> and <o> tags, and "fillcolor" and "strokecolor" attributes are PDF4NET extensions to HTML specification.

External fonts

HTML formatted text can also use external fonts, like TrueType, PostScript or CJK. To use external fonts with HTML formatted text, the fonts must be created separately then added to a hashtable. The key in the hashtable is the face of the font and the value is the font object. The key used in the hashtable is used as a value for 'face' attribute of font tag.
The following sample shows how to use external fonts with HTML formatted text:
...
CJKFont cjk = new CJKFont( CJKFontFace.HeiseiMinchoW3, 12 );
TrueTypeFont vr = new TrueTypeFont( "Verdana.ttf", 10, true, true );
TrueTypeFont vri = new TrueTypeFont( "Verdanai.ttf", 10, true, true );
// Create the fonts to write the text
Hashtable fc = new Hashtable( );
fc.Add( "verdana", vr );
fc.Add( "verdanaitalic", vri );
fc.Add( "heisei", cjk );
// Draw the text
page.Canvas.DrawHTMLTextBox( "<font face='heisei'>PDF4NET はあらゆるNET のアプリケーションからPDF" +
    "文書をオンザフラ</font><font face= 'verdana'>This will start with Verdana and</font>" +
    "<font face= 'verdanaitalic'>it will be italic</font>",
    cjk, null, brush, 20, 20, 200, 200, tfo, 0, fc );
...

© 2003 - 2007 O2 Solutions. All rights reserved.


Fonts metrics

Developer's Guide

Font Metrics

Version 2.1 of PDF4NET library gives access to the metrics of the fonts used to display text. Any font object exposes a property named Metrics of type PDFFontMetrics that returns read only values of font metrics. Ascent, descent, leading, stemV, stemH, cap height, x height, average width and max width metrics are available. All these values are given in unscaled glyph units.
Also, two new methods are available in any font object:
fontobj.MeasureString( string text ) - returns the width of the text in points, based on the fontobj metrics
fontobj.GetCharWidth( char charCode ) - returns the width of the given character in unscaled glyph units.
To convert from unscaled glyph units to points, divide the value by 1000 then multiply it by font size.

© 2003 - 2007 O2 Solutions. All rights reserved.


Clipping regions

Version 2.1 of PDF4NET library brings support for clipping regions. The following clased shapes can be used as clipping regions: PDFEllipse, PDFPie, PDFPolygon and PDFRectangle. When a clipping region is active, only the graphics inside the region are visible. Any graphic or part of a graphic that falls outsite of the region is clipped at region boundary. The PDFCanvas class makes public two methods to work with clipping regions:
SetClipRegion( PDFGraphic clipGraphic ) sets the given graphic object as a clipping region
ResetClipRegion( ) clears the active clipping region.
The following sample shows how to use a clipping region:
...
// create a rectangular clip region, with top left at 10, 10, width 200, height 100
// pen and brush do not matter, they can be null
PDFRectangle rc = new PDFRectangle( null, null, 10, 10, 200, 100 );
page.Canvas.SetClipRegion( rc );
...
// continue to add content here
// when the pdf file is viewed, only the graphics inside the rectangle will be visible
...
// The clip region is cleared
page.Canvas.ResetClipRegion( );
...
// all the graphics drawn from this point on the page will be visible when the pdf file is viewed
...

© 2003 - 2007 O2 Solutions. All rights reserved.


Layers

Layers in a PDF file allows to define optional content that can selectively shown or hidden by the user. Layers are especially usefull in graphics applications for grouping related content.
PDF4NET library allows to create unlimited levels of layers and sublayers in a parent-child relationship. The page's Canvas has a Layers property that allows to add new layers to a page. Each layer has its own independent Canvas for creating its content. The z-order of the layers on a page is determined by the order they have been added to the layers collection of the page.
Regular page content (created through page's Canvas) is separate from layers' content and its visibility (show/hide) can not be controlled by the user that views the PDF file. For imported PDF documents, layers can be created also under existing page content.

The following sample shows how to create 2 top level layers and 4 sublayers for the first layer:

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Layers
{
   class Layers
   {
      [STAThread]
      static void Main(string[] args)
      {
         // Create the pdf document
         PDFDocument doc = new PDFDocument( );

         // Create one page
         PDFPage page = doc.AddPage( );

         PDFPen redPen = new PDFPen( new PDFColor( 192, 0, 0 ), 1 );
         PDFBrush blueBrush = new PDFBrush( new PDFColor( 0, 0, 255 ) );
         PDFBrush darkBlueBrush = new PDFBrush( new PDFColor( 0, 0, 128 ) );

         // Draw "Hello world" in the center of the page
         // this text is always visible.
         page.Canvas.DrawText( "Hello world !",
            new PDFFont( FontFace.Helvetica, 100 ), redPen, blueBrush, page.Width/2, page.Height/2,
            0, TextAlign.MiddleCenter );

         // Create a parent layer
         PDFLayer squareLayer = page.Canvas.Layers.Add( "Empty square" );
         // Create a poly polygon and draw it on the layer
         PDFPoint[][] polygons = new PDFPoint[2][];
         polygons[0] = new PDFPoint[]{ new PDFPoint( 50, 100 ), new PDFPoint( 550, 100 ),
                                 new PDFPoint( 550, 600 ), new PDFPoint( 50, 600 ) };
         polygons[1] = new PDFPoint[]{ new PDFPoint( 100, 150 ), new PDFPoint( 500, 150 ),
                                 new PDFPoint( 500, 550 ), new PDFPoint( 100, 550 ) };
         PDFPolyPolygon pp = new PDFPolyPolygon( redPen, darkBlueBrush, polygons );
         pp.FillMode = FillMode.EvenOdd;
         squareLayer.Canvas.Add( pp );

         // create 4 sublayers
         // 1. Hatched layer
         PDFLayer hatchedLayer = squareLayer.Canvas.Layers.Add( "Hatched square" );
         // Create a hatch brush
         PDFHatchBrush hb = new PDFHatchBrush( HatchType.DiagonalCross );
         hb.HatchColor = new PDFColor( Color.Aquamarine );
         hb.Color = new PDFColor( Color.Azure );
         hatchedLayer.Canvas.DrawRectangle2( redPen, hb, 100, 150, 200, 200 );

         // 2. Vertical gradient layer
         PDFLayer verticalGradientLayer = squareLayer.Canvas.Layers.Add( "Vertical gradient square" );
         // Create a vertical gradien brush
         PDFVerticalGradientBrush vgb = new PDFVerticalGradientBrush( );
         vgb.StartColor = new PDFColor( Color.Aquamarine );
         vgb.EndColor = new PDFColor( Color.Purple );
         verticalGradientLayer.Canvas.DrawRectangle2( redPen, vgb, 300, 150, 200, 200 );

         // 4. Horizontal gradient layer
         PDFLayer horizontalGradientLayer = squareLayer.Canvas.Layers.Add( "Horizontal gradient square" );
         // Create a horizontal gradient brush
         PDFHorizontalGradientBrush hgb = new PDFHorizontalGradientBrush( );
         hgb.StartColor = new PDFColor( Color.YellowGreen );
         hgb.EndColor = new PDFColor( Color.Violet );
         horizontalGradientLayer.Canvas.DrawRectangle2( redPen, hgb, 100, 350, 200, 200 );

         // 4. Solid layer
         PDFLayer solidLayer = squareLayer.Canvas.Layers.Add( "Solid square" );
         // Create a solid brush
         PDFBrush solidBrush = new PDFBrush( new PDFColor( Color.CornflowerBlue ) );
         solidLayer.Canvas.DrawRectangle2( redPen, solidBrush, 300, 350, 200, 200 );

         // create another layer on top of existing ones
         PDFLayer xLayer = page.Canvas.Layers.Add( "Green X" );
         PDFPen greenPen = new PDFPen( new PDFColor( Color.GreenYellow ), 32 );
         greenPen.LineCap = LineCap.Round;
         xLayer.Canvas.DrawLine( greenPen, 50, 100, 550, 600 );
         xLayer.Canvas.DrawLine( greenPen, 550, 100, 50, 600 );

         // Save the document to disk
         doc.SaveToFile( "layers.pdf" );
      }
   }
}

The results of the code above are displayed below:
All layers visible | Top level X layer and 2 child layers invisible | All layers invisible

© 2003 - 2007 O2 Solutions. All rights reserved.


Form XObjects

A form XObject is a self contained graphic block. Its content is created like usual page content, using its own Canvas, and it can be painted multiple times on several pages in the same document or on several locations on the same page. The size of a form XObject is defined by its Width and Height properties, anything that falls outside the form XObject's rectangle is not visible. The coordinate system used by a form XObject has its origin in the top left corner. The form XObject has a Canvas property that allows to create its content, much like creating page content.
When a form XObject is drawn onto a page, its content is scaled and/or rotated to fit the given drawing rectangle.
The following sample shows how to create a simple form XObject and draw it multiple times on a page.

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Net;
using System.Collections;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Fonts;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace Test
{

   class Test
   {

      [STAThread]
      static void Main(string[] args)
      {
         // Create the pdf document
         PDFDocument doc = new PDFDocument( );

         // Create one page
         PDFPage page = doc.AddPage( );

         PDFPen redPen = new PDFPen( new PDFColor( 255, 0, 0 ), 1 );
         PDFBrush darkBlueBrush = new PDFBrush( new PDFColor( 0, 0, 128 ) );

         // create a form XObject
         PDFFont font = new PDFFont( FontFace.Helvetica, 16 );
         string pdf4net = "PDF4NET";
         // the size of form xobject matches the text size
         PDFFormXObject form = new PDFFormXObject( );
         form.Width = font.MeasureString( pdf4net );
         form.Height = 16;
         // draw the text on the form xobject
         form.Canvas.DrawText( pdf4net, font, null, darkBlueBrush, 0, 0 );

         // draw the form XObject on the page.
         // strectch it to cover the whole page header and on the left margin
         page.Canvas.DrawFormXObject( form, 0, 0, page.Width, 24 );
         page.Canvas.DrawFormXObject( form, 32, 0, page.Height, 32, -90 );
         // draw the form XObject in its original size
         page.Canvas.DrawFormXObject( form, 50, 50, form.Width, form.Height );

         doc.SaveToFile( "formxobject.pdf" );
      }
   }
}

The result is displayed below:

The content of a form XObject is stored only once in the PDF file, no matter how many times it is drawn. This allows to reduce PDF file size when there are graphic patterns that repeat themselves on the same page or on several pages.

© 2003 - 2007 O2 Solutions. All rights reserved.


Custom brushes

The PDF4NET library provides support for custom brushes for filling closed paths. Both hatched brushes and gradient brushes are supported.

Hatched brushes

Hatched brushes allow filling closed paths with predefined patterns. The following patterns are available:
HatchType.BackwardDiagonal | HatchType.ForwardDiagonal | HatchType.Cross | HatchType.DiagonalCross | HatchType.Horizontal | HatchType.Vertical

Hatched brushes can be drawn either transparent (default) or opaque. To draw an opaque hatched pattern, set the Color property of the PDFHatchBrush object. Also, the color of the hatch pattern can be specified.
The following sample shows how to create a red hatched pattern with yellow background:
...
PDFHatchBrush hb = new PDFHatchBrush( HatchType.DiagonalCross );
hb.Color = new PDFColor( 255, 255, 0 ); // yellow background
hb.HatchColor = new PDFColor( 255, 0, 0 ); // red hatch
...
The result is displayed below:

The library allows to customize the distance between pattern's lines, both on vertical and on horizontal.
...
PDFHatchBrush hb = new PDFHatchBrush( HatchType.BackwardDiagonal );
hb.Color = new PDFColor( 255, 255, 0 ); // yellow background
hb.HatchColor = new PDFColor( 255, 0, 0 ); // red hatch
hb.HatchVerticalSize = 5;
hb.HatchHorizontalSize = 10;
...
The result is displayed below:

Gradient brushes

Gradient brushes can be used with any fillable path. They use linear gradients with 2 colors for filling the paths. Both horizontal and vertical gradients can be used with gradient brushes.
The following sample shows how to create a horizontal gradient:
...
PDFHorizontalGradientBrush hgb = new PDFHorizontalGradientBrush( );
hgb.StartColor = new PDFColor( Color.Red );
hgb.EndColor = new PDFColor( Color.Blue );
...
The result is displayed below:

The following sample shows how to create a vertical gradient:
...
PDFVerticalGradientBrush vgb = new PDFVerticalGradientBrush( );
vgb.StartColor = new PDFColor( Color.Green );
vgb.EndColor = new PDFColor( Color.Blue );
...
The result is displayed below:

Gradient brushes work only when using the default coordinate system (the point is the measure unit and the origin of the coordinate system is in the top left corner of the page).

© 2003 - 2007 O2 Solutions. All rights reserved.


Transparency

PDF4NET library allows to define unlimited levels of transparency in a PDF file. Once a transparency level has been set in place, all subsequent drawing operations will use it. Only one transparency level can be active at a moment. The transparency levels vary from 0% (opaque) to 100% (full transparency).
The following sample shows how to draw lines of text, each one with its transparency level:
using System;
using System.IO;
using System.Drawing;
using System.Text;
using System.Collections;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Fonts;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace Test
{

class Test
{

[STAThread]
static void Main(string[] args)
{
// Create the
                            pdf document
PDFDocument doc = new PDFDocument(
                    );

// Create the
                            graphic objects
PDFBrush blackBrush = new
                    PDFBrush( new PDFColor( ) );
PDFFont font = new PDFFont(
                    FontFace.Helvetica, 20 );
font.Bold = true;

         PDFPage page = doc.AddPage( );

         // generate random background
         Random rnd = new Random( );
         for( int i = 0; i < 50; i++ )
         {
            // Create random colors for drawing the spline
            PDFColor penColor = new PDFColor( ( byte )rnd.Next( 256 ),
               ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );

            // Create the pen to draw the border
            PDFPen randomPen = new PDFPen( penColor, 1 );

            // Generate random control points
            float x1 = rnd.Next( ( int )page.Width );
            float y1 = rnd.Next( ( int )page.Height );
            float x2 = rnd.Next( ( int )page.Width );
            float y2 = rnd.Next( ( int )page.Height );
            float x3 = rnd.Next( ( int )page.Width );
            float y3 = rnd.Next( ( int )page.Height );
            float x4 = rnd.Next( ( int )page.Width );
            float y4 = rnd.Next( ( int )page.Height );

            // Draw the Bezier spline
            page.Canvas.DrawBezier( randomPen, x1, y1, x2, y2, x3, y3, x4, y4 );
         }

         float y = 100;
         // draw several strings, each one with its level of transparency
         for( int i = 0; i <=  10 0; i = i +
         5
            ) { page.Canvas.SetTransparency( i );
            page.Canvas.DrawText( "PDF4NET transparency sample", font, null, blackBrush, 120, y );
            y = y + 24;
         }

         doc.SaveToFile( "transparency.pdf" );
      }
   }
}

The result is displayed below:

© 2003 - 2007 O2 Solutions. All rights reserved.


TrueType / Type1 fonts / CJK Fonts

The PDF4NET library can use both TrueType/OpenType fonts and Type1 PostScript fonts.

TrueType/OpenType fonts

The TrueType/OpenType fonts can be used with PDF4NET library through TrueTypeFont class. These fonts are used in the same way the built in fonts are used. When a TrueTypeFont object is created, the path to the font file on disk must be provided. The font can be embedded or not in the pdf file.

When the TrueType font is embedded in the pdf file, the best results are obtained when the pdf file is viewed or printed, because the font data is available within the file.

When the TrueType font is not embedded in the pdf file, the pdf viewer will load the font, if available, from the local machine. If the font is not available on the local machine, the pdf viewer with substitute it with a font that matches the best the original font metrics.

At development time, the font must be present on the local machine, no matter the font will be embedded or not in the final pdf file, because the necessary metrics information must be extracted from the file. Because the library parses the font data in order to load the necessary metrics information, the font does not need to be installed on the local machine.

The following code snippet shows how to use a TrueType font:

...
TrueTypeFont ttf = new TrueTypeFont( "verdana.ttf", 12, true );
page.Canvas.DrawText( "This text uses Verdana font, size 12 and the font is embedded", ttf, pen, brush, 10, 10 );
...

The library allows to create a TrueTypeFont object based on an existing TrueTypeFont object. In this way, the second font object does not reparse the TrueType font file, and the font data is shared by both font objects. Because the Bold and Italic attributes are read from the font file, they are shared, so changing the Bold property for one font object causes the other font object to update its Bold property. These 2 properties are the only ones that are shared, all the other properties can be used without side effects.

When the font is embedded in the pdf file, the values of Bold and Italic properties are ignored, because the pdf viewer synthesize the correct font appearance based on the embedded font data. When the font is not embedded, these 2 properties are used to give the pdf viewer a hint about the font appearance.

The following code snippet shows how to create a TrueTypeFont object based on an existing one:

...
TrueTypeFont ttf2 = new TrueTypeFont( ttf, 16 );
page.Canvas.DrawText( "This text uses Verdana font, size 16", ttf2, pen, brush, 10, 50 );
...

The PDF4NET library provides support for Unicode characters, when using TrueType fonts. A Unicode TrueType font is created like in the sample below:

...
TrueTypeFont ttf = new TrueTypeFont( "verdana.ttf", 12, true, true );
page.Canvas.DrawText( "This text uses Unicode Verdana font, size 12 and the font is embedded", ttf, pen, brush, 10, 10 );
...

The 4th parameter of the constructor instructs the library to use Unicode features of the TrueType font.

A TrueType font can also be created from a System.Drawing.Font object. The following sample shows how to do it:

...
System.Drawing.Font fnt = new System.Drawing.Font( "verdana", 12 );
TrueTypeFont ttf = new TrueTypeFont( fnt, true, true );
page.Canvas.DrawText( "This text uses Unicode Verdana font, based on a System.Drawing.Font object, and the font is embedded", ttf, pen, brush, 10, 10 );
...

Type1 PostScript fonts

The Type1 PostScript fonts are used the same way (all that has been said above about TrueType fonts applies to Type1 fonts) like TrueType fonts, with one exception: when creating a PostScriptFont object, there are 2 files that define the font on disk. The PDF4NET library uses a .afm file (Adobe Font Metrics) or a .pfm file (Printer Font Metrics) to read font metrics, and a .pfb file (Printer Font Binary) to read font data.

The following code snippet shows how to use a Type1 font:

...
PostScriptFont psf = new PostScriptFont( "times-roman.afm", "times-roman.pfb", 12, true );
page.Canvas.DrawText( "This text uses Times-Roman postscript font, size 12 and the font is embedded", psf, pen, brush, 10, 10 );
...

CJK fonts

The PDF4NET library provides supports for CJK fonts based on Adobe Asian Language Pack. The following fonts are supported:
- Heisei Kaku Gothic W5 japanese font face (UniJIS-UCS2-H encoding).
- Heisei Mincho W3 japanese font face (UniJIS-UCS2-H encoding).
- Hanyang Systems Gothic Medium korean font face (UniKS-UCS2-H encoding).
- Hanyang Systems Shin MyeongJo Medium korean font face (UniKS-UCS2-H encoding).
- Monotype Hei Medium chinese traditional font face (UniCNS-UCS2-H encoding).
- Monotype Sung Light chinese traditional font face (UniCNS-UCS2-H encoding).
- SinoType Song Light chinese simplified font face (UniGB-UCS2-H encoding).

The following code snippet shows how to use a CJK font:

...
CJKFont cjk = new CJKFont( CJKFontFace.HeiseiKakuGothicW5, 12 );
page.Canvas.DrawText( "PDF4NET はあらゆるNET のアプリケーションからPDF 文書をオンザフラ", psf, pen, brush, 10, 10 );
...

© 2003 - 2007 O2 Solutions. All rights reserved.


Update existing pdf files

With PDF4NET library, existing pdf files can be updated to include new content. The library can add new pages to an existing document, at any location, in front of existing pages, in the middle or at the end of the imported document. Adding new content to an existing page is the same like adding content to a new page. The new content is drawn on top of existing content. The existing content of a page can not me changed.

To import a pdf document in PDF4NET library, the following constructor should be used: PDFDocument( string pdfFile ); where the pdfFile parameter is the full path to a pdf file on disk. After the constructor is executed, the Pages collection of PDFDocument object contains a PDFPage object for each page in the source pdf file. The pages of the imported document can be accessed using the index based PDFDocument.Pages collection. Pages[0] is the first page of the document, while Pages[Pages.Count-1] is the last page of the document. New pages can be added anywhere in the document.

The following sample code shows how to add new content to an existing pdf file. It draws a line on top of the first page of the imported document.
...
PDFDocument doc = new PDFDocument( "helloworld.pdf" );
PDFPen pen = new PDFPen( );
doc.Pages[0].Canvas.DrawLine( pen, 0, 0, doc.Pages[0].Width, doc.Pages[0].Height );
doc.SaveToFile( "new.pdf" );
...

The next sample code shows how to create a new page at the beginning of the imported file, then it draws a line of text on it.
...
PDFDocument doc = new PDFDocument( "helloworld.pdf" );
// create a new page at the beginning of the document (insert it at index 0)
PDFPage page = doc.InsertPage( 0 );
page.Canvas.DrawText( "This is a new page", font, null, brush, 10, 10 );
doc.SaveToFile( "new.pdf" );
...

In this version, encrypted documents can not be updated. When an encrypted document is used, an exception is raised.

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Editing

PDF4NET library allows to perfom a wide range of operations on existing pdf files. The library allows to merge multiple pdf files or to split a pdf file to individual pages, it allows to apply security to existing pdf files. It also allows to extract full pages or their content from a pdf file. All the methods dealing with pdf editing capabilities are located in the O2S.Components.PDF4NET.PDFFile namespace and PDFFile class implements all these operations.

Merging pdf files

Multiple pdf files can be merged at once with a single line of code. The resulted pdf file can be automatically saved to disk, or it can be used further in the application to add new content.
The following 2 methods are available for merging pdf files:
public static void MergeFiles( string destFileName, string[] srcFileNames );
This method allows to merge multiple pdf files into a single one that is automatically saved to disk. The source pdf files are provided in a string array. They are merged in the order they appear in the array. The resulted pdf file is saved to the file specified by destFileName parameter.
public static PDFDocument MergeFiles( string[] srcFileNames );
This method allows to merge multiple pdf files into a single one and returns the corresponding PDFDocument object to be further used in the application. The source pdf files are provided in a string array. They are merged in the order they appear in the array. The resulted pdf file is returned as a PDFDocument object.
Sample
The following sample shows how to append 2 pdf files:
PDFFile.MergeFiles( "append.pdf", new string[]{ "unicode.pdf", "multicolumntextandimages.pdf" } );

or

PDFDocument doc = PDFFile.MergeFiles( new string[]{ "unicode.pdf", "multicolumntextandimages.pdf" } );
doc.SaveToStream( stream );

Splitting pdf files

A pdf file can be splitted to individual pages and each pdf file corresponding to a page saved to disk.
The following method is available for splitting pdf files:
public static void SplitFile( string srcFileName, string destFileName );
This method allows to merge split a pdf file into a single pages that are automatically saved to disk. The source pdf file is specified by srcFileName parameter. The destFileName parameter is used to construct the name of each page. At the end of the name a suffix representing the page number is appended.
Sample
The following sample shows how to split a pdf file to single pages:
...
PDFFile.SplitFile( "unicode.pdf", "unicode-page.pdf" );
...

Applying security to existing pdf files

Existing pdf files can be secured at once with a single line of code. The resulted pdf file can be automatically saved to disk, or it can be used further in the application to add new content.
The following 2 methods are available for applying security to an existing pdf file:
public static void EncryptFile( PDFSEcurityManager securityManager, string srcFileName, string destFileName );
This method allows to encrypt a pdf file that is automatically saved to disk. The source pdf file specified by srcFileName parameter. The resulted pdf file that is encrypted is saved to the file specified by destFileName parameter. The security settings are specified by the securityManager parameter.
public static PDFDocument EncryptFile( PDFSEcurityManager securityManager, string srcFileName );
This method allows to encrypt a pdf file and returns the corresponding PDFDocument object to be further used in the application. The source pdf file specified by srcFileName parameter. The resulted pdf file is returned as a PDFDocument object. The security settings are specified by the securityManager parameter.

Sample
The following sample shows how to encrypt a pdf file:
PDFSecurityManager securityManager = new PDFSecurityManager( );
securityManager = securityManager;
securityManager.KeySize = EncryptionKeySize.Use128BitKey;
securityManager.UserPassword = Encoding.ASCII.GetBytes( "userpass" );
securityManager.OwnerPassword = Encoding.ASCII.GetBytes( "ownerpass" );
securityManager.AllowPrint = false;
securityManager.FullQualityPrint = true;
securityManager.AllowModifyDocument = false;
securityManager.AllowExtractContent = false;
securityManager.AllowInteractiveEdit = false;
securityManager.AllowFormsFill = true;
securityManager.AllowAccessibilityExtractContent = true;
securityManager.AllowAssembleDocument = false;

PDFFile.EncryptFile( securityManager, "unicode.pdf", "unicode_secure.pdf" );

// or

PDFDocument doc = PDFFile.EncryptFile( securityManager, "unicode.pdf" );
doc.SaveToStream( stream );

Page and content extraction

PDF4NET library allows to extract both full pages and page content only from existing pdf files. The difference between these 2 features is that a full page can be inserted as it is in a new document and includes annotations, links and form fields, while the page content can be drawn on any new page, rotated and scaled. Multiple extracted page contents can be placed on a single new page (page imposition). Page content is extracted as a binary block, not as single items (images, text, drawing primitives)
The following methods are available for extracting pages from an existing pdf file:
public PDFImportedPage ExtractPage( int pageNumber );
This method extracts a single page from a pdf document and returns the corresponding PDFImportedPage object. pageNumber is zero based index.
public PDFImportedPage[] ExtractPages( string pageNumbers );
This method extracts a set of pages from a pdf document and returns an array of PDFImportedPage objects.
The page numbers are specified using a comma or dash separated list. Page numbers separated by comma represent single pages, while dash separated page numbers represent page ranges. "1,2,3" represents pages 2, 3 and 4 (remember the page number as parameter is zero based), while "2-5" represents pages 3, 4, 5 and 6. A pages list can contain both comma and dashes, ex: "1, 3, 5-7, 10" meaning that pages 2, 4, 6, 7, 8 and 11 will be extracted.
An imported page can be added to a new pdf document using the AddPage( PDFPage page ) method of PDFDocument class.
The PDF4NET library can extract pages and content from encrypted PDF file. The overloaded FromFile method of PDFFile class accepts a password (user or owner password) as its second parameter.
Sample
The following sample shows how to mix 2 pdf files:
PDFFile unicodeFile = PDFFile.FromFile( "unicode.pdf" );
PDFFile mctiFile = PDFFile.FromFile( "multicolumntextandimages.pdf" );
PDFImportedPage ip = null;

PDFDocument doc = new PDFDocument( );
for( int i = 0; i < 4; i++ )
{
    // extract the page
    ip = unicodeFile.ExtractPage( i );

    // add the page to new document
    doc.AddPage( ip );

    // extract the page
    ip = mctiFile.ExtractPage( i );

    // add the page to new document
    doc.AddPage( ip );
}

// save the mixed document
doc.SaveToFile( "mix.pdf" );

unicodeFile.Close( );
mctiFile.Close( );
The following methods are available for extracting page content from an existing pdf file:
public PDFImportedContent ExtractPageContent( int pageNumber );
This method extracts a single page content from a pdf document and returns the corresponding PDFImportedContent object. pageNumber is zero based index.
public PDFImportedContent[] ExtractPagesContent( string pageNumbers );
This method extracts a set of pages content from a pdf document and returns an array of PDFImportedContent objects.
The page numbers are specified using a comma or dash separated list. Page numbers separated by comma represent single pages, while dash separated page numbers represent page ranges. "1,2,3" represents pages 2, 3 and 4 (remember the page number as parameter is zero based), while "2-5" represents pages 3, 4, 5 and 6. A pages list can contain both comma and dashes, ex: "1, 3, 5-7, 10" meaning that pages 2, 4, 6, 7, 8 and 11 will be extracted.
Imported content is drawn on a new page using the DrawImportedContent method of PDFCanvas class.

Sample
The following sample shows how to place the content of 4 pages on a single new page:
PDFFile mctiFile = PDFFile.FromFile( "multicolumntextandimages.pdf" );
// extract the content of first 4 pages
PDFImportedContent[] ic = mctiFile.ExtractPagesContent( "0-3" );

// create the new document
PDFDocument doc = new PDFDocument( );
// add a page to it
PDFPage page = doc.AddPage( );

// draw the imported content (4 pages) on the new page
page.Canvas.DrawImportedContent( ic[0], 0, 0, page.Width/2, page.Height/2 );
page.Canvas.DrawImportedContent( ic[1], page.Width/2, 0, page.Width/2, page.Height/2 );
page.Canvas.DrawImportedContent( ic[2], 0, page.Height/2, page.Width/2, page.Height/2 );
page.Canvas.DrawImportedContent( ic[3], page.Width/2, page.Height/2, page.Width/2, page.Height/2 );

// save the mixed document
doc.SaveToFile( "imposition.pdf" );

mctiFile.Close( );

© 2003 - 2007 O2 Solutions. All rights reserved.


Automatic page numbering

The PDF4NET library offers the possibility of numbering document's pages in an automated way. The developer can customize the way the page number is displayed on document's pages. The visual aspect of page number can be customized for each page, if desired. Also, the developer can set up numbering schemes (also known as numbering ranges), associating a numbering range with a set of consecutive pages in the document. The pages covered by a numbering range share the same numbering system. A numbering range starts from a page in the document and ends where the next numbering range starts, or at the end of the document. The start of a numbering range is defined by the index of first page in range. This index a document global index and represents the position of the page in document's Pages collection. This index is 0 based. The first page of the document has 0 index, the second page has 1 index, the third page has 2 index, and so on. This index is not the same with the page number. While for some documents they may coincide, generally they do not match. The page index always starts at 0 for the first page and runs consecutively through the document, while the page numbers can start with any value that is appropiate for the document's logical structure. For example, a document may have an introduction of 10 pages numbered in roman numerals, while the rest of the document is numbered using arabic numerals. The first page in the document has index 0 and page number i, the tenth page in the document has index 9 and page number x, and the eleventh page has index 10 and page number 1. The previous example assumes that 2 numbering ranges have been defined for the document, one starting at index 0 with roman numbering system, and another starting at index 10 with arabic numberic system.

Implementation

The automatic page numbering features of PDF4NET library are implemented by 2 classes:.

- PDFPageNumberingRange - defines a numbering range.

- PDFPageNumber - defines the visual aspect of the page number as it is printed on the page.

PDFPageNumberingRange
A numering range defines a common numbering system for a set of consecutive pages. A numbering range is characterized by the following properties:
- start page index - the index of the page where the numbering range starts
- start page number - the value of the page number for the first page in range. For the rest of the pages in range, this value is incremented accordingly with page's position in range. For example, the page number for the first page in a range in 10, then for the second page it is 11, for the third page it is 12, and so on.
- numbering style - defines the numbering system for the range. It can be roman numbering system or arabic numbering system. For roman numbering system, uppercase or lowercase letters can be used.
- page prefix - a string the will be displayed in front of the page number when it is printed on the page. For example, for a range the string "Chapter 1 - " is defined as prefix and the page number starts at 1. When the page numbers are drawn on the page, they will look like this: Chapter 1 - 1 for the first page, Chapter 1 - 2 for the second page, and so on.
The following sample source code numbers the document in the following way: introduction on first 10 page with roman numbering system, and the rest of the pages with arabic numbering system
...
PDFPageNumberingRange pnr1 = new PDFPageNumberingRange( );
pnr1.StartPageIndex = 0;
pnr1.StartPageNumber = 1;
pnr1.NumberingStyle = NumberingStyle.LowerCaseRoman;
PDFPageNumberingRange pnr2 = new PDFPageNumberingRange( );
pnr2.StartPageIndex = 10;
pnr2.StartPageNumber = 1;
pnr2.NumberingStyle = NumberingStyle.Arabic;
doc.AddNumberingRange( pnr1 );
doc.AddNumberingRange( pnr2 );
...

PDFPageNumber
This class defines the visual aspect of the printed page number. A page number is characterized by the following properties:
- font - the font used to draw the page number.
- pen - the pen used to draw the border of the text representing the page number.
- brush - the brush used to fill the interior of the text representing the page number.
- align - the alignment of the page number when it is drawn on the page.
- vertical offset and horizontal offset - these 2 values are dependent on the type of alignment of the page number. When the page number is left aligned on horizontal, the horizontal offset represents the distance between the left margin of the page and the left margin of the text. When the page number is right aligned on horizontal, the horizontal offset represents the distance between the right margin of the page and the right margin of the text. When the page number is center aligned on horizontal, the horizontal offset is not used, the page number is positioned in the center of the page, on horizontal. When the page number is top aligned on verical, the vertical offset represents the distance between the top margin of the page and the top margin of the text. When the page number is bottom aligned on vertical, the vertical offset represents the distance between the bottom margin of the page and the bottom margin of the text. When the page number is middle aligned on vertical, the vertical offset is not used, the page number is positioned in the middle of the page, on vertical.
The page number appearance can be customized separately for each page of the document.

Note: The page number is printed on a page only if the page belongs to a numbering range and it has defined a page number (the Number property of the page is not null).

© 2003 - 2007 O2 Solutions. All rights reserved.


Creating document's bookmarks tree

To ease navigation in large documents, pdf files may display a document outline in the viewer, allowing the user to navigate from one page to another. The document outline consists of a tree like hierarchy of outline items (they are also called bookmarks). This tree hierarchy serves as a visual table of content that display the structure of the document to the user. Each node in the outline can be open or closed with the mouse. When a node is open, its imediate children are displayed. Each child can be open or clsed, revealing further the parts of the hierarchy. When an item is clicked, the viewer displays the destination page associated with the item. In fact, an outline item acts like an internal link, the difference is that the document outline is displayed in a separate navigation page, and both the document and its outline can be visible at the same time.

The document outline is displayed using a viewer selected font, but the document can specify whether an outline item should be displayed bold and/or italic. Also, the document can choose a different color for each outline item.

In the PDF4NET object model an outline item is represented by PDFOutline class. Each outline has an outlines collection which represents its imediate children. The document object also holds an outlines collection. The outline items in this collection represent the top level items in the hierarchy.

© 2003 - 2007 O2 Solutions. All rights reserved.


Linking to other content

PDF files may include hyperlinks to various content. This content can be internal or external to the document. A hyperlink is defined by a rectangular area on the page.

Depending on the type of the refered content, the hyperlinks can be divided in 4 categories:

1. Internal document links - these links point to pages in the same document. These links can be created using PDFAreaDocLink / PDFTextDocLink classes. When creating an internal link, the destination page and a vertical offset must be specified. The vertical offset is used to position the destination page when it is open in the viewer as a result of using the link. If the vertical offset is 0, then the page is displayed at top, and if it is page.Height/2 then the page is displayed starting from middle. This positioning is dependent on the screen resolution, if the screen resolution allows the display of a full page, then the value of the vertical offset does not matter because the destination page will be always displayed in full. If the screen resolution does not allow the display of a full page and you have to scroll up and down to view the page, then the vertical offset works. The vertical offset is set using the TopDestination property of the document link classes.
When an internal link is clicked, the destination page is displayed in the viewer and it is positioned as specified by the vertical offset.

2. External document links - these links point to other pdf files. These links can be created using PDFAreaRemoteDocLink / PDFTextRemoteDocLink classes. When creating an external document link, the path to the destination pdf document must be specified. If the path is a relative one, then it is considered relative to the location of the current document.
When an external document link is clicked, the destination pdf file is loaded in the viewer.

3. External file links - these links point to other types of files. These links can be created using PDFAreaFileLink / PDFTextFileLink classes. When creating an external file link, the path to the destination file must be specified. If the path is a relative one, then it is considered relative to the location of the current document.
When an external file link is clicked, the destination file is launched or it is opened by its associated application.

4. Web links - these links point to web locations. These links can be created using PDFAreaWebLink / PDFTextwebLink classes. When creating a web link, the URL of the web location file must be specified.
When a web link is clicked, the URL is opened in the browser.

The PDF4NET library allows the creation of all 4 types of links. Each type of link comes in 2 flavours: a rectangular link and a text link.

- rectangular links are defined by a rectangular area on the page. When the user clicks inside the rectangle, he is taken to the corresponding destination.

- text links are a specialized version of the rectangular links. In fact, they are rectangular links, but the library calculates the rectangular area automatically, as the bounding rectangle of the text.

Neither types of links can be displayed rotated.

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF support for presentations

PDF files may include basic presentation features, such as automatic advance to the next page and transition effects when advancing from one page to the next one. In this way, the document can be displayed in the form of a slide show.

The presentation features are controlled by the PDFPageTransition class. This class specifies the type of transition effect between page, the display duration of a page and the transition duration to the next page.

In order to enable the presentation features, each page of the document must have attached a PDFPageTransition object, using the Transition property of the page. The display duration of a page is controlled by the PageDuration property, and the transition duration is controlled by the TransitionDuration property. Both properties are specified in seconds. The TransitionDuration for a page controls the transition between the previous page and that page. This rule also applies to the transition effect.

The PageDuration controls the display duration of a page. If it is zero or the page does not have a transition object, then the viewer does not automatically advance to the next page. Also, the next page must have attached a transition object to specify the transition effect and the transition duration between the first page and the next page, in order to have automatic advance.

Note: The presentation features are optional and may not be implemented by all viewers.

© 2003 - 2007 O2 Solutions. All rights reserved.


Document metadata

PDF files can store general information about the document itself. They also can control the way they are displayed when they are open in the viewer.

Document information

A PDF file may store information about the document, such as document's title, subject, etc. This information can be searched by external applications for different purposes.

You can access this information using the DocumentInformation property of the document class. The value of this property is an instance of PDFDocumentInformation class. All the information fields can be accessed using the properties of DocumentInformation object. The following items can be used:

- Title (read/write)

- Author (read/write)

- Subject (read/write)

- Keywords (read/write)

- Creator (read/write) - the application that is creating the pdf file.

- Producer (read only) - this property always evaluates to "PDF4NET (http://www.pdf4net.com/)".

This information is displayed in Document Info window in Adobe's viewers.

Viewer preferences

A PDF file can control the way the document is presented on the screen when it is open in the viewer. The following customizations of the viewer can be performed when a document is open:

- hide toolbar - when the document is open, the toolbar can be made invisible.

- hide menu bar - when the document is open, the menu bar can be made invisible.

- hide viewer user interface - when the document is open, the whole viewer user interface can be made invisible.

- fit window - when the document is open, the document's window can be resized to fit the size of first displayed page.

- center window - when the document is open, the document's window can be placed in the center of the screen.

- display document title - when the document is open, the document's title is displayed in the titlebar of the viewer, instead of file's name.

These properties can be accessed using the ViewerPreferences property of the document class. The value of this property is an instance of PDFViewerPreferences class.

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Security and encryption

PDF4NET library allows to create secure pdf documents, with support for user and owner passwords, document encryption and document access rights.

The following options are available when creating a secure document:

Encryption - pdf documents can be encrypted using 40 bit or 128 bit keys. PDF4NET library supports both key types.

User and owner password - pdf documents can be protected using 2 passwords: a user password and an owner password. The user password allows a user to view the document and the access to document is restricted based on the access rights that have been set. The owner password allows a user to get full control over the pdf document. When both password are identical, the user is considered to log in as owner.

Access rights - the following access rights can be set on a pdf document:
Allow Print - this flag, together with FullQualityPrint flag and encryption key size, controls the printing of the document. If this flag is not set, then the user is not allowed to print the document. If this property is true, then the user is allowed to print the document, depending on the value of FullQualityPrint flag and encryption key size. If encryption key size is 40 bit then FullQualityPrint flag property is ignored. If encryption key size is 128 bit then if FullQualityPrint flag is set, then the document is printed at full quality, otherwise printing of the document is limited to a low-level representation of the document, of degraded quality. This degraded quality printing is viewer implementation dependent.
Full Quality Print - This property has effect only when AllowPrint flag is set and encryption key size is 128 bit. If this flag is set, then the document is printed at full quality, otherwise printing of the document is limited to a low-level representation of the document, of degraded quality. This degraded quality printing is viewer implementation dependent.
Allow Modify Document - This flag, if set, allows a user to modify the content of pdf document by operations other than those controlled by the following flags: Allow Interactive Edit, Allow Forms Fill, Allow Assemble Document.
Allow Interactive Edit - This flag, if set, allows a user to add or modify text annotations, fill in interactive forms fields, and, if AllowModifyDocument flag is set, create or modify interactive form fields (including signature fields).
Allow Forms Fill - This flag has effect only when using 128 bit encryption. This flag, if set, allows a user to fill in existing interactive form fields (including signature fields), even the Allow Interactive Edit flag is not set.
Allow Assemble Document - This flag has effect only when using 128 bit encryption This flag, if set, allows a user to assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even the Allow Modify Document flag is not set.
Allow Extract Content - When using 128 bit encryption this flag, if set, allows a user to copy or otherwise extract text and graphics from the document by operations other than those controlled by AllowAccessibilityExtractContent flag. When using 40 bit encryption, then this flag also controls extraction of text and graphics in support of accessibility to disabled users or other purposes.
Allow Accessibility Extract Content - This property has effect only when using 128 bit encryption This flag, if set, allows a user to copy or otherwise extract text and graphics from the document in support of accessibility to disabled users or for other.

The PDF security and encryption are implemented by PDFSecurityManager class. It exposes properties for setting the encryption key size, the user and owner passwords and the above access rights. A pdf document is encrypted automatically when the SecurityManager property of a PDFDocument object is set to a valid instance of PDFSEcurityManager class.

The following sample shows how to set the security over a pdf file:
...
// Create the pdf document
PDFDocument doc = new PDFDocument( );

// set the security options
doc.SecurityManager = new PDFSecurityManager( );
// use 128 bit encryption
doc.SecurityManager.KeySize = EncryptionKeySize.Use128BitKey;
// set user password to "userpass"
doc.SecurityManager.UserPassword = Encoding.ASCII.GetBytes( "userpass" );
// set owner password to "ownerpass"
doc.SecurityManager.OwnerPassword = Encoding.ASCII.GetBytes( "ownerpass" );
// allow to print the pdf document
doc.SecurityManager.AllowPrint = true;
// do not allow high quality print
doc.SecurityManager.FullQualityPrint = false;
// do not alow to modify the document
doc.SecurityManager.AllowModifyDocument = false;
// do not allow to extract content (text and images) from the document
doc.SecurityManager.AllowExtractContent = false;
// do not allow to fill forms or to create annotations
doc.SecurityManager.AllowInteractiveEdit = false;
// do not allow forms fill
doc.SecurityManager.AllowFormsFill = false;
// allow to extract content in support for accessibility
doc.SecurityManager.AllowAccessibilityExtractContent = true;
// do not allow to assemble document
doc.SecurityManager.AllowAssembleDocument = false;
...
...
doc.SaveToFile( "encrypted.pdf" );

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Actions

In a PDF file, the target of a bookmark can be an action to be performed when the bookmark is selected. Also, actions can be executed automatically when a document is opened or when a page is displayed.
The following actions are supported by PDF4NET library:

GoTo actions

A GoTo action (PDFGoToAction class) displays a specified page in the current document. A position and a magnification factor can be specified for the destination page.

The sample below shows a GoTo action that displays the second page of the document at the top using a magnification factor of 800%:

static void Main(string[] args)
{
// Create the pdf document
PDFDocument doc = new PDFDocument( );

// Create two pages
doc.AddPage( );
doc.AddPage( );

/// OpenDocument action
// Create an action to be executed when the
                document is opened
// The action will open the document at the
// second page of the document using a 800% zoom
PDFGoToAction goToAction = new PDFGoToAction( );
goToAction.Page = doc.Pages[1];
goToAction.MagnificationMode =
                MagnificationMode.XYZ;
goToAction.Left = 0;
goToAction.Top = 0;
goToAction.Zoom = 800;

// set the action on the document
doc.OpenAction = goToAction;
/// OpenDocument action

// Save the document to disk
doc.SaveToFile( "actions.pdf" );
}

Remote GoTo actions

A Remote GoTo action (PDFRemoteGoToAction class) displays a specified page in an external pdf document. A position and a magnification factor can be specified for the destination page.

The sample below shows a Remote GoTo action that displays the second page of the "second.pdf" document at the top using a magnification factor of 800%:

static void Main(string[] args)
{
// Create the pdf document
PDFDocument doc = new PDFDocument( );

// Create one page
doc.AddPage( );

// create a remote GoTo action
PDFRemoteGoToAction remoteGoToAction = new
                PDFRemoteGoToAction( );
// the page number is zero based
remoteGoToAction.PageNumber = 1;
remoteGoToAction.RemoteFile = "second.pdf";

// create a bookmark to point to the "second.pdf"
PDFOutline ol = new PDFOutline( "External pdf
                document", new PDFColor( ), false, OutlineDisplay.Regular, remoteGoToAction );

// add the bookmark to the document
doc.Outlines.Add( ol );

// Save the document to disk
doc.SaveToFile( "actions.pdf" );
}

JavaScript actions

A JavaScript action (PDFJavaScriptAction class) allows execution of javascript code embedded in the pdf document.

The sample below shows a JavaScript action that prints the document:

static void Main(string[] args)
{
// Create the pdf document
PDFDocument doc = new PDFDocument( );

// Create one page
doc.AddPage( );

// create a javascript action to print the
                document
PDFJavaScriptAction jsAction = new
                PDFJavaScriptAction( );
jsAction.Script = "this.print(true);\n";

// create a bookmark to execute the action
PDFOutline js = new PDFOutline( "Print me from
                JavaScript", new PDFColor( ), false, OutlineDisplay.Regular, jsAction );

// add the bookmark to the document
doc.Outlines.Add( js );

// Save the document to disk
doc.SaveToFile( "actions.pdf" );
}

Launch actions

A Launch action (PDFLaunchAction class) allows execution of an external application or file.

The sample below shows a Launch action that launches Microsoft Word:

static void Main(string[] args)
{
// Create the pdf document
PDFDocument doc = new PDFDocument( );

// Create one page
doc.AddPage( );

// create a Launch action to start the MS Word
                application
PDFLaunchAction launchAction = new
                PDFLaunchAction( );
launchAction.File = "msword.exe";

// create a bookmark to execute the action
PDFOutline ol = new PDFOutline( "Start me", new
                PDFColor( ), false, OutlineDisplay.Regular, launchAction );

// add the bookmark to the document
doc.Outlines.Add( ol );

// Save the document to disk
doc.SaveToFile( "actions.pdf" );
}

Named actions

A Named action (PDFNamedAction class) allows execution of predefined PDF actions. The following predefined PDF actions are available: go to next page, go to prev page, go to first page, go to last page.

The sample below shows a Named action that displays the last page of the document:

static void Main(string[] args)
{
// Create the pdf document
PDFDocument doc = new PDFDocument( );

// Create one page
doc.AddPage( );

// create a Named action to display the last page
                of the document
PDFNamedAction namedAction = new PDFNamedAction(
                );
namedAction.NamedAction = NamedAction.LastPage;

// create a bookmark to execute the action
PDFOutline ol = new PDFOutline( "Go to last
                page", new PDFColor( ), false, OutlineDisplay.Regular, namedAction );

// add the bookmark to the document
doc.Outlines.Add( ol );

// Save the document to disk
doc.SaveToFile( "actions.pdf" );
}

URI actions

A URI action (PDFURIAction class) allows to display a hypertext link in a web browser.

The sample below shows an URI action that displays the O2 Solutions homepage in the browser:

static void Main(string[] args)
{
// Create the pdf document
PDFDocument doc = new PDFDocument( );

// Create one page
doc.AddPage( );

// create a URI action to display the O2
                Solutions homepage
PDFURIAction uriAction = new PDFURIAction( );
uriAction.URI = "http://www.o2sol.com/";

// create a bookmark to execute the action
PDFOutline ol = new PDFOutline( "www.o2sol.com",
                new PDFColor( ), false, OutlineDisplay.Regular, uriAction );

// add the bookmark to the document
doc.Outlines.Add( ol );

// Save the document to disk
doc.SaveToFile( "actions.pdf" );
}

© 2003 - 2007 O2 Solutions. All rights reserved.


Annotations

PDF4NET library provides support for adding annotations both to existing and newly created PDF files. The following anootation types are supported: circle annotation, file attachment annotation (for embedding files into a PDF file), line annotation, markup annotation, movie annotation, rubber stamp annotation, square annotation and text annotation. Each annotation allows to control its opacity. The annotation's opacity can vary from 0 (fully transparent) to 100 (opaque).

The following sample shows how to create several types of annotations:

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Annotations;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Annotations
{
   /// <summary>
   /// This sample shows all annotations that can be created with PDF4NET.
   /// </summary>
   class Annotations
   {
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main(string[] args)
      {
         // Create the pdf document
         PDFDocument doc = new PDFDocument( );

         // Create one page
         PDFPage page = doc.AddPage( );

         PDFBrush blackBrush = new PDFBrush( new PDFColor( 0, 0, 0 ) );
         PDFFont fontSection = new PDFFont( FontFace.Helvetica, 10 );
         fontSection.Bold = true;
         PDFFont fontText = new PDFFont( FontFace.Helvetica, 8 );

         page.Canvas.DrawText( "Text annotations", fontSection, null, blackBrush, 20, 45, 0, TextAlign.BottomLeft );
         // Create all available text annotations
         PDFTextAnnotation ta = new PDFTextAnnotation( "Comment", "Comment annotation" );
         ta.Icon = TextAnnotationIcon.Comment;
         ta.Rectangle = new RectangleF( 20, 60, 100, 100 );
         page.Annotations.Add( ta );
         page.Canvas.DrawText( "Comment", fontText, null, blackBrush, 20, 80, 0, TextAlign.TopLeft );

         ta = new PDFTextAnnotation( "Help", "Help annotation" );
         ta.Icon = TextAnnotationIcon.Help;
         ta.Rectangle = new RectangleF( 100, 60, 100, 100 );
         page.Annotations.Add( ta );
         page.Canvas.DrawText( "Help", fontText, null, blackBrush, 100, 80, 0, TextAlign.TopLeft );

         ta = new PDFTextAnnotation( "Insert", "Insert annotation" );
         ta.Icon = TextAnnotationIcon.Insert;
         ta.Rectangle = new RectangleF( 180, 60, 100, 100 );
         page.Annotations.Add( ta );
         page.Canvas.DrawText( "Insert", fontText, null, blackBrush, 180, 80, 0, TextAlign.TopLeft );

         ta = new PDFTextAnnotation( "Key", "Key annotation" );
         ta.Icon = TextAnnotationIcon.Key;
         ta.Rectangle = new RectangleF( 260, 60, 100, 100 );
         page.Annotations.Add( ta );
         page.Canvas.DrawText( "Key", fontText, null, blackBrush, 260, 80, 0, TextAlign.TopLeft );

         ta = new PDFTextAnnotation( "New paragraph", "New paragraph annotation" );
         ta.Icon = TextAnnotationIcon.NewParagraph;
         ta.Rectangle = new RectangleF( 340, 60, 100, 100 );
         page.Annotations.Add( ta );
         page.Canvas.DrawText( "New paragraph", fontText, null, blackBrush, 340, 80, 0, TextAlign.TopLeft );

         ta = new PDFTextAnnotation( "Note", "Note annotation" );
         ta.Icon = TextAnnotationIcon.Note;
         ta.Rectangle = new RectangleF( 420, 60, 100, 100 );
         page.Annotations.Add( ta );
         page.Canvas.DrawText( "Note", fontText, null, blackBrush, 420, 80, 0, TextAlign.TopLeft );

         ta = new PDFTextAnnotation( "Paragraph", "Paragraph annotation" );
         ta.Icon = TextAnnotationIcon.Paragraph;
         ta.Rectangle = new RectangleF( 500, 60, 100, 100 );
         page.Annotations.Add( ta );
         page.Canvas.DrawText( "Paragraph", fontText, null, blackBrush, 500, 80, 0, TextAlign.TopLeft );

         // Rubber stamp annotations

         page.Canvas.DrawText( "Rubber stamp annotations", fontSection, null, blackBrush, 20, 120, 0, TextAlign.TopLeft );
         // Create all available rubber stamp annotations
         PDFRubberStampAnnotation rsa = new PDFRubberStampAnnotation( "Approved", "Approved annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Approved;
         rsa.Rectangle = new RectangleF( 20, 140, 100, 30 );
         rsa.Opacity = 50;
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Approved", fontText, null, blackBrush, 20, 180, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "As Is", "As Is annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Asis;
         rsa.Rectangle = new RectangleF( 120, 140, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "As Is", fontText, null, blackBrush, 120, 180, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "Confidential", "Confidential annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Confidential;
         rsa.Rectangle = new RectangleF( 220, 140, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Confidential", fontText, null, blackBrush, 220, 180, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "Departmental", "Departmental annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Departmental;
         rsa.Rectangle = new RectangleF( 320, 140, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Departmental", fontText, null, blackBrush, 320, 180, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "Draft", "Draft annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Draft;
         rsa.Rectangle = new RectangleF( 420, 140, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Draft", fontText, null, blackBrush, 420, 180, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "Experimental", "Experimental annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Experimental;
         rsa.Rectangle = new RectangleF( 520, 140, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Experimental", fontText, null, blackBrush, 520, 180, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "Expired", "Expired annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Expired;
         rsa.Rectangle = new RectangleF( 20, 200, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Expired", fontText, null, blackBrush, 20, 240, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "Final", "Final annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Final;
         rsa.Rectangle = new RectangleF( 120, 200, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Final", fontText, null, blackBrush, 120, 240, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "ForComment", "ForComment annotation" );
         rsa.Icon = RubberStampAnnotationIcon.ForComment;
         rsa.Rectangle = new RectangleF( 220, 200, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "ForComment", fontText, null, blackBrush, 220, 240, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "ForPublicRelease", "ForPublicRelease annotation" );
         rsa.Icon = RubberStampAnnotationIcon.ForPublicRelease;
         rsa.Rectangle = new RectangleF( 320, 200, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "ForPublicRelease", fontText, null, blackBrush, 320, 240, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "NotApproved", "NotApproved annotation" );
         rsa.Icon = RubberStampAnnotationIcon.NotApproved;
         rsa.Rectangle = new RectangleF( 420, 200, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "NotApproved", fontText, null, blackBrush, 420, 240, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "NotForPublicRelease", "NotForPublicRelease annotation" );
         rsa.Icon = RubberStampAnnotationIcon.NotForPublicRelease;
         rsa.Rectangle = new RectangleF( 520, 200, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "NotForPublicRelease", fontText, null, blackBrush, 520, 240, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "Sold", "Sold annotation" );
         rsa.Icon = RubberStampAnnotationIcon.Sold;
         rsa.Rectangle = new RectangleF( 20, 260, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "Sold", fontText, null, blackBrush, 20, 300, 0, TextAlign.TopLeft );

         rsa = new PDFRubberStampAnnotation( "TopSecret", "TopSecret annotation" );
         rsa.Icon = RubberStampAnnotationIcon.TopSecret;
         rsa.Rectangle = new RectangleF( 120, 260, 100, 30 );
         page.Annotations.Add( rsa );
         page.Canvas.DrawText( "TopSecret", fontText, null, blackBrush, 120, 300, 0, TextAlign.TopLeft );

         // Line annotations

         page.Canvas.DrawText( "Line annotations", fontSection, null, blackBrush, 20, 350, 0, TextAlign.TopLeft );
         PDFLineAnnotation la = new PDFLineAnnotation( "Line", "Line annotation" );
         la.BeginLineStyle = LineEndingStyle.Circle;
         la.EndLineStyle = LineEndingStyle.OpenArrow;
         la.Rectangle = new RectangleF( 20, 370, 150, 30 );
         la.Border = new PDFAnnotationBorder( 1, BorderStyle.Solid );
         la.BorderColor = new PDFColor( Color.Red );
         la.InteriorColor = new PDFColor( Color.CornflowerBlue );
         page.Annotations.Add( la );
         page.Canvas.DrawText( "Line annotation with a circle and open arrow", fontText, null, blackBrush,
            20, 420, 0, TextAlign.TopLeft );

         // File attachment annotations

         page.Canvas.DrawText( "File attachment annotations", fontSection, null, blackBrush, 20, 480, 0, TextAlign.TopLeft );
         // Create all available file attachment annotations
         PDFFileAttachmentAnnotation faa = new PDFFileAttachmentAnnotation( "Graph", "Graph icon" );
         faa.Icon =FileAttachmentAnnotationIcon.Graph;
         faa.Rectangle = new RectangleF( 20, 500, 100, 30 );
         faa.Compress = true;
         faa.File = "sample.pdf";
         page.Annotations.Add( faa );
         page.Canvas.DrawText( "Graph", fontText, null, blackBrush, 20, 530, 0, TextAlign.TopLeft );

         faa = new PDFFileAttachmentAnnotation( "Paperclip", "Paperclip icon" );
         faa.Icon =FileAttachmentAnnotationIcon.Paperclip;
         faa.Rectangle = new RectangleF( 100, 500, 100, 30 );
         faa.Compress = true;
         faa.File = "sample.pdf";
         page.Annotations.Add( faa );
         page.Canvas.DrawText( "Paperclip", fontText, null, blackBrush, 100, 530, 0, TextAlign.TopLeft );

         faa = new PDFFileAttachmentAnnotation( "PushPin", "PushPin icon" );
         faa.Icon =FileAttachmentAnnotationIcon.PushPin;
         faa.Rectangle = new RectangleF( 180, 500, 100, 30 );
         faa.Compress = true;
         faa.File = "sample.pdf";
         page.Annotations.Add( faa );
         page.Canvas.DrawText( "PushPin", fontText, null, blackBrush, 180, 530, 0, TextAlign.TopLeft );

         faa = new PDFFileAttachmentAnnotation( "Tag", "Tag icon" );
         faa.Icon =FileAttachmentAnnotationIcon.Tag;
         faa.Rectangle = new RectangleF( 260, 500, 100, 30 );
         faa.Compress = true;
         faa.File = "sample.pdf";
         page.Annotations.Add( faa );
         page.Canvas.DrawText( "Graph", fontText, null, blackBrush, 260, 530, 0, TextAlign.TopLeft );

         // Save the document to disk
         doc.SaveToFile( "annotations.pdf" );
      }
   }
}
The result is displayed below:

© 2003 - 2007 O2 Solutions. All rights reserved.


Linearized PDF

PDF4NET library can create linearized PDF files (fast web view PDF files) with no additional effort from the developer. The new Save method added to PDFDocument class has a second boolean parameter that allows to specify whether the resulting PDF file should be created in linearized or regular format.
PDFDocument doc = new PDFDocument();
// Create the PDF file content.
// ...
// Save the linearized PDF file (set second parameter to true).
doc.Save("file.pdf", true);

Linearized PDF files require 2 passes over the PDF file and the save operation will require more time than saving the file in regular format.

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Forms

Developer's Guide

Working with PDF Forms

This section shows how to use PDF4NET library when working with PDF forms.
Interactive forms allows to collect input from user. The PDF specification, starting with PDF 1.5, supports 2 types of interactive forms: AcroForms and XFA Forms.

AcroForms

AcroForms are available starting with PDF 1.2. They evolved as the PDF specification evolved, and now complex business scenarios can be developed using AcroForms.
The following form field types are supported in AcroForms:
• textboxes - single and multi line
• pushbuttons
• checboxes
• radiobuttons
• dropdown lists
• listboxes
Form fields can be enhanced with JavaScript actions for data formatting and validation, or for interoperability with external data sources, such as SOAP webservices.
PDF4NET library supports both creating new AcroForms and reading and filling existing AcroForms.

XFA Forms

XFA Forms are available starting with PDF 1.5, but they become widely used starting with PDF 1.6. They are the new generation of PDF forms that follow the Adobe's XML Forms Architecture. They are more complex that AcroForms and they have features that are not available in AcroForms.
The following form field types are supported in XFA Forms:
• text fields - single and multi line
• password fields
• numeric fields
• date and time fields
• pushbutton fields
• checbutton fields
• radiobutton lists
• choice fields - both drop down and list
• image fields
• barcode fields
Form fields can be enhanced with JavaScript or FormCalc scripts for data formatting, validation and complex calculations, or for interoperability with external data sources, such as databases and SOAP webservices.
PDF4NET library supports reading and filling existing XFA Forms, all the above field types being supported.

Working with interactive forms

The PDF4NET library allows to accomplish a variety of form related tasks when working PDF forms.
• Create AcroForms - shows how to create AcroFroms using the object model available in PDF4NET library.
• Read and fill AcroForms - shows how to read values from AcroForms and how to fill fields in AcroForms.
• Read and fill XFA Forms - shows how to read values from XFA Forms and how to fill fields in XFA Forms.
• Data import/export - shows how to import and export data from PDF forms.
• Advanced topics - less known things about PDF forms.

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Forms: Create AcroForms

Developer's Guide

Creating AcroForms

PDF4NET library can create fully working PDF forms that can be filled from code or from any interactive PDF viewer application.
All AcroForm fields can be created with PDF4NET library. Throughout the sample code fragments below, the doc variable is a PDFDocument object and page variable is a PDFPage object.
All form related classes are located in O2S.Components.PDF4NET.Forms namespace.

How to create a text box

A text box field is represented in PDF4NET library by PDFTextBoxField class.
A simple text box field can be created with only 3 lines of code:
...
// Create the text box field.
PDFTextBoxField tbx = new PDFTextBoxField( "TextBox1" );
// Set the field's position on page.
tbx.Appearance.Rectangle = new RectangleF( 50, 50, 200, 20 );
// Attach the field to the page.
page.Fields.Add( tbx );
...

The following sample creates a text field with an enhanced visual appearance:
...
// Create the text box field.
PDFTextBoxField tbx = new PDFTextBoxField( "Name" );
// Set a tooltip for the text box.
tbx.Tooltip = "Enter your full name here";
// Set the field's position.
tbx.Appearance.Rectangle = new RectangleF( 50, 50, 200, 20 );
// Use Verdana font, size 10 pt, for the text in the field.
tbx.Appearance.Font = new TrueTypeFont( "verdana.ttf", 10, true );
// Use black color for text.
tbx.Appearance.ForeColor = new PDFColor( 0, 0, 0 );
// Use red color for background.
tbx.Appearance.BackColor = new PDFColor( 255, 0, 0 );
// Create a border around the field.
tbx.Appearance.Border = new PDFFieldBorder( );
// Make the border solid.
tbx.Appearance.Border.Style = FieldBorderStyle.Solid;
// Make the border thin.
tbx.Appearance.Border.Width = 1;
// Use blue for border color.
tbx.Appearance.Border.Color = new PDFColor( 0, 0, 255 );
// Make the field visible.
tbx.Appearance.VisibilityStatus = FieldVisibilityStatus.Visible;
// Align the text in the field to the left.
tbx.Align = FieldTextAlign.Left;
// Limit the text input to 32 characters.
tbx.MaxLen = 32;
// Set the field's text.
tbx.Text = "<Your name here>";
// Set the field's value.
tbx.Value = "";
// Add the text box to the page.
page.Fields.Add( tbx );
...

The Text and Value properties allow to create an interesting effect: when the field does not have focus,
            the Text is displayed, but when the user clicks the field, the Text disappears and the field is empty and
            ready for text input. This helps to create user friendly forms. For this feature to work, the Value must be
            an empty string. If either Text or Value are null (Nothing in VB.NET), when the form is created the one that
            has a value is used both for Text and for Value.

How to create a pushbutton

A pushbutton field is represented in PDF4NET library by PDFPushButtonField class.
Here it is how to create a pushbutton:
...
// Create the push button field.
PDFPushbuttonField btn = new PDFPushbuttonField( "Pushbutton" );
// Set the button's caption.
btn.NormalAppearance.Caption = "Push me";
// Set the button's position.
btn.NormalAppearance.Rectangle = new RectangleF( 50, 150, 200, 20 );
// Use red for button caption.
btn.NormalAppearance.ForeColor = new PDFColor( 255, 0, 0 );
// Use green for button background.
btn.NormalAppearance.BackColor = new PDFColor( 0, 255, 0 );
// Add the button to the page.
page.Fields.Add( btn );
...

A pushbutton can have up to 3 appearances: one for normal button state, called NormalAppearance, one for
            when the mouse is over the button, called RolloverAppearance, and one when the button is pressed, called
            DownAppearance. Normal appearance exists always, the other 2 appearances are optional.
Pushbuttons are used for executing actions inside a form. The following code fragment shows how to
            execute a JavaScript action when the button is pressed:
...
// Create the JavaScript action.
PDFJavaScriptAction js = new PDFJavaScriptAction( );
// Set the action's code to execute.
js.Script = "var f = this.getField(\"Name\");\r\nf.value = \"John Doe\";";
// Attach the action to the button.
btn.Actions.MouseUp = js;
...

Pushbuttons are also used to initiate the submission of form data to a server. The following code fragment
            shows how to create an action that will submit the form data to a server:
...
// Create the submit form action.
PDFSubmitFormAction submitFormAction = new PDFSubmitFormAction( );
// Set the Url where the form data is submitted.
submitFormAction.Url = "http://localhost/fieldsexplorer/fieldsviewer.aspx";
// Attach the action to the button.
btn.Actions.MouseUp = submitFormAction;
...

How to create a checkbox

A checkbox field is represented in PDF4NET library by PDFCheckBoxField class.
Here it is how to create a checkbox:
...
// Create the checkbox field.
PDFCheckBoxField checkBox = new PDFCheckBoxField( "CheckBox" );
// Set the checbox export value.
checkBox.Value = "1";
// Use a checkmark symbol for the checkbox.
checkBox.Style = SymbolStyle.Check;
// Set the checkbox position.
checkBox.CheckedNormalAppearance.Rectangle = new RectangleF( 50, 200, 20, 20 );
// Use black for the checkmark
checkBox.CheckedNormalAppearance.ForeColor = new PDFColor( 0, 0, 0 );
// Use white for the background.
checkBox.CheckedNormalAppearance.BackColor = new PDFColor( 255, 255, 255 );
// Add the checkbox to the page.
page.Fields.Add( checkBox );
...

A checkbox can have up to 3 appearances for each state, checked and unchecked: one for normal checkbox state,
            called CheckedNormalAppearance and UncheckedNormalAppearance, one when the mouse is over the button,
            called CheckedRolloverAppearance and UncheckedRolloverAppearance, and one when the button is pressed, called
            CheckedDownAppearance and UncheckedDownAppearance. Normal appearance exists always, the other 2 appearances are
            optional.

How to create a radiobutton list

A radiobutton list field is represented in PDF4NET library by PDFRadioButtonListField class.
A radiobutton list field consists of several exclusive radiobutton items.
            Here it is how to create a radiobutton list field with 2 radiobutton items:
...
// Create the radiobutton list.
PDFRadioButtonListField rbl = new PDFRadioButtonListField( "Field.4" );
// Use a circle symbol for the radio buttons.
rbl.Style = SymbolStyle.Circle;
// Create first radiobutton item.
PDFRadioButtonItem rbi = new PDFRadioButtonItem( );
// Set the item's export value.
rbi.Value = "1";
// Set the item's position.
rbi.CheckedNormalAppearance.Rectangle = new RectangleF( 50, 250, 20, 20 );
// Use white for the circle symbol.
rbi.CheckedNormalAppearance.ForeColor = new PDFColor( 255, 255, 255 );
// Use black for the background.
rbi.CheckedNormalAppearance.BackColor = new PDFColor( 0, 0, 0 );
// Add the item to the list.
rbl.Items.Add( rbi );
// Create the second item.
PDFRadioButtonItem rbi2 = new PDFRadioButtonItem( );
// Set the item's export value.
rbi2.Value = "2";
// Set the item's position.
rbi2.CheckedNormalAppearance.Rectangle = new RectangleF( 50, 300, 20, 20 );
// Use white for the circle symbol.
rbi2.CheckedNormalAppearance.ForeColor = new PDFColor( 255, 255, 255 );
// Use black for the background.
rbi2.CheckedNormalAppearance.BackColor = new PDFColor( 0, 0, 0 );
// Add the item to the list.
rbl.Items.Add( rbi2 );
// Add the radiobutton list to the page.
page.Fields.Add( rbl );
...

A radiobutton item, like a checkbox, can have up to 3 appearances for each state, checked and unchecked:
            one for normal checkbox state, called CheckedNormalAppearance and UncheckedNormalAppearance, one when
            the mouse is over the button, called CheckedRolloverAppearance and UncheckedRolloverAppearance, and
            one when the button is pressed, called CheckedDownAppearance and UncheckedDownAppearance. Normal appearance
            exists always, the other 2 appearances are optional.

How to create a drop down list

A drop down list field is represented in PDF4NET library by PDFDropDownListField class.
Here it is how to create a drop down list:
...
// Create the drop down list field.
PDFDropDownListField ddl = new PDFDropDownListField( "Dropdownlist" );
// Set its position.
ddl.Appearance.Rectangle = new RectangleF( 50, 400, 200, 20 );
// Add 3 items to the list.
PDFListItem li = new PDFListItem( "Item 1", "1" );
ddl.Items.Add( li );
PDFListItem li2 = new PDFListItem( "Item 2", "2" );
ddl.Items.Add( li2 );
PDFListItem li3 = new PDFListItem( "Item 3", "3" );
ddl.Items.Add( li3 );
// Select the second item.
ddl.SelectedIndex = 1;
// Add the drop down list to the page.
page.Fields.Add( ddl );
...

How to create a list box

A list box field is represented in PDF4NET library by PDFListBoxField class.
Here it is how to create a list box field:
...
// Create the drop down list field.
PDFListBoxField lbx = new PDFListBoxField( "ListBox" );
// Set its position.
lbx.Appearance.Rectangle = new RectangleF( 50, 400, 200, 20 );
// Add 3 items to the list.
PDFListItem li = new PDFListItem( "Item 1", "1" );
lbx.Items.Add( li );
PDFListItem li2 = new PDFListItem( "Item 2", "2" );
lbx.Items.Add( li2 );
PDFListItem li3 = new PDFListItem( "Item 3", "3" );
lbx.Items.Add( li3 );
// Select the second item.
lbx.SelectedIndex = 1;
// Add the list box to the page.
page.Fields.Add( lbx );
...

Other considerations

A field can be added only to the Fields collection of a PDFPage object. If a field is added to the Fields collection of the PDFDocument object, an exception is thrown. The line below throws an exception:
...
doc.Fields.Add( field ); // this line throws an exception.
...

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Forms: Reading and filling AcroForms

Developer's Guide

Reading and filling AcroForms

PDF4NET can read and fill field values in existing PDF forms that have been created with other form design tools.
When a PDF form is loaded with PDF4NET, each field in the form is transformed into a corresponding field object. These fields are available through the Fields collections of PDFDocument object and corresponding PDFPage objects. For each field in the form, a library field object is created:
• text fields - they are available as PDFTextBoxField objects
• pushbutton fields - they are available as PDFPushButtonField objects
• checkbox fields - they are available as PDFCheckBoxField objects
• radiobutton list fields - they are available as PDFRadioButtonListField objects
• drop down list fields - they are available as PDFDropDownListField objects
• list box fields - they are available as PDFListBoxField objects
The Fields collections can be indexed either by field name or by its position. The position of a field in the Fields collection is not related to the position of the field on the page.

The sample below shows how to fill the fields from a PDF document:

...
// Load the PDF form
PDFDocument doc = new PDFDocument( "form.pdf" );
// Fill the fields
doc.Form.Fields["companyName"].Value = "O2 Solutions";
doc.Form.Fields["url"].Value = "http://www.o2sol.com/";
doc.Form.Fields["taxed"].Value = "3";
doc.Form.Fields["country"].Value = "20";
doc.Form.Fields["area"].Value = "2";
// Save the document to disk
doc.SaveToFile( "formfill.pdf" );
...

            If the PDF form already contains values in its fields, these values can be read into application's variables.
            The following code fragment shows how to read field values into local variables:
...
// Load the PDF form
PDFDocument doc = new PDFDocument( "form.pdf" );
// Read the fields
string companyName = doc.Form.Fields["companyName"].Value;
string website = doc.Form.Fields["url"].Value;
string countryCode = doc.Form.Fields["country"].Value;
...

In the samples above the fields are used through the generic PDFField class (all field classes inherit this class). If the specialized properties of a field need to be used, the field object needs to be converted to its native type.
The following sample shows how to inspect the items in a drop down list field:

            ...
// Load the PDF form
PDFDocument doc = new PDFDocument( "form.pdf" );
// Get the countries drop down list
PDFDropDownListField countriesList = doc.Form.Fields["ddlCountry"] as PDFDropDownListField;
// Loop through the list items.
            for( int i = 0; i < countriesList.Items.Count; i++ )
{
// Display the item content.
Console.WriteLine( "Country id-name: {0}-{1)", countriesList.Items[i].Value, countriesList.Items[i].Name );
}
...

Field references can be retrived both from the Fields collection of the PDFDocument object and the corresponding PDFPage objects. When the Fields collections are accessed by numeric index, a field object is always returned. If the Fields collections are accessed by field name, the collection returns null (Nothing in VB.NET) if the field does not exist in the collection.

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Forms: Reading and filling XFA Forms

Developer's Guide

Reading and filling XFA Forms

PDF4NET can read and fill field values in existing XFA forms (embedded in PDF documents) that have been created with other form design tools.
XFA forms have a hierarchical structure which is reflected in the object model available in PDF4NET. A XFA form can include several subforms and fields. Each subform can include also other subforms and fields and this leads to a tree like structure. The tree structure in the XFA form is mapped 1-to-1 to objects in PDF4NET library. The XFA form embedded in a PDF file is available through the XFAForm property of the PDFDocument object. When a XFA form is loaded with PDF4NET, the library creates an object for each support XFA form element:
• subform - XFASubform class
• area - XFAArea class
• pageSet - XFAPageSet class
• pageArea - XFAPageArea class
• field - XFAField class

Form fields are available for read/write operations through the Fields collections of XFASubform, XFAArea and XFAPageArea objects. For each field in the form, a library field object is created:
• text edit fields - they are available as XFATextEditField objects
• password edit fields - they are available as XFAPasswordEditField objects
• numeric edit fields - they are available as XFANumericEditField objects
• datetime edit fields - they are available as XFADateTimeEditField objects
• pushbutton fields - they are available as XFAButtonField objects
• checkbox fields - they are available as XFACheckButtonField objects
• radiobutton list fields - they are available as XFARadioButtonListField objects
• drop down list fields and list boxes - they are available as XFAChoiceField objects
• image fields - they are available as XFAImageEditField objects
• barcode fields - they are available as XFABarcodeField objects
The Fields collections can be indexed either by field name or by its position. The position of a field in the Fields collection is not related to the position of the field on the page.

The sample below shows how to fill the fields from a XFA form:

...
// Load the XFA form
PDFDocument doc = new PDFDocument( "xfasampleform.pdf" );
// Get the main subform.
XFASubform mainSubform = doc.XFAForm.Subforms[0].Subforms[0];
// Fill the product name.
mainSubform.Fields["txtName"].Value = "PDF4NET";
// Fill the product SKU.
mainSubform.Fields["txtSKU"].Value = "PDF4NET01090";
// Fill the product URL.
mainSubform.Fields["txtURL"].Value = "http://www.o2sol.com/pdf4net/products.htm";
// Select the product category.
mainSubform.Fields["ddlCategory"].Value = "PDF";
// Also add a new item to Category drop down list.
XFAListItem listItem = new XFAListItem( "Compression", "CMP" );
( mainSubform.Fields["ddlCategory"] as XFAChoiceListField ).Items.Add( listItem );
// Fill the product image.
mainSubform.Fields["imgProduct"].Value = "pdf4net.jpg";
( mainSubform.Fields["imgProduct"] as XFAImageEditField ).ContentType = "image/jpg";
// Fill the product short description.
mainSubform.Fields["txtShortDescription"].Value = "PDF4NET is a .NET library for adding " +
    "PDF capabilities to .NET applications. It supports both desktop and web applications.";
// Fill the product features.
mainSubform.Fields["txtFeature1"].Value = "Create PDF files from scratch.";
mainSubform.Fields["txtFeature2"].Value = "Merge, split and encrypt PDF files.";
mainSubform.Fields["txtFeature3"].Value = "Create, fill and flatten PDF e-forms.";
mainSubform.Fields["txtFeature4"].Value = "Fill XFA forms.";
mainSubform.Fields["txtFeature5"].Value = "Add, edit and remove document attachments.";
mainSubform.Fields["txtFeature6"].Value = "Add, edit and remove text annotations.";
mainSubform.Fields["txtFeature7"].Value = "Support for WinForms and ASP.NET applications.";
// Fill the product long description.
mainSubform.Fields["txtLongDescription"].Value = "PDF4NET is a .NET library for adding " +
    "PDF capabilities to .NET applications. Version 2.7 brings support for PDF e-form " +
    "creation, support for reading and filling static XFA forms and document attachments. " +
    "It supports both desktop and web applications.";
// Save the document to disk
doc.SaveToFile( "xfasampleform.fill.pdf" );
...

            If the PDF form already contains values in its fields, these values can be read into application's variables.
            The following code fragment shows how to read field values into local variables:
...
// Load the XFA form
PDFDocument doc = new PDFDocument( "xfasampleform.pdf" );
// Get the main subform.
XFASubform mainSubform = doc.XFAForm.Subforms[0].Subforms[0];
// Read the fields
string productName = (string)mainSubform.Fields["companyName"].Value;
string sku = (string)mainSubform.Fields["url"].Value;
byte[] productImage = (byte[])mainSubform.Fields["country"].Value;
...

In the samples above the fields are used through the generic XFAField class (all XFA field classes inherit this class). If the specialized properties of a field need to be used, the field object needs to be converted to its native type.
The following sample shows how to inspect the items in a choice list field:

            ...
// Load the XFA form
PDFDocument doc = new PDFDocument( "xfasamplesform.pdf" );
// Get the main subform.
XFASubform mainSubform = doc.XFAForm.Subforms[0].Subforms[0];
// Get the countries drop down list
XFAChoiceListField countriesList = mainSubform.Fields["ddlCountry"] as XFAChoiceListField;
// Loop through the list items.
            for( int i = 0; i < countriesList.Items.Count; i++ )
{
// Display the item content.
Console.WriteLine( "Country id-name: {0}-{1)", countriesList.Items[i].Value, countriesList.Items[i].Name );
}
...

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Forms: Form data import/export

Developer's Guide

Exporting and importing form data

Data export

Data from PDF forms can be exported to files using several formats, such as FDF, XFDF and XML.
AcroForms data can be exported using all 3 formats, while XFA form data can be exported only as XML.

The following sample shows how to export data from an AcroForm in FDF format:

            ...
// Load the PDF form
PDFDocument doc = new PDFDocument( "form.pdf" );
// Export the form data.
            doc.Form.ExportData( "form_data.fdf", DataFormat.FDF, ExportDataOptions.FormData, "form.pdf" );
            ...

The reason for the last parameter is that FDF and XFDF files require a refernce back to the PDF file they were exported from. Because the PDF file can be loaded from a stream, its name might not be available when exporting the form data.

The next sample shows how to export data from a XFA form in XML format:

            ...
// Load the XFA form
PDFDocument doc = new PDFDocument( "xfasampleform.pdf" );
// Export the form data.
            doc.Form.ExportData( "xfasampleform_data.xml", XFADataFormat.XML );
            ...

Data import

PDF forms can be filled automatically using data files. The data files can have several formats, such as FDF, XFDF and XML.
Data can be imported into AcroForm using all 3 formats, while XFA forms can import only XML data files.

The following sample shows how to import FDF data from into an AcroForm:

            ...
// Load the PDF form
PDFDocument doc = new PDFDocument( "form.pdf" );
// Import the form data.
            doc.Form.ImportData( "form_data.fdf", DataFormat.FDF );
            ...

The next sample shows how to import XML data into a XFA form:

            ...
// Load the XFA form
PDFDocument doc = new PDFDocument( "xfasampleform.pdf" );
// Import the form data.
            doc.Form.ImportData( "xfasampleform_data.xml", XFADataFormat.XML );
            ...

The data files can be created by exporting form data or using 3rd party tools to create them. While FDF format is more complex and difficult to create, the XML and XFDF (also XML based) formats are easier to create by external tools.

© 2003 - 2007 O2 Solutions. All rights reserved.


PDF Forms: Advanced topics

Developer's Guide

Advanced form topics

AcroForm advanced topics

This section applies to AcroForms only.

Fields and widgets

An AcroForm field consists of 2 parts: the logical field that stores the field value and the visual part that displays the field value on the form. The visual part of the field is called widget. Any field has always at least a widget, but there are situations when a field can have multiple widgets. A field with multiple widgets appears to the user (in the PDF viewer) as multiple fields but all with the same name. Because the logical field stores the value, all widgets will display always the same value.

When a form is loaded, the Fields collections are filled with the logical fields, and not with the field widgets. Each PDFField object corresponds to a logical field. For example, if an AcroForm contains 7 fields with the same name (they are in fact a single field with 7 widgets), when it is loaded the in PDF4NET, the Fields collection of the PDFDocument object will have only one field.

After loading a PDF form, each field activates its first widget (first widget does not mean the first field appearance in the document or on the page, but the first widget that has been read from the PDF file). The library allows to activate each field widget, one at a time. The position, fore and back color and border (available through Appearance properties) are widget specific.

The following sample shows how to inspect all field widgets:

...
// Load the PDF form
PDFDocument doc = new PDFDocument( "form.pdf" );
// Get the field with multiple widgets.
PDFTextBoxField multiWidgetTextBox = (PDFTextBoxField)doc.Form.Fields["fullName"];
// Activate first widget (all fields have always at least a widget).
multiWidgetTextBox.ActivateFirstWidget();
// Inspect widget properties, like position and colors.
...
// Loop through all the other widgets if they exist
while(multiWidgetTextBox.ActivateNextWidget()) // ActivateNextWidget returns false when there are no more widgets.
{
    // Inspect current widget properties, like position and colors.
    // multiWidgetTextBox.Appearance property corresponds to active widget information.
    ...
}
...

The code above behaves different based on how the field reference was obtained. If the field reference was obtained from the document (like in the sample above), then the code iterates through all the field widgets in the document.
If the field reference was obtained from the page, like this:
...
PDFTextBoxField multiWidgetTextBox = (PDFTextBoxField)page.Fields["fullName"];
...
 then the code iterates through all the field widgets on the page the field reference was obtained from.

PDF4NET library can create fields with multiple widgets by creating field objects with the same name.
The following code creates a text box field with 2 widgets:
...
// Create the first text box field.
PDFTextBoxField tbx1 = new PDFTextBoxField( "MultiWidgetTextBox" );
// Set the field's position on page.
tbx1.Appearance.Rectangle = new RectangleF( 50, 50, 200, 20 );
// Attach the field to the page.
page.Fields.Add( tbx1 );
// Create the second text box field.
PDFTextBoxField tbx2 = new PDFTextBoxField( "MultiWidgetTextBox" );// The same field name is used.
// Set the field's position on page.
tbx2.Appearance.Rectangle = new RectangleF( 50, 100, 200, 20 );
// Attach the field to the page.
page.Fields.Add( tbx2 );
...

The code above generates a text box field with 2 widgets. Also, after the above code is executed, the Fields collection
            of the page object contains only one element (the MultiWidgetTextBox field), not two. A side effect of the above code is
            that after tbx2 object is added to the page, the library merges its information with the first field (tbx1) and tbx2 is
            no longer a valid field reference.

How to merge identical AcroForms but with different data.

            A common requirement is to merge multiple AcroForms that are identical as structure,
            but each one containing different data. Because the AcroForms have identical structure, when they are merged, the fields
            are also merged (fields with the same name appear in each AcroForm) and the final document keeps the data only from the
            first form used in the merge process, and this data is propagated to all the other forms. In order to avoid this to happen,
            each form needs to be flattened after it has been inserted in the main document. Fields flattening is the process that
            transforms all fields into plain PDF content, therefore making the fields no longer editable. Fields flattening is a
            distructive process, the field definitions are removed from the document and they can no longer be recovered. It is
            important to mention that this process takes place on the in-memory copy of the form, the actual form is not affected.
The following sample shows how to merge the forms into a single document and also keep the form data intact:
...
// Create a new PDF document that will store the merged forms.
PDFDocument doc = new PDFDocument( );
// Let's assume the GetFormsToMerge method returns the list of forms.
string[] formFiles = GetFormsToMerge();
// Loop through all the forms
for( int i = 0; i < formFiles.Length; i++ ).
{
// Open the form file.
PDFFile file = PDFFile.FromFile(formFiles[i]);
// Let's assume each form is one page length.
// Extract the page containing the form.
PDFImportedPage page = file.ExtractPage(0);
// Insert the page in the new document.
doc.AddPage(page);
// Flatten the form fields.
doc.Form.FlattenFormFields;
}
// Save the final document.
doc.SaveToFile("mergedforms.pdf");

© 2003 - 2007 O2 Solutions. All rights reserved.


Barcodes

PDF4NET library provides native support for dislaying barcodes in PDF document. The library supports both 1D and 2D barcode symbologies. The library validates the data automatically and computes the check characters as needed. The size of the barcodes is computed automatically based on encoded data and XDimension and YDimension properties.

The following code fragment shows the minimum required code to display a Code39 barcode in a PDF page:
PDFDocument doc = new PDFDocument( )
PDFPage page = new PDFPage( )
// Create and draw the barcode
PDFCode39Barcode c39 = new PDFCode39Barcode( "CODE39" );
page.Canvas.DrawBarcode( c39, 20, 570 );
// Save the PDF file
doc.SaveToFile( "Code39.pdf" );

All barcode related classes are included in the following namespace: O2S.Components.PDF4NET.Graphics.Barcodes

© 2003 - 2007 O2 Solutions. All rights reserved.


Barcode symbologies

PDF4NET supports both 1D and 2D barcode symbologies. 1D symbologies are also called linear or unidimensional symbologies and 2D symbologies are also called bidimensional symbologies.
The following barcode symbologies are supported by PDF4NET library:

1D Symbologies
Codabar | Codabar
 | Also known as: USD-4 | NW-7 | Code 2 of 7
 | Codabar symbology was developer by Pitney Bowes, Inc in 1972. It is a discrete and self-checking symbology that supports 16 different characters for encoding. Because it is a self-checking symbology, it does not have a checksum character. EnableCheckSum and DisplayCheckSum properties have no effect on this symbology. Codabar symbology uses start and stop characters to mark the beginning and the end of the barcode. The start/stop characters are not returned by barcode reader when the barcode is scanned. Codabar symbology is used by U.S. blood banks, photo labs, and on FedEx airbills.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9 - $ : / . +
 | Required data length: Variable.
Code 11 | Code 11
 | Also known as: USD-8
 | Code 11 is a high density numeric only symbology. The symbology is discrete and is able to encode the numbers 0 through 9, the dash symbol (-) and start/stop characters. Code 11 symbology uses start and stop characters to mark the beginning and the end of the barcode. The start/stop characters are not returned by barcode reader when the barcode is scanned. This symbology is not very secure, printing defects can convert one character into another vald character. Because of this, Code 11 supports one or two check characters, depending on data length. If data length is less than 10, only one check character is used, otherwise two check characters are used. PDF4NET automatically computes the check characters if EnableCheckSum property is true. Code 11 symbology is used primarily in labeling telecommunications equipment.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9 -
 | Required data length: Variable.
Code 128A | Code 128A
 | Code 128A is a high density alphanumeric symbology that uses codeset A of Code 128. The symbology is self-checking and also requires check digit (EnableCheckSum property is true by default and the check character is computed automatically) for greater security. Code 128A symbology is used primarily in applications where large amounts of data must be encoded in a small space.
 | Allowed characters: NUL (0x00) SOH (0x01) STX (0x02) ETX (0x03) EOT (0x04) ENQ (0x05) ACK (0x06) BEL (0x07) BS (0x08) HT (0x09) LF (0x0A) VT (0x0B) FF (0x0C) CR (0x0D) SO (0x0E) SI (0x0F) DLE (0x10) DC1 (0x11) DC2 (0x12) DC3 (0x13) DC4 (0x14) NAK (0x15) SYN (0x16) ETB (0x17) CAN (0x18) EM (0x19) SUB (0x1A) ESC (0x1B) FS (0x1C) GS (0x1D) RS (0x1E) US (0x1F) SPACE (0x20) ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ]^ _
 | Required data length: Variable.
Code 128B | Code 128B
 | Code 128B is a high density alphanumeric symbology that uses codeset B of Code 128. The symbology is self-checking and also requires check digit (EnableCheckSum property is true by default and the check character is computed automatically) for greater security. Code 128B symbology is used primarily in applications where large amounts of data must be encoded in a small space.
 | Allowed characters: SPACE (0x20) ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ]^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ DEL (\x7F)
 | Required data length: Variable.
Code 128C | Code 128C
 | Code 128C is a high density numberic only symbology that uses codeset C of Code 128. The symbology is self-checking and also requires check digit (EnableCheckSum property is true by default and the check character is computed automatically) for greater security. Code 128C symbology is used primarily in applications where large amounts of numeric data must be encoded in a small space, because each pair of digits is encoded as a single barcode symbol.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: Variable.
Code 2 of 5 | Code 2 of 5
 | Also known as: Standard 2 of 5 | Industrial 2 of 5
 | Code 2 of 5 is a low density numeric only symbology. It has been in use since 1960. This symbology may include an optional check character. PDF4NET automatically computes the check character if EnableCheckSum property is true. A newer version of this symbology is Code 2 of 5 Interleaved which achieves a higher density. Code 2 of 5 is used for sequentially numbering airline tickets, for photofinishing and warehouse sorting industries.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: Variable.
Code 2 of 5 Interleaved | Code 2 of 5 Interleaved
 | Also known as: Interleaved 2 of 5
 | Code 2 of 5 Interleaved is a high density numeric only symbology and it is a newer version of Code 2 of 5. This symbology may include an optional check character. PDF4NET automatically computes the check character if EnableCheckSum property is true. Code 2 of 5 is used in distribution and warehouse industry.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: Variable.
Code 39 | Code 39
 | Also known as: USD-3 | Code 3 of 9 | LOGMARS
 | Code 39 is the first developed barcode symbology. It is self checking and may include an optional check character. PDF4NET automatically computes the check character if EnableCheckSum property is true. Code 39 is used by the United States Department of Defense, by the Health Industry Bar Code Council (HIBCC) and also in non-retail environments.
 | Allowed characters: 1 2 3 4 5 6 7 8 9 0 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - . $ / + % SPACE.
 | Required data length: Variable.
Code 39 Extended | Code 39 Extended
 | Also known as: USD-3 | Code 3 of 9 | LOGMARS
 | Code 39 Extended is based on Code 39 and supports all 128 ASCII characters.
 | Allowed characters: All 128 ASCII characters.
 | Required data length: Variable.
Code 93 | Code 93
 | Also known as: USS-93
 | Code 93 symbology was designed to improve and complement the Code 39 symbology. It supports 47 different characters to encode. Two check characters are required (EnableCheckSum property is true by default) and they are computed automatically.
 | Allowed characters: 1 2 3 4 5 6 7 8 9 0 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - . $ / + % SPACE.
 | Required data length: Variable.
Code 93 Extended | Code 93 Extended
 | Also known as: USS-93
 | Code 93 Extended is based on Code 93 and supports all 128 ASCII characters.
 | Allowed characters: All 128 ASCII characters.
 | Required data length: Variable.
COOP 2 of 5 | COOP 2 of 5
 | Also known as: COOP 25
 | COOP 2 of 5 is a numeric only symbology. It is self checking and it may include an optional check character. PDF4NET automatically computes the check character if EnableCheckSum property is true. COOP 2 of 5 is used for management of physical distribution.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: Variable.
EAN-13 | EAN-13
 | EAN-13 is a numeric only symbology based on UPC-A standard (it is a super set of UPC-A). It is self checking and it requires a check character. PDF4NET automatically computes the check character regardless of EnableCheckSum property and the check character is always displayed regardless of DisplayCheckSum property. EAN-13 barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement. EAN-13 was implemented by the International Article Numbering Association (EAN) in Europe and it uses 2 digits for the number system code.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 12 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
EAN-8 | EAN-8
 | EAN-8 is a numeric only symbology, the "short" version of EAN-13 designed for small packages. It is self checking and it requires a check character. PDF4NET automatically computes the check character regardless of EnableCheckSum property and the check character is always displayed regardless of DisplayCheckSum property. EAN-8 barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 7 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
IATA 2 of 5 | IATA 2 of 5
 | IATA 2 of 5 is a numeric only symbology. It is self checking and a check character is always required. PDF4NET automatically computes the check character if EnableCheckSum property is true (this is default). IATA 2 of 5 is used by IATA (International Air Transport Association) for the management of air cargo.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: 16 digits.
ISBN | ISBN
 | ISBN (International Standard Book Numbering) is a EAN-13 symbology that uses the number system 978. ISBN barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement. This symbology is used for labeling books.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 9 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
ISMN | ISMN
 | ISMN (International Standard Music Number) is a EAN-13 symbology that uses the number system 979. ISMN barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement. This symbology is used for labeling music casettes and CDs.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 9 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
ISSN | ISSN
 | ISSN (International Standard Serial Number for Periodicals) is a EAN-13 symbology that uses the number system 977. ISSN barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement. This symbology is used for labeling periodicals and newspapers.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 9 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
JAN-13 | JAN-13
 | JAN-13 is a EAN-13 symbology that uses the number system 49. JAN-13 barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement. This symbology is used in Japan in retail applications.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 10 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
Matrix 2 of 5 | Matrix 2 of 5
 | Matrix 2 of 5 is a numeric only symbology. It is self checking and an optional check character may be included. PDF4NET automatically computes the check character if EnableCheckSum property is true.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: Variable.
MSI/Plessey | MSI/Plessey
 | Also known as: Modified Plessey
 | MSI/Plessey is a numeric only symbology. It was developed by MSI Data Corporation, based on the original Plessey Code. It is not self checking but an optional check character may be included. PDF4NET automatically computes the check character if EnableCheckSum property is true. This symbology is used primarily to mark retail shelves for inventory control.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: Variable.
Planet | Planet
 | Planet is a height modulated numeric only symbology, it is the inverse of PostNet symbology. A check character is required and it is computed automatically regardless of EnableCheckSum property. This symbology is used in combination with PostNet by USPS to track customer's piece of mail.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: 11 or 13 digits.
Postnet | Postnet
 | Postnet is a height modulated numeric only symbology. It was created by USPS to allow faster sorting and routing of mail. A check character is required and it is computed automatically regardless of EnableCheckSum property. Postnet barcodes can encode 5 digits (ZIP code), 9 digits (ZIP+4) or 11 digits (full delivery point). This symbology is used by USPS to allow faster sorting and routing of mail.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: 5, 9 or 11 digits.
RM4SCC | RM4SCC
 | RM4SCC (Royal Mail 4-state Customer Code) is a height modulated symbology. A check character is required and it is computed automatically regardless of EnableCheckSum property. This symbology is used by UK Royal Mail to allow faster sorting and routing of mail.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
 | Required data length: Variable.
SCC-14 | SCC-14
 | SCC-14 (Shipping Container Code 14) is a numeric only symbology based on Code 128C. It is in fact a Code 128C barcode with a fixed data format. A check character is required and it is computed automatically regardless of EnableCheckSum property. SCC-14 is part of the larger UCC/EAN-128 specification with application identifier 01, and it is a shorter version of SSCC-18 symbology. Shipping Container Code is used to identify individual shipping containers. This is used, generally, to establish a number that is unique worldwide to track a specific container.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: 13 digits.
SSCC-18 | SSCC-18
 | SSCC-18 (Serial Shipping Container Code 18) is a numeric only symbology based on Code 128C. It is in fact a Code 128C barcode with a fixed data format. A check character is required and it is computed automatically regardless of EnableCheckSum property. SCC-18 is part of the larger UCC/EAN-128 specification with application identifier 00. Serial Shipping Container Code is used to identify individual shipping containers. This is used, generally, to establish a number that is unique worldwide to track a specific container.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length: 17 digits.
UPC-A | UPC-A
 | UPC-A is a numeric only symbology. It is self checking and it requires a check character. PDF4NET automatically computes the check character regardless of EnableCheckSum property and the check character is always displayed regardless of DisplayCheckSum property. UPC-A barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement. UPC-A is widely used in United States in retail.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 11 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
UPC-E | UPC-E
 | UPC-E is a numeric only symbology, a shorter version of UPC-A symbology. It is self checking and it requires a check character. PDF4NET automatically computes the check character regardless of EnableCheckSum property and the check character is always displayed regardless of DisplayCheckSum property. UPC-E barcodes allow a secondary barcode, called supplement, to be added to main barcode. PDF4NET supports both 2 and 5 digits supplement. UPC-E is widely used in United States in retail and it is used instead of UPC-A for products with very small packaging.
 | Allowed characters: 0 1 2 3 4 5 6 7 8 9
 | Required data length for main barcode: 7 digits.
 | Required data length for supplement barcode: 2 or 5 digits.
2D Symbologies
CODABLOCK F | CODABLOCK F
 | CODABLOCK F is is multirow symbology, a 2D version of Code 128. It was created at ICS Identcode-Systeme, being invented by Heinrich Oehlmann.
 | Allowed characters: All 256 ISO 8859-1 characters.
 | Required data length: Variable, up to 2725 characters.
Code 16K | Code 16K
 | Code 16K is is multirow symbology based on Code 128. It was created by Ted Williams in 1989.
 | Allowed characters: All 256 ISO 8859-1 characters.
 | Required data length: Variable, up to 77 ASCII characters or 154 numeric characters.
DataMatrix | DataMatrix
 | DataMatrix is a 2D matrix symbology made up of square modules arranged within a perimeter finder pattern. A limited set of symbol sizes, both square and rectangular, is available, together with a fixed level of error correction for each symbol size. PDF4NET uses ECC200 version of DataMatrix symbology.
 | Allowed characters: All 256 ISO 8859-1 characters.
 | Required data length: Variable, up to 1556 bytes or 2335 alphanumeric characters or 3116 numeric characters.
MicroPDF417 | MicroPDF417
 | MicroPDF417 is a multi-row symbology, derived from and closely based on PDF417. MicroPDF417 is designed for applications with a need for improved area efficiency but without the requirement for PDF417's maximum data capacity. A limited set of symbol sizes is available, together with a fixed level of error correction for each symbol size.
 | Allowed characters: All 256 ISO 8859-1 characters.
 | Required data length: Variable, up to 150 bytes or 250 alphanumeric characters or 366 numeric characters.
PDF417 | PDF417
 | PDF417 is a multi-row, variable-length symbology that offers high data capacity and error correction capabilities. Up to 2700 characters can be encoded depending on the selected data compaction mode. PDF4NET supports all 3 data compaction modes: Text, Byte and Numeric.
 | Allowed characters: All 256 ISO 8859-1 characters.
 | Required data length: Variable, up to 1108 bytes or 1850 alphanumeric characters or 2710 numeric characters.

© 2003 - 2007 O2 Solutions. All rights reserved.


Samples

The following samples are available. They cover all the features of the PDF4NET library.

Samples

3D

Actions

Annotations

ArcsPies - Supported by Compact .NET Edition

Attachments

Autonumbering - Supported by Compact .NET Edition

Barcodes

Bezier - Supported by Compact .NET Edition

Bookmarks - Supported by Compact .NET Edition

CharacterMap - Supported by Compact .NET Edition

ColorSpaces

Digital Signature

DocAndViewer - Supported by Compact .NET Edition

Edit PDF

Ellipses - Supported by Compact .NET Edition

Encryption - Supported by Compact .NET Edition

ExtractImages

Forms

Form XObjects

GroupingGrid - Supported by Compact .NET Edition

HelloWorld - Supported by Compact .NET Edition

Images - Supported by Compact .NET Edition

Layers

Lines - Supported by Compact .NET Edition

Links - Supported by Compact .NET Edition

Metafiles

MulticolumnTextAndImages

PageOrientations - Supported by Compact .NET Edition

PageSizes - Supported by Compact .NET Edition

Pantone colors

Paths

Polygons - Supported by Compact .NET Edition

RandomAccess - Supported by Compact .NET Edition

Rectangles - Supported by Compact .NET Edition

SaveProgress

SimpleGrid - Supported by Compact .NET Edition

Sin(x) Graph

SlideShow

Stamp PDF

Templates - Supported by Compact .NET Edition

TextBoxes - with TrueType font support - Supported by Compact .NET Edition (no TrueType)

TextLines - Supported by Compact .NET Edition

Tiff2PDF

Unicode - Supported by Compact .NET Edition (CJK Fonts only)

Update PDF - Supported by Compact .NET Edition

Watermarks

© 2003 - 2007 O2 Solutions. All rights reserved.


Samples: 3D

Samples

3D

This sample shows how to embed 3D artwork (U3D data) in PDF files. It shows how to work with 3D annotations, projections, render modes and lighting schemes.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


3D.cs

using System;
using System.IO;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Annotations;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to embed 3D artwork in PDF files.
    /// </summary>
    class _3DArtwork
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument();

            // Create a blank page
            PDFPage page = doc.AddPage();

            // Create the annotation that will display the 3D artwork.
            PDF3DAnnotation annot3d = new PDF3DAnnotation();
            annot3d.Rectangle = new RectangleF(50, 50, 400, 400);
            annot3d.Stream = Create3DStream();
            annot3d.Appearance = new PDFFormXObject();
            annot3d.Appearance.Canvas.DrawText("Click to activate", new PDFFont(),
                null, new PDFBrush(new PDFColor()), 200, 200, 0, TextAlign.MiddleCenter);

            // Create the default view.
            PDF3DProjection projection1 = new PDF3DProjection(PDF3DProjectionType.Perspective);
            projection1.FieldOfView = 30;
            PDF3DLightingScheme lightScheme1 = null;//new PDF3DLightingScheme(PDF3DLightingStyle.Artwork);
            PDF3DRenderMode renderMode1 = new PDF3DRenderMode(PDF3DRenderStyle.Solid);
            PDF3DBackground background1 = new PDF3DBackground(new PDFColor(255, 255, 255));
            PDF3DView defaultView = CreateView("Default view",
                new float[]{-0.382684f, 0.92388f, -0.0000000766026f, 0.18024f, 0.0746579f, 0.980785f, 0.906127f, 0.37533f, -0.19509f, -122.669f, -112.432f, 45.6829f},
                131.695f, background1, projection1, renderMode1, lightScheme1);

            // Create a wireframe view.
            PDF3DRenderMode renderMode2 = new PDF3DRenderMode(PDF3DRenderStyle.Wireframe);
            PDF3DView wireframeView = CreateView("Wireframe view",
                new float[]{-0.382684f, 0.92388f, -0.0000000766026f, 0.18024f, 0.0746579f, 0.980785f, 0.906127f, 0.37533f, -0.19509f, -122.669f, -112.432f, 45.6829f},
                131.695f, background1, projection1, renderMode2, lightScheme1);

            // Create a wireframe view.
            PDF3DRenderMode renderMode3 = new PDF3DRenderMode(PDF3DRenderStyle.TransparentWireframe);
            renderMode3.AuxiliaryColor = new PDFColor(0, 192, 0);
            PDF3DView transparentWireframeView = CreateView("Transparent wireframe view",
                new float[]{-0.382684f, 0.92388f, -0.0000000766026f, 0.18024f, 0.0746579f, 0.980785f, 0.906127f, 0.37533f, -0.19509f, -122.669f, -112.432f, 45.6829f},
                131.695f, background1, projection1, renderMode3, lightScheme1);

            annot3d.Stream.Views.Add(defaultView);
            annot3d.Stream.Views.Add(wireframeView);
            annot3d.Stream.Views.Add(transparentWireframeView);
            annot3d.Stream.DefaultView = 0;

            // Add the annotation to the page.
            page.Annotations.Add(annot3d);

            doc.Save("3d.pdf", true);
        }

        /// <summary>
        /// Creates the 3D stream.
        /// </summary>
        private static PDF3DStream Create3DStream()
        {
            // Read the U3D file.
            FileStream fs = new FileStream("box.u3d", FileMode.Open, FileAccess.Read);
            byte[] u3data = new byte[fs.Length];
            fs.Read(u3data, 0, u3data.Length);
            fs.Close();

            PDF3DStream stream = new PDF3DStream();
            stream.Content = u3data;

            return stream;
        }

        /// <summary>
        /// Creates a view for the 3D artwork.
        /// </summary>
        private static PDF3DView CreateView(string viewName, float[] camera2world, float centerOfOrbit,
            PDF3DBackground background, PDF3DProjection projection, PDF3DRenderMode renderMode, PDF3DLightingScheme lightingScheme)
        {
            PDF3DView view = new PDF3DView();
            view.ExternalName = viewName;
            view.InternalName = Guid.NewGuid().ToString("N");
            view.CameraToWorldMatrix = camera2world;
            view.CenterOfOrbit = centerOfOrbit;
            view.Background = background;
            view.Projection = projection;
            view.RenderMode = renderMode;
            view.LightingScheme = lightingScheme;
            view.ResetNodesState = true;

            return view;
        }
    }
}


3D.vb

Imports System
Imports System.IO
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Annotations
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to embed 3D artwork in PDF files.
'/ </summary>

Class _3DArtwork

    '/ <summary>
    '/ The main entry point for the application.
    '/ </summary>
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument()

        '// Create a blank page
        Dim page As PDFPage = doc.AddPage()

        '// Create the annotation that will display the 3D artwork.
        Dim annot3d As PDF3DAnnotation = New PDF3DAnnotation()
        annot3d.Rectangle = New RectangleF(50, 50, 400, 400)
        annot3d.Stream = Create3DStream()
        annot3d.Appearance = New PDFFormXObject()
        annot3d.Appearance.Canvas.DrawText("Click to activate", New PDFFont(), _
            Nothing, New PDFBrush(New PDFColor()), 200, 200, 0, TextAlign.MiddleCenter)

        '// Create the default view.
        Dim projection1 As PDF3DProjection = New PDF3DProjection(PDF3DProjectionType.Perspective)
        projection1.FieldOfView = 30
        Dim lightScheme1 As PDF3DLightingScheme = New PDF3DLightingScheme(PDF3DLightingStyle.Artwork)
        Dim renderMode1 As PDF3DRenderMode = New PDF3DRenderMode(PDF3DRenderStyle.Solid)
        Dim background1 As PDF3DBackground = New PDF3DBackground(New PDFColor(255, 255, 255))
        Dim defaultView As PDF3DView = CreateView("Default view", _
            New Single() {-0.382684F, 0.92388F, -0.0000000766026F, 0.18024F, 0.0746579F, 0.980785F, 0.906127F, 0.37533F, -0.19509F, -122.669F, -112.432F, 45.6829F}, _
            131.695F, background1, projection1, renderMode1, lightScheme1)

        '// Create a wireframe view.
        Dim renderMode2 As PDF3DRenderMode = New PDF3DRenderMode(PDF3DRenderStyle.Wireframe)
        Dim wireframeView As PDF3DView = CreateView("Wireframe view", _
            New Single() {-0.382684F, 0.92388F, -0.0000000766026F, 0.18024F, 0.0746579F, 0.980785F, 0.906127F, 0.37533F, -0.19509F, -122.669F, -112.432F, 45.6829F}, _
            131.695F, background1, projection1, renderMode2, lightScheme1)

        '// Create a wireframe view.
        Dim renderMode3 As PDF3DRenderMode = New PDF3DRenderMode(PDF3DRenderStyle.TransparentWireframe)
        renderMode3.AuxiliaryColor = New PDFColor(0, 192, 0)
        Dim transparentWireframeView As PDF3DView = CreateView("Transparent wireframe view", _
            New Single() {-0.382684F, 0.92388F, -0.0000000766026F, 0.18024F, 0.0746579F, 0.980785F, 0.906127F, 0.37533F, -0.19509F, -122.669F, -112.432F, 45.6829F}, _
            131.695F, background1, projection1, renderMode3, lightScheme1)

        annot3d.Stream.Views.Add(defaultView)
        annot3d.Stream.Views.Add(wireframeView)
        annot3d.Stream.Views.Add(transparentWireframeView)
        annot3d.Stream.DefaultView = 0

        '// Add the annotation to the page.
        page.Annotations.Add(annot3d)

        doc.Save("3d.pdf", True)

    End Sub 'Main

    '/// <summary>
    '/// Creates the 3D stream.
    '/// </summary>
    Private Shared Function Create3DStream() As PDF3DStream
        '// Read the U3D file.
        Dim fs As FileStream = New FileStream("box.u3d", FileMode.Open, FileAccess.Read)
        Dim u3data(fs.Length) As Byte
        fs.Read(u3data, 0, u3data.Length)
        fs.Close()

        Dim stream As PDF3DStream = New PDF3DStream()
        stream.Content = u3data

        Return stream
    End Function

    '/// <summary>
    '/// Creates a view for the 3D artwork.
    '/// </summary>
    Private Shared Function CreateView(ByVal viewName As String, ByVal camera2world As Single(), ByVal centerOfOrbit As Single, _
    ByVal background As PDF3DBackground, ByVal projection As PDF3DProjection, ByVal renderMode As PDF3DRenderMode, ByVal lightingScheme As PDF3DLightingScheme) As PDF3DView
        Dim view As PDF3DView = New PDF3DView()
        view.ExternalName = viewName
        view.InternalName = Guid.NewGuid().ToString("N")
        view.CameraToWorldMatrix = camera2world
        view.CenterOfOrbit = centerOfOrbit
        view.Background = background
        view.Projection = projection
        view.RenderMode = renderMode
        view.LightingScheme = lightingScheme
        view.ResetNodesState = True

        Return view
    End Function
End Class '_3DArtwork


Samples: Actions

Samples

Actions

This sample demonstrates the support for PDF actions implemented in PDF4NET library.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Actions.cs

/// <fileName>
/// File name: Actions.cs.
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Actions;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Actions
{
    /// <summary>
    /// This sample shows how to use the PDF actions.
    /// </summary>
    class Actions
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create 3 pages
            PDFPage page = doc.AddPage( );
            page.Canvas.DrawText( "Page 1", fontText, null, blackBrush, 20, 30 );
            page = doc.AddPage( );
            page.Canvas.DrawText( "Page 2", fontText, null, blackBrush, 20, 30 );
            page = doc.AddPage( );
            page.Canvas.DrawText( "Page 3", fontText, null, blackBrush, 20, 30 );

            /// URI Action
            // create a web action
            PDFURIAction uriAction = new PDFURIAction( );
            uriAction.URI = "http://www.o2sol.com/";

            // create a bookmark to point to the url above
            PDFOutline url = new PDFOutline( "www.o2sol.com",
                new PDFColor( ), false, OutlineDisplay.Regular, uriAction );

            // add the bookmark to the document
            doc.Outlines.Add( url );
            /// URI Action

            /// Javascript Action
            // create a javascript action to print the document
            PDFJavaScriptAction jsAction = new PDFJavaScriptAction( );
            jsAction.Script = "this.print(true);\n";

            // create a bookmark to point to execute the action
            PDFOutline js = new PDFOutline( "Print me from JavaScript",
                new PDFColor( ), false, OutlineDisplay.Regular, jsAction );

            // add the bookmark to the document
            doc.Outlines.Add( js );
            /// Javascript Action

            /// OpenDocument action
            // Create an action to be executed when the document is opened
            // The action will open the document at the
            // second page of the document using a 800% zoom
            PDFGoToAction goToAction = new PDFGoToAction( );
            goToAction.Page = doc.Pages[1];
            goToAction.MagnificationMode = MagnificationMode.XYZ;
            goToAction.Left = 0;
            goToAction.Top = 0;
            goToAction.Zoom = 800;

            // set the action on the document
            doc.OpenAction = goToAction;
            /// OpenDocument action

            // Save the document to disk
            doc.SaveToFile( "actions.pdf" );
        }
    }
}


Actions.vb

'
' File name: Actions.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Actions
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to use the PDF actions.
'/ </summary>

Class Actions

    '/ <summary>
    '/ The main entry point for the application.
    '/ </summary>
    <STAThread()>  _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument()

        ' Create the graphic objects
        Dim fontText As New PDFFont(FontFace.Helvetica, 12)
        Dim blackBrush As New PDFBrush(New PDFColor())

        ' Create 3 pages
        Dim page As PDFPage = doc.AddPage()
        page.Canvas.DrawText("Page 1", fontText, Nothing, blackBrush, 20, 30)
        page = doc.AddPage()
        page.Canvas.DrawText("Page 2", fontText, Nothing, blackBrush, 20, 30)
        page = doc.AddPage()
        page.Canvas.DrawText("Page 3", fontText, Nothing, blackBrush, 20, 30)

        '/ URI Action
        ' create a web action
        Dim uriAction As New PDFURIAction()
        uriAction.URI = "http://www.o2sol.com/"

        ' create a bookmark to point to the url above
        Dim url As New PDFOutline("www.o2sol.com", New PDFColor(), False, OutlineDisplay.Regular, uriAction)

        ' add the bookmark to the document
        doc.Outlines.Add(url)
        '/ URI Action
        '/ Javascript Action
        ' create a javascript action to print the document
        Dim jsAction As New PDFJavaScriptAction()
        jsAction.Script = "this.print(true);" + vbLf

        ' create a bookmark to point to execute the action
        Dim js As New PDFOutline("Print me from JavaScript", New PDFColor(), False, OutlineDisplay.Regular, jsAction)

        ' add the bookmark to the document
        doc.Outlines.Add(js)
        '/ Javascript Action
        '/ OpenDocument action
        ' Create an action to be executed when the document is opened
        ' The action will open the document at the
        ' second page of the document using a 800% zoom
        Dim goToAction As New PDFGoToAction()
        goToAction.Page = doc.Pages(1)
        goToAction.MagnificationMode = MagnificationMode.XYZ
        goToAction.Left = 0
        goToAction.Top = 0
        goToAction.Zoom = 800

        ' set the action on the document
        doc.OpenAction = goToAction
        '/ OpenDocument action
        ' Save the document to disk
        doc.SaveToFile("actions.pdf")

    End Sub 'Main
End Class 'Actions


Samples: Annotations

Samples

Annotations

This sample demonstrates the support for PDF annotations implemented in PDF4NET library.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Annotations.cs

/// <fileName>
/// File name: Annotations.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Annotations;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Annotations
{
    /// <summary>
    /// This sample shows all annotations that can be created with PDF4NET.
    /// </summary>
    class Annotations
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Create one page
            PDFPage page = doc.AddPage( );

            PDFBrush blackBrush = new PDFBrush( new PDFColor( 0, 0, 0 ) );
            PDFFont fontSection = new PDFFont( FontFace.Helvetica, 10 );
            fontSection.Bold = true;
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 8 );

            page.Canvas.DrawText( "Text annotations", fontSection, null, blackBrush, 20, 45, 0, TextAlign.BottomLeft );
            // Create all available text annotations
            PDFTextAnnotation ta = new PDFTextAnnotation( "Comment", "Comment annotation" );
            ta.Icon = TextAnnotationIcon.Comment;
            ta.Rectangle = new RectangleF( 20, 60, 100, 100 );
            page.Annotations.Add( ta );
            page.Canvas.DrawText( "Comment", fontText, null, blackBrush, 20, 80, 0, TextAlign.TopLeft );

            ta = new PDFTextAnnotation( "Help", "Help annotation" );
            ta.Icon = TextAnnotationIcon.Help;
            ta.Rectangle = new RectangleF( 100, 60, 100, 100 );
            page.Annotations.Add( ta );
            page.Canvas.DrawText( "Help", fontText, null, blackBrush, 100, 80, 0, TextAlign.TopLeft );

            ta = new PDFTextAnnotation( "Insert", "Insert annotation" );
            ta.Icon = TextAnnotationIcon.Insert;
            ta.Rectangle = new RectangleF( 180, 60, 100, 100 );
            page.Annotations.Add( ta );
            page.Canvas.DrawText( "Insert", fontText, null, blackBrush, 180, 80, 0, TextAlign.TopLeft );

            ta = new PDFTextAnnotation( "Key", "Key annotation" );
            ta.Icon = TextAnnotationIcon.Key;
            ta.Rectangle = new RectangleF( 260, 60, 100, 100 );
            page.Annotations.Add( ta );
            page.Canvas.DrawText( "Key", fontText, null, blackBrush, 260, 80, 0, TextAlign.TopLeft );

            ta = new PDFTextAnnotation( "New paragraph", "New paragraph annotation" );
            ta.Icon = TextAnnotationIcon.NewParagraph;
            ta.Rectangle = new RectangleF( 340, 60, 100, 100 );
            page.Annotations.Add( ta );
            page.Canvas.DrawText( "New paragraph", fontText, null, blackBrush, 340, 80, 0, TextAlign.TopLeft );

            ta = new PDFTextAnnotation( "Note", "Note annotation" );
            ta.Icon = TextAnnotationIcon.Note;
            ta.Rectangle = new RectangleF( 420, 60, 100, 100 );
            page.Annotations.Add( ta );
            page.Canvas.DrawText( "Note", fontText, null, blackBrush, 420, 80, 0, TextAlign.TopLeft );

            ta = new PDFTextAnnotation( "Paragraph", "Paragraph annotation" );
            ta.Icon = TextAnnotationIcon.Paragraph;
            ta.Rectangle = new RectangleF( 500, 60, 100, 100 );
            page.Annotations.Add( ta );
            page.Canvas.DrawText( "Paragraph", fontText, null, blackBrush, 500, 80, 0, TextAlign.TopLeft );

            // Rubber stamp annotations

            page.Canvas.DrawText( "Rubber stamp annotations", fontSection, null, blackBrush, 20, 120, 0, TextAlign.TopLeft );
            // Create all available rubber stamp annotations
            PDFRubberStampAnnotation rsa = new PDFRubberStampAnnotation( "Approved", "Approved annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Approved;
            rsa.Rectangle = new RectangleF( 20, 140, 100, 30 );
            rsa.Opacity = 50;
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Approved", fontText, null, blackBrush, 20, 180, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "As Is", "As Is annotation" );
            rsa.Icon = RubberStampAnnotationIcon.AsIs;
            rsa.Rectangle = new RectangleF( 120, 140, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "As Is", fontText, null, blackBrush, 120, 180, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "Confidential", "Confidential annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Confidential;
            rsa.Rectangle = new RectangleF( 220, 140, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Confidential", fontText, null, blackBrush, 220, 180, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "Departmental", "Departmental annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Departmental;
            rsa.Rectangle = new RectangleF( 320, 140, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Departmental", fontText, null, blackBrush, 320, 180, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "Draft", "Draft annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Draft;
            rsa.Rectangle = new RectangleF( 420, 140, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Draft", fontText, null, blackBrush, 420, 180, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "Experimental", "Experimental annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Experimental;
            rsa.Rectangle = new RectangleF( 520, 140, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Experimental", fontText, null, blackBrush, 520, 180, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "Expired", "Expired annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Expired;
            rsa.Rectangle = new RectangleF( 20, 200, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Expired", fontText, null, blackBrush, 20, 240, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "Final", "Final annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Final;
            rsa.Rectangle = new RectangleF( 120, 200, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Final", fontText, null, blackBrush, 120, 240, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "ForComment", "ForComment annotation" );
            rsa.Icon = RubberStampAnnotationIcon.ForComment;
            rsa.Rectangle = new RectangleF( 220, 200, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "ForComment", fontText, null, blackBrush, 220, 240, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "ForPublicRelease", "ForPublicRelease annotation" );
            rsa.Icon = RubberStampAnnotationIcon.ForPublicRelease;
            rsa.Rectangle = new RectangleF( 320, 200, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "ForPublicRelease", fontText, null, blackBrush, 320, 240, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "NotApproved", "NotApproved annotation" );
            rsa.Icon = RubberStampAnnotationIcon.NotApproved;
            rsa.Rectangle = new RectangleF( 420, 200, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "NotApproved", fontText, null, blackBrush, 420, 240, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "NotForPublicRelease", "NotForPublicRelease annotation" );
            rsa.Icon = RubberStampAnnotationIcon.NotForPublicRelease;
            rsa.Rectangle = new RectangleF( 520, 200, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "NotForPublicRelease", fontText, null, blackBrush, 520, 240, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "Sold", "Sold annotation" );
            rsa.Icon = RubberStampAnnotationIcon.Sold;
            rsa.Rectangle = new RectangleF( 20, 260, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "Sold", fontText, null, blackBrush, 20, 300, 0, TextAlign.TopLeft );

            rsa = new PDFRubberStampAnnotation( "TopSecret", "TopSecret annotation" );
            rsa.Icon = RubberStampAnnotationIcon.TopSecret;
            rsa.Rectangle = new RectangleF( 120, 260, 100, 30 );
            page.Annotations.Add( rsa );
            page.Canvas.DrawText( "TopSecret", fontText, null, blackBrush, 120, 300, 0, TextAlign.TopLeft );

            // Line annotations

            page.Canvas.DrawText( "Line annotations", fontSection, null, blackBrush, 20, 350, 0, TextAlign.TopLeft );
            PDFLineAnnotation la = new PDFLineAnnotation( "Line", "Line annotation" );
            la.BeginLineStyle = LineEndingStyle.Circle;
            la.EndLineStyle = LineEndingStyle.OpenArrow;
            la.Rectangle = new RectangleF( 20, 370, 150, 30 );
            la.Border = new PDFAnnotationBorder( 1, BorderStyle.Solid );
            la.BorderColor = new PDFColor( Color.Red );
            la.InteriorColor = new PDFColor( Color.CornflowerBlue );
            page.Annotations.Add( la );
            page.Canvas.DrawText( "Line annotation with a circle and open arrow", fontText, null, blackBrush,
                20, 420, 0, TextAlign.TopLeft );

            // File attachment annotations

            page.Canvas.DrawText( "File attachment annotations", fontSection, null, blackBrush, 20, 450, 0, TextAlign.TopLeft );
            // Create all available file attachment annotations
            PDFFileAttachmentAnnotation faa = new PDFFileAttachmentAnnotation( "Graph", "Graph icon" );
            faa.Icon =FileAttachmentAnnotationIcon.Graph;
            faa.Rectangle = new RectangleF( 20, 470, 100, 30 );
            faa.Compress = true;
            faa.File = "sample.pdf";
            page.Annotations.Add( faa );
            page.Canvas.DrawText( "Graph", fontText, null, blackBrush, 20, 500, 0, TextAlign.TopLeft );

            faa = new PDFFileAttachmentAnnotation( "Paperclip", "Paperclip icon" );
            faa.Icon =FileAttachmentAnnotationIcon.Paperclip;
            faa.Rectangle = new RectangleF( 100, 470, 100, 30 );
            faa.Compress = true;
            faa.File = "sample.pdf";
            page.Annotations.Add( faa );
            page.Canvas.DrawText( "Paperclip", fontText, null, blackBrush, 100, 500, 0, TextAlign.TopLeft );

            faa = new PDFFileAttachmentAnnotation( "PushPin", "PushPin icon" );
            faa.Icon =FileAttachmentAnnotationIcon.PushPin;
            faa.Rectangle = new RectangleF( 180, 470, 100, 30 );
            faa.Compress = true;
            faa.File = "sample.pdf";
            page.Annotations.Add( faa );
            page.Canvas.DrawText( "PushPin", fontText, null, blackBrush, 180, 500, 0, TextAlign.TopLeft );

            faa = new PDFFileAttachmentAnnotation( "Tag", "Tag icon" );
            faa.Icon =FileAttachmentAnnotationIcon.Tag;
            faa.Rectangle = new RectangleF( 260, 470, 100, 30 );
            faa.Compress = true;
            faa.File = "sample.pdf";
            page.Annotations.Add( faa );
            page.Canvas.DrawText( "Graph", fontText, null, blackBrush, 260, 500, 0, TextAlign.TopLeft );

            // Popup annotation
            page.Canvas.DrawText( "Annotation with popup window controlled from code",
                fontSection, null, blackBrush, 20, 540, 0, TextAlign.BottomLeft );
            PDFTextAnnotation tap = new PDFTextAnnotation( "Comment with popup", "Comment annotation with user defined popup" );
            tap.Icon = TextAnnotationIcon.Comment;
            tap.Rectangle = new RectangleF( 20, 550, 100, 100 );
            tap.PopupRectangle = new RectangleF( page.Width - 200, page.Height - 200, 200, 200 );
            tap.BorderColor = new PDFColor( 0, 192, 0 );
            page.Annotations.Add( tap );
            page.Canvas.DrawText( "Popup comment. The popup window is displayed in the bottom right corner of the page",
                fontText, null, blackBrush, 20, 580, 0, TextAlign.TopLeft );

            // Highlight annotation
            page.Canvas.DrawText( "Markup annotation - this text will be highlighted",
                fontSection, null, blackBrush, 20, 610 );
            PDFMarkupAnnotation mka =
                new PDFMarkupAnnotation( "Markup annotation", "Markup annotation with highlight style" );
            mka.MarkupStyle = MarkupStyle.Highlight;
            mka.Rectangle = new RectangleF( 200, 610, 100, 10 );
            mka.QuadPoints = new float[]{ 115, 608, 250, 608, 115, 622, 250, 622 };
            mka.BorderColor = new PDFColor( 255, 255, 0 );
            page.Annotations.Add( mka );

            // Save the document to disk
            doc.SaveToFile( "annotations.pdf" );
        }
    }
}


Annotations.vb

'
' File name: Annotations.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Annotations
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows all annotations that can be created with PDF4NET.
'/ </summary>

Class Annotations

   '/ <summary>
   '/ The main entry point for the application.
   '/ </summary>
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument

        ' Create one page
        Dim page As PDFPage = doc.AddPage()

        Dim blackBrush As New PDFBrush(New PDFColor(0, 0, 0))
        Dim fontSection As New PDFFont(FontFace.Helvetica, 10)
        fontSection.Bold = True
        Dim fontText As New PDFFont(FontFace.Helvetica, 8)

        page.Canvas.DrawText("Text annotations", fontSection, Nothing, blackBrush, 20, 45, 0, TextAlign.BottomLeft)
        ' Create all available text annotations
        Dim ta As New PDFTextAnnotation("Comment", "Comment annotation")
        ta.Icon = TextAnnotationIcon.Comment
        ta.Rectangle = New RectangleF(20, 60, 100, 100)
        page.Annotations.Add(ta)
        page.Canvas.DrawText("Comment", fontText, Nothing, blackBrush, 20, 80, 0, TextAlign.TopLeft)

        ta = New PDFTextAnnotation("Help", "Help annotation")
        ta.Icon = TextAnnotationIcon.Help
        ta.Rectangle = New RectangleF(100, 60, 100, 100)
        page.Annotations.Add(ta)
        page.Canvas.DrawText("Help", fontText, Nothing, blackBrush, 100, 80, 0, TextAlign.TopLeft)

        ta = New PDFTextAnnotation("Insert", "Insert annotation")
        ta.Icon = TextAnnotationIcon.Insert
        ta.Rectangle = New RectangleF(180, 60, 100, 100)
        page.Annotations.Add(ta)
        page.Canvas.DrawText("Insert", fontText, Nothing, blackBrush, 180, 80, 0, TextAlign.TopLeft)

        ta = New PDFTextAnnotation("Key", "Key annotation")
        ta.Icon = TextAnnotationIcon.Key
        ta.Rectangle = New RectangleF(260, 60, 100, 100)
        page.Annotations.Add(ta)
        page.Canvas.DrawText("Key", fontText, Nothing, blackBrush, 260, 80, 0, TextAlign.TopLeft)

        ta = New PDFTextAnnotation("New paragraph", "New paragraph annotation")
        ta.Icon = TextAnnotationIcon.NewParagraph
        ta.Rectangle = New RectangleF(340, 60, 100, 100)
        page.Annotations.Add(ta)
        page.Canvas.DrawText("New paragraph", fontText, Nothing, blackBrush, 340, 80, 0, TextAlign.TopLeft)

        ta = New PDFTextAnnotation("Note", "Note annotation")
        ta.Icon = TextAnnotationIcon.Note
        ta.Rectangle = New RectangleF(420, 60, 100, 100)
        page.Annotations.Add(ta)
        page.Canvas.DrawText("Note", fontText, Nothing, blackBrush, 420, 80, 0, TextAlign.TopLeft)

        ta = New PDFTextAnnotation("Paragraph", "Paragraph annotation")
        ta.Icon = TextAnnotationIcon.Paragraph
        ta.Rectangle = New RectangleF(500, 60, 100, 100)
        page.Annotations.Add(ta)
        page.Canvas.DrawText("Paragraph", fontText, Nothing, blackBrush, 500, 80, 0, TextAlign.TopLeft)

        ' Rubber stamp annotations
        page.Canvas.DrawText("Rubber stamp annotations", fontSection, Nothing, blackBrush, 20, 120, 0, TextAlign.TopLeft)
        ' Create all available rubber stamp annotations
        Dim rsa As New PDFRubberStampAnnotation("Approved", "Approved annotation")
        rsa.Icon = RubberStampAnnotationIcon.Approved
        rsa.Rectangle = New RectangleF(20, 140, 100, 30)
        rsa.Opacity = 50
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Approved", fontText, Nothing, blackBrush, 20, 180, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("As Is", "As Is annotation")
        rsa.Icon = RubberStampAnnotationIcon.Asis
        rsa.Rectangle = New RectangleF(120, 140, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("As Is", fontText, Nothing, blackBrush, 120, 180, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("Confidential", "Confidential annotation")
        rsa.Icon = RubberStampAnnotationIcon.Confidential
        rsa.Rectangle = New RectangleF(220, 140, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Confidential", fontText, Nothing, blackBrush, 220, 180, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("Departmental", "Departmental annotation")
        rsa.Icon = RubberStampAnnotationIcon.Departmental
        rsa.Rectangle = New RectangleF(320, 140, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Departmental", fontText, Nothing, blackBrush, 320, 180, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("Draft", "Draft annotation")
        rsa.Icon = RubberStampAnnotationIcon.Draft
        rsa.Rectangle = New RectangleF(420, 140, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Draft", fontText, Nothing, blackBrush, 420, 180, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("Experimental", "Experimental annotation")
        rsa.Icon = RubberStampAnnotationIcon.Experimental
        rsa.Rectangle = New RectangleF(520, 140, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Experimental", fontText, Nothing, blackBrush, 520, 180, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("Expired", "Expired annotation")
        rsa.Icon = RubberStampAnnotationIcon.Expired
        rsa.Rectangle = New RectangleF(20, 200, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Expired", fontText, Nothing, blackBrush, 20, 240, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("Final", "Final annotation")
        rsa.Icon = RubberStampAnnotationIcon.Final
        rsa.Rectangle = New RectangleF(120, 200, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Final", fontText, Nothing, blackBrush, 120, 240, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("ForComment", "ForComment annotation")
        rsa.Icon = RubberStampAnnotationIcon.ForComment
        rsa.Rectangle = New RectangleF(220, 200, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("ForComment", fontText, Nothing, blackBrush, 220, 240, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("ForPublicRelease", "ForPublicRelease annotation")
        rsa.Icon = RubberStampAnnotationIcon.ForPublicRelease
        rsa.Rectangle = New RectangleF(320, 200, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("ForPublicRelease", fontText, Nothing, blackBrush, 320, 240, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("NotApproved", "NotApproved annotation")
        rsa.Icon = RubberStampAnnotationIcon.NotApproved
        rsa.Rectangle = New RectangleF(420, 200, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("NotApproved", fontText, Nothing, blackBrush, 420, 240, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("NotForPublicRelease", "NotForPublicRelease annotation")
        rsa.Icon = RubberStampAnnotationIcon.NotForPublicRelease
        rsa.Rectangle = New RectangleF(520, 200, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("NotForPublicRelease", fontText, Nothing, blackBrush, 520, 240, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("Sold", "Sold annotation")
        rsa.Icon = RubberStampAnnotationIcon.Sold
        rsa.Rectangle = New RectangleF(20, 260, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("Sold", fontText, Nothing, blackBrush, 20, 300, 0, TextAlign.TopLeft)

        rsa = New PDFRubberStampAnnotation("TopSecret", "TopSecret annotation")
        rsa.Icon = RubberStampAnnotationIcon.TopSecret
        rsa.Rectangle = New RectangleF(120, 260, 100, 30)
        page.Annotations.Add(rsa)
        page.Canvas.DrawText("TopSecret", fontText, Nothing, blackBrush, 120, 300, 0, TextAlign.TopLeft)

        ' Line annotations
        page.Canvas.DrawText("Line annotations", fontSection, Nothing, blackBrush, 20, 350, 0, TextAlign.TopLeft)
        Dim la As New PDFLineAnnotation("Line", "Line annotation")
        la.BeginLineStyle = LineEndingStyle.Circle
        la.EndLineStyle = LineEndingStyle.OpenArrow
        la.Rectangle = New RectangleF(20, 370, 150, 30)
        la.Border = New PDFAnnotationBorder(1, BorderStyle.Solid)
        la.BorderColor = New PDFColor(Color.Red)
        la.InteriorColor = New PDFColor(Color.CornflowerBlue)
        page.Annotations.Add(la)
        page.Canvas.DrawText("Line annotation with a circle and open arrow", fontText, Nothing, blackBrush, 20, 420, 0, TextAlign.TopLeft)

        ' File attachment annotations
        page.Canvas.DrawText("File attachment annotations", fontSection, Nothing, blackBrush, 20, 450, 0, TextAlign.TopLeft)
        ' Create all available file attachment annotations
        Dim faa As New PDFFileAttachmentAnnotation("Graph", "Graph icon")
        faa.Icon = FileAttachmentAnnotationIcon.Graph
        faa.Rectangle = New RectangleF(20, 470, 100, 30)
        faa.Compress = True
        faa.File = "sample.pdf"
        page.Annotations.Add(faa)
        page.Canvas.DrawText("Graph", fontText, Nothing, blackBrush, 20, 500, 0, TextAlign.TopLeft)

        faa = New PDFFileAttachmentAnnotation("Paperclip", "Paperclip icon")
        faa.Icon = FileAttachmentAnnotationIcon.Paperclip
        faa.Rectangle = New RectangleF(100, 470, 100, 30)
        faa.Compress = True
        faa.File = "sample.pdf"
        page.Annotations.Add(faa)
        page.Canvas.DrawText("Paperclip", fontText, Nothing, blackBrush, 100, 500, 0, TextAlign.TopLeft)

        faa = New PDFFileAttachmentAnnotation("PushPin", "PushPin icon")
        faa.Icon = FileAttachmentAnnotationIcon.PushPin
        faa.Rectangle = New RectangleF(180, 470, 100, 30)
        faa.Compress = True
        faa.File = "sample.pdf"
        page.Annotations.Add(faa)
        page.Canvas.DrawText("PushPin", fontText, Nothing, blackBrush, 180, 500, 0, TextAlign.TopLeft)

        faa = New PDFFileAttachmentAnnotation("Tag", "Tag icon")
        faa.Icon = FileAttachmentAnnotationIcon.Tag
        faa.Rectangle = New RectangleF(260, 470, 100, 30)
        faa.Compress = True
        faa.File = "sample.pdf"
        page.Annotations.Add(faa)
        page.Canvas.DrawText("Graph", fontText, Nothing, blackBrush, 260, 500, 0, TextAlign.TopLeft)

        ' Popup annotation
        page.Canvas.DrawText("Annotation with popup window controlled from code", fontSection, Nothing, blackBrush, 20, 540, 0, TextAlign.BottomLeft)
        Dim tap As New PDFTextAnnotation("Comment with popup", "Comment annotation with user defined popup")
        tap.Icon = TextAnnotationIcon.Comment
        tap.Rectangle = New RectangleF(20, 550, 100, 100)
        tap.PopupRectangle = New RectangleF(page.Width - 200, page.Height - 200, 200, 200)
        tap.BorderColor = New PDFColor(0, 192, 0)
        page.Annotations.Add(tap)
        page.Canvas.DrawText("Popup comment. The popup window is displayed in the bottom right corner of the page", fontText, Nothing, blackBrush, 20, 580, 0, TextAlign.TopLeft)

        ' Highlight annotation
        page.Canvas.DrawText("Markup annotation - this text will be highlighted", fontSection, Nothing, blackBrush, 20, 610)
        Dim mka As New PDFMarkupAnnotation("Markup annotation", "Markup annotation with highlight style")
        mka.MarkupStyle = MarkupStyle.Highlight
        mka.Rectangle = New RectangleF(200, 610, 100, 10)
        mka.QuadPoints = New Single() {115, 608, 250, 608, 115, 622, 250, 622}
        mka.BorderColor = New PDFColor(255, 255, 0)
        page.Annotations.Add(mka)

        ' Save the document to disk
        doc.SaveToFile("annotations.pdf")
    End Sub 'Main
End Class 'Annotations


Samples: ArcsPies

Samples

ArcsPies

This samples demonstrates the arcs and pies drawing capabilities of the PDF4NET library. It creates a 2 pages document. On the first page, it draws 50 arcs positioned at random locations, with random angles. On the second page, it draws 50 pies positioned at random locations, with random angles. The colors of the arcs and pies are generated randomly.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


ArcsPies.cs

/// <fileName>
/// File name: ArcsPies.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.ArcsPies
{
    /// <summary>
    /// This sample will show how to draw arcs and pies
    /// on the page.
    /// </summary>
    class ArcsPies
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( Color.Black ) );
            PDFBrush greenBrush = new PDFBrush( new PDFColor( Color.Green ) );
            PDFPen pen = new PDFPen( new PDFColor( Color.Orange ), 1 );

            Random rnd = new Random( );

            // Create first page
            PDFPage pdfPage1 = pdfDoc.AddPage( );

            // Draw 50 arcs
            for( int i = 0; i < 50; i++ )
            {
                // Create random colors for the border and the interior
                Color penColor = Color.FromArgb( rnd.Next( 256 ), rnd.Next( 256 ), rnd.Next( 256 ) );

                // Create the pen to draw the border
                PDFPen randomPen = new PDFPen( new PDFColor( penColor ), 1 );

                // Generate random positions
                float left = rnd.Next( ( int )pdfPage1.Width );
                float top = rnd.Next( ( int )pdfPage1.Height );

                // Generate random sizes
                float width = rnd.Next( ( int )( pdfPage1.Width - left ) ); // try to keep the arc within the page
                float startAngle = rnd.Next( 360 );
                float sweepAngle = rnd.Next( 360 );

                // Draw the ellipse
                pdfPage1.Canvas.DrawArc( randomPen, top, left, width, startAngle, sweepAngle );
            }

            // Draw a label
            pdfPage1.Canvas.DrawText( "Random arcs",
                fontText, null, blackBrush, 20, 20 );

            // Create the second page
            PDFPage pdfPage2 = pdfDoc.AddPage( );

            // Draw 50 pies
            for( int i = 0; i < 50; i++ )
            {
                // Create random colors for the border and the interior
                Color brushColor = Color.FromArgb( rnd.Next( 256 ), rnd.Next( 256 ), rnd.Next( 256 ) );
                Color penColor = Color.FromArgb( rnd.Next( 256 ), rnd.Next( 256 ), rnd.Next( 256 ) );

                // Create the brush to fill the interior
                PDFBrush randomBrush = new PDFBrush( new PDFColor( brushColor ) );
                // Create the pen to draw the border
                PDFPen randomPen = new PDFPen( new PDFColor( penColor ), 1 );

                // Generate random positions
                float left = rnd.Next( ( int )pdfPage2.Width );
                float top = rnd.Next( ( int )pdfPage2.Height );

                // Generate random sizes
                float width = rnd.Next( ( int )( pdfPage2.Width - left ) ); // try to keep the pie within the page
                float startAngle = rnd.Next( 360 );
                float sweepAngle = rnd.Next( 360 );

                // Draw the ellipse
                pdfPage2.Canvas.DrawPie( randomPen, randomBrush,
                    top, left, width, startAngle, sweepAngle );
            }

            // Draw a label
            pdfPage2.Canvas.DrawText( "Random pies",
                fontText, null, blackBrush, 20, 20 );

            // Save the document to disk
            pdfDoc.SaveToFile( "arcspies.pdf" );
        }
    }
}


ArcsPies.vb

'
' File name: ArcsPies.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.ArcsPies
    '/ <summary>
    '/ This sample will show how to draw arcs and pies
    '/ on the page.
    '/ </summary>
    Class ArcsPies

        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim greenBrush As New PDFBrush(New PDFColor(0, 255, 0))
            Dim pen As New PDFPen(New PDFColor(Color.Orange), 1)

            Dim rnd As New Random()

            ' Create first page
            Dim pdfPage1 As PDFPage = pdfDoc.AddPage()

            ' Draw 50 arcs
            Dim i As Integer
            For i = 0 To 49
                ' Create random colors for the border and the interior
                Dim penColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))

                ' Create the pen to draw the border
                Dim randomPen As New PDFPen(penColor, 1)

                ' Generate random positions
                Dim left As Single = rnd.Next(CInt(pdfPage1.Width))
                Dim top As Single = rnd.Next(CInt(pdfPage1.Height))

                ' Generate random sizes
                Dim width As Single = rnd.Next(CInt(pdfPage1.Width - left)) ' try to keep the arc within the page
                Dim startAngle As Single = rnd.Next(360)
                Dim sweepAngle As Single = rnd.Next(360)

                ' Draw the ellipse
                pdfPage1.Canvas.DrawArc(randomPen, top, left, width, startAngle, sweepAngle)
            Next i

            ' Draw a label
            pdfPage1.Canvas.DrawText("Random arcs", fontText, Nothing, blackBrush, 20, 20)

            ' Create the second page
            Dim pdfPage2 As PDFPage = pdfDoc.AddPage()

            ' Draw 50 pies
            'Dim i As Integer
            For i = 0 To 49
                ' Create random colors for the border and the interior
                Dim brushColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))
                Dim penColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))

                ' Create the brush to fill the interior
                Dim randomBrush As New PDFBrush(brushColor)
                ' Create the pen to draw the border
                Dim randomPen As New PDFPen(penColor, 1)

                ' Generate random positions
                Dim left As Single = rnd.Next(CInt(pdfPage2.Width))
                Dim top As Single = rnd.Next(CInt(pdfPage2.Height))

                ' Generate random sizes
                Dim width As Single = rnd.Next(CInt(pdfPage2.Width - left)) ' try to keep the pie within the page
                Dim startAngle As Single = rnd.Next(360)
                Dim sweepAngle As Single = rnd.Next(360)

                ' Draw the ellipse
                pdfPage2.Canvas.DrawPie(randomPen, randomBrush, top, left, width, startAngle, sweepAngle)
            Next i

            ' Draw a label
            pdfPage2.Canvas.DrawText("Random pies", fontText, Nothing, blackBrush, 20, 20)

            ' Save the document to disk
            pdfDoc.SaveToFile("arcspies.pdf")
        End Sub 'Main
    End Class 'ArcsPies
End Namespace 'O2S.Samples.PDF4NET.ArcsPies


Samples: Attachments

Samples

Attachments

This sample shows how to work with document attachments using PDF4NET library.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Attachments.cs

/// <fileName>
/// File name: Attachments.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to work with document attachments using PDF4NET library.
    /// </summary>
    class Attachments
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create a document with 2 file attachments.
            CreateAttachments( );

            // Display attachments in a PDF file.
            DisplayAttachments( );
        }

        /// <summary>
        /// Creates a PDF file that contains 2 file attachments.
        /// </summary>
        private static void CreateAttachments( )
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Create a blank page
            PDFPage page = doc.AddPage( );
            // Print instructions about how to view the attachments in the PDF file.
            PDFBrush brush = new PDFBrush( new PDFColor( 0, 0, 0 ) );
            PDFFont font = new PDFFont( );
            page.Canvas.DrawText( "This document contains 2 file attachments.",
                font, null, brush, 50, 50 );
            page.Canvas.DrawText( "In the Acrobat/Reader menu click on View > " +
                "Navigation tabs > Attachments to view them.", font, null, brush, 50, 60 );

            // Create an attachment for 'xfasampleform.pdf' file
            PDFDocumentAttachment attachment = new PDFDocumentAttachment( );
            attachment.FileName = "xfasampleform.pdf";
            attachment.MimeType = "application/pdf";
            attachment.Description = "XFA sample form";
            // Add the attachment to document.
            doc.Attachments.Add( attachment );

            // Create an attachment for 'auto1.pdf' file
            attachment = new PDFDocumentAttachment( );
            attachment.FileName = "auto1.jpg";
            attachment.MimeType = "image/jpg";
            attachment.Description = "Lexus - Minority Report";
            // Add the attachment to document.
            doc.Attachments.Add( attachment );

            // Save the document to disk
            doc.SaveToFile( "attachments.pdf" );
        }

        private static void DisplayAttachments( )
        {
            // Load the PDF file that contains the attachments
            // (use the document created by previous function)
            PDFDocument doc = new PDFDocument( "attachments.pdf" );
            // Display the attachments in the document
            for( int i = 0; i < doc.Attachments.Count; i++ )
            {
                Console.WriteLine( "Attachment: {0}; Description: {1}; Creation Date: {2}",
                    doc.Attachments[i].FileName, doc.Attachments[i].Description,
                    doc.Attachments[i].CreationDate );
                // doc.Attachments[i].FileData contains the attachment content.
                // It can be saved to disk if needed.
            }
        }
    }
}


Attachments.vb

'
' File name: Attachments.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Namespace O2S.Samples.PDF4NET

    ''' <summary>
    ''' This sample shows how to work with document attachments using PDF4NET library.
    ''' </summary>
    Class Attachments
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            ' Create a document with 2 file attachments.
            CreateAttachments()
            ' Display attachments in a PDF file.
            DisplayAttachments()
        End Sub
        ''' <summary>
        ''' Creates a PDF file that contains 2 file attachments.
        ''' </summary>
        Private Shared Sub CreateAttachments()
            ' Create the pdf document
            Dim doc As PDFDocument = New PDFDocument
            ' Create a blank page
            Dim page As PDFPage = doc.AddPage()
            ' Print instructions about how to view the attachments in the PDF file.
            Dim brush As PDFBrush = New PDFBrush(New PDFColor(0, 0, 0))
            Dim font As PDFFont = New PDFFont
            page.Canvas.DrawText("This document contains 2 file attachments.", _
                font, Nothing, brush, 50, 50)
            page.Canvas.DrawText("In the Acrobat/Reader menu click on View > " + _
                "Navigation tabs > Attachments to view them.", font, Nothing, brush, 50, 60)
            ' Create an attachment for 'xfasampleform.pdf' file
            Dim attachment As PDFDocumentAttachment = New PDFDocumentAttachment
            attachment.FileName = "xfasampleform.pdf"
            attachment.MimeType = "application/pdf"
            attachment.Description = "XFA sample form"
            ' Add the attachment to document.
            doc.Attachments.Add(attachment)
            ' Create an attachment for 'auto1.pdf' file
            attachment = New PDFDocumentAttachment
            attachment.FileName = "auto1.jpg"
            attachment.MimeType = "image/jpg"
            attachment.Description = "Lexus - Minority Report"
            ' Add the attachment to document.
            doc.Attachments.Add(attachment)
            ' Save the document to disk
            doc.SaveToFile("attachments.pdf")
        End Sub
        Private Shared Sub DisplayAttachments()
            ' Load the PDF file that contains the attachments
            ' (use the document created by previous function)
            Dim doc As PDFDocument = New PDFDocument("attachments.pdf")
            For i As Integer = 0 To doc.Attachments.Count - 1
                ' Display the attachments in the document
                Console.WriteLine("Attachment: {0}; Description: {1}; Creation Date: {2}", _
                    doc.Attachments(i).FileName, doc.Attachments(i).Description, _
                    doc.Attachments(i).CreationDate)
                ' doc.Attachments[i].FileData contains the attachment content.
                ' It can be saved to disk if needed.
            Next
        End Sub
    End Class
End Namespace


Samples: Autonumbering

Samples

Autonumbering

This samples demonstrates the autonumbering capabilities of the PDF4NET library. It creates a 100 pages document. Then, it creates 10 numbering ranges, one range for each 10 pages. Each numbering range is considered to be a chapter, the first range is considered to be the introduction. The first numbering range uses roman numbering system, while the others use arabic numbering system. The numbering of the chapters use the chapter number as the prefix for page number.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


AutoNumbering.cs

/// <fileName>
/// File name: AutoNumbering.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.AutoNumbering
{
    /// <summary>
    /// This sample will show how to use the automatic page numbering feature
    /// available with the PDF4NET library.
    /// The document will have 100 pages, first 10 pages will be the introduction
    /// and they will use roman numerals, then each 10 pages will be grouped as
    /// a chapter. The numbering will be chapter based, meaning the pages will be
    /// numbered within the chapter. Ex: chapte 1: 1-1, 1-2, 1-3, etc, chapter 2:
    /// 2-1, 2-2, 2-3, etc.
    /// </summary>
    class AutoNumbering
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 96 );
            PDFFont fontNumber = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            int i;
            // Create 10 numbering ranges, each range will correspond to a chapter
            // The first range is for the introduction.
            for( i = 0; i < 10; i++ )
            {
                PageNumberingRange pnr = new PageNumberingRange( );
                if( i == 0 )
                { // pages in the introduction use roman numerals
                    pnr.NumberingStyle = NumberingStyle.LowerCaseRoman;
                }
                else
                { // pages in the rest of the chapters use arabic numerals
                    pnr.NumberingStyle = NumberingStyle.Arabic;
                }
                // Each numbering range covers 10 pages
                pnr.StartPageIndex = i * 10;

                // Within each chapter, the page numbers will start from 1
                pnr.StartPageNumber = 1;

                // Set the page number prefix for each numbering range
                // to be the number of the chapter. For the introduction
                // we do not set a page number.
                if( i > 0 )
                {
                    pnr.PageNumberPrefix = i.ToString( ) + " - ";
                }

                // Add the numbering range to document
                pdfDoc.AddNumberingRange( pnr );
            }

            // Create the visual aspect of the page number
            PageNumber pn = new PageNumber( );
            pn.Font = fontNumber;
            pn.Brush = blackBrush;
            // Print the page number centered at the bottom of the page
            pn.Align = TextAlign.BottomCenter;
            // The page number will be printed 10 points above the bottom margin.
            pn.VerticalOffset = 10;

            // Set the page number visual aspect for all the pages in the document
            // by attaching it to the document.
            pdfDoc.PageNumber = pn;

            // Create the pages of the document, 100 pages
            for( i = 0; i < 100; i++ )
            {
                // Create the page
                PDFPage pdfPage = pdfDoc.AddPage( );
                // Draw a label on it
                if( i / 10 == 0 )
                {
                    pdfPage.Canvas.DrawText( "Introduction",
                        fontText, null, blackBrush, pdfPage.Width/2, pdfPage.Height/2,
                        0, TextAlign.MiddleCenter );
                }
                else
                {
                    pdfPage.Canvas.DrawText( "Chapter " + ( i / 10 ).ToString( ),
                        fontText, null, blackBrush, pdfPage.Width/2, pdfPage.Height/2,
                        0, TextAlign.MiddleCenter );
                }
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "autonumbering.pdf" );
        }
    }
}


AutoNumbering.vb

'
' File name: AutoNumbering.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.AutoNumbering
    '/ <summary>
    '/ This sample will show how to use the automatic page numbering feature
    '/ available with the PDF4NET library.
    '/ The document will have 100 pages, first 10 pages will be the introduction
    '/ and they will use roman numerals, then each 10 pages will be grouped as
    '/ a chapter. The numbering will be chapter based, meaning the pages will be
    '/ numbered within the chapter. Ex: chapte 1: 1-1, 1-2, 1-3, etc, chapter 2:
    '/ 2-1, 2-2, 2-3, etc.
    '/ </summary>
    Class AutoNumbering

        Shared Sub Main()
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 96)
            Dim fontNumber As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            Dim i As Integer
            ' Create 10 numbering ranges, each range will correspond to a chapter
            ' The first range is for the introduction.
            For i = 0 To 9
                Dim pnr As New PageNumberingRange()
                If i = 0 Then
                    ' pages in the introduction use roman numerals
                    pnr.NumberingStyle = NumberingStyle.LowerCaseRoman
                Else ' pages in the rest of the chapters use arabic numerals
                    pnr.NumberingStyle = NumberingStyle.Arabic
                End If
                ' Each numbering range covers 10 pages
                pnr.StartPageIndex = i * 10

                ' Within each chapter, the page numbers will start from 1
                pnr.StartPageNumber = 1

                ' Set the page number prefix for each numbering range
                ' to be the number of the chapter. For the introduction
                ' we do not set a page number.
                If i > 0 Then
                    pnr.PageNumberPrefix = i.ToString() + " - "
                End If

                ' Add the numbering range to document
                pdfDoc.AddNumberingRange(pnr)
            Next i

            ' Create the visual aspect of the page number
            Dim pn As New PageNumber()
            pn.Font = fontNumber
            pn.Brush = blackBrush
            ' Print the page number centered at the bottom of the page
            pn.Align = TextAlign.BottomCenter
            ' The page number will be printed 10 points above the bottom margin.
            pn.VerticalOffset = 10

            ' Set the page number visual aspect for all the pages in the document
            ' by attaching it to the document.
            pdfDoc.PageNumber = pn

            ' Create the pages of the document, 100 pages
            For i = 0 To 99
                ' Create the page
                Dim pdfPage As PDFPage = pdfDoc.AddPage()
                ' Draw a label on it
                If i / 10 = 0 Then
                    pdfPage.Canvas.DrawText("Introduction", fontText, Nothing, blackBrush, pdfPage.Width / 2, pdfPage.Height / 2, 0, TextAlign.MiddleCenter)
                Else
                    pdfPage.Canvas.DrawText("Chapter " + (i / 10).ToString(), fontText, Nothing, blackBrush, pdfPage.Width / 2, pdfPage.Height / 2, 0, TextAlign.MiddleCenter)
                End If
            Next i

            ' Save the document to disk
            pdfDoc.SaveToFile("autonumbering.pdf")
        End Sub 'Main
    End Class 'AutoNumbering
End Namespace 'O2S.Samples.PDF4NET.AutoNumbering


Samples: Barcodes

Samples

Barcodes

This sample demonstrates the native support for barcodes implemented in PDF4NET library. Both 1D and 2D barcodes are shown in this sample.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Barcodes.cs

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Barcodes;
using O2S.Components.PDF4NET.Graphics.Fonts;

namespace O2S.Samples.PDF4NET.Barcodes
{
    /// <summary>
    /// This sample shows how to display barcodes in a PDF document.
    /// </summary>
    class Barcodes
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Create the PDF document
            PDFDocument doc = new PDFDocument( );

            // Create the helper graphic objects.
            PDFFont titleFont = new PDFFont( FontFace.Helvetica, 10 );
            titleFont.Bold = true;
            PDFFont textFont = new PDFFont( FontFace.Helvetica, 8 );
            PDFBrush brush = new PDFBrush( new PDFColor( Color.Black ) );

            // First page for linear barcodes.
            PDFPage page = doc.AddPage();
            page.Canvas.DrawText("1D/Linear barcodes", titleFont, null, brush, 20, 50);

            page.Canvas.DrawText( "1. Codabar", textFont, null, brush, 20, 70 );
            PDFCodabarBarcode cb = new PDFCodabarBarcode( "0123456789" );
            page.Canvas.DrawBarcode( cb, 20, 80 );

            page.Canvas.DrawText( "2. Code 11", textFont, null, brush, 20, 140 );
            PDFCode11Barcode c11 = new PDFCode11Barcode( "0123456789" );
            page.Canvas.DrawBarcode( c11, 20, 150 );

            page.Canvas.DrawText( "3. Code 128A", textFont, null, brush, 20, 210 );
            PDFCode128ABarcode c128a = new PDFCode128ABarcode( "CODE128A" );
            page.Canvas.DrawBarcode( c128a, 20, 220 );

            page.Canvas.DrawText( "4. Code 128B", textFont, null, brush, 20, 280 );
            PDFCode128BBarcode c128b = new PDFCode128BBarcode( "CODE128B" );
            page.Canvas.DrawBarcode( c128b, 20, 290 );

            page.Canvas.DrawText( "5. Code 128C", textFont, null, brush, 20, 350 );
            PDFCode128CBarcode c128c = new PDFCode128CBarcode( "0123456789" );
            page.Canvas.DrawBarcode( c128c, 20, 360 );

            page.Canvas.DrawText( "6. Code 25", textFont, null, brush, 20, 420 );
            PDFCode25Barcode c25 = new PDFCode25Barcode( "0123456789" );
            page.Canvas.DrawBarcode( c25, 20, 430 );

            page.Canvas.DrawText( "7. Code 25 Interleaved", textFont, null, brush, 20, 490 );
            PDFCode25InterleavedBarcode c25i = new PDFCode25InterleavedBarcode( "0123456789" );
            page.Canvas.DrawBarcode( c25i, 20, 500 );

            page.Canvas.DrawText( "8. Code 39", textFont, null, brush, 20, 560 );
            PDFCode39Barcode c39 = new PDFCode39Barcode( "CODE39" );
            page.Canvas.DrawBarcode( c39, 20, 570 );

            page.Canvas.DrawText( "9. Code 39 Extended", textFont, null, brush, 20, 630 );
            PDFCode39ExtendedBarcode c39x = new PDFCode39ExtendedBarcode( "C39Ext" );
            page.Canvas.DrawBarcode( c39x, 20, 640 );

            page.Canvas.DrawText( "10. Code 93", textFont, null, brush, 20, 700 );
            PDFCode93Barcode c93 = new PDFCode93Barcode( "CODE93" );
            page.Canvas.DrawBarcode( c93, 20, 710 );

            page.Canvas.DrawText( "11. Code 93 Extended", textFont, null, brush, 200, 70 );
            PDFCode93ExtendedBarcode c93x = new PDFCode93ExtendedBarcode( "C93Ext" );
            page.Canvas.DrawBarcode( c93x, 200, 80 );

            page.Canvas.DrawText( "12. COOP 25", textFont, null, brush, 200, 140 );
            PDFCOOP25Barcode coop25 = new PDFCOOP25Barcode( "0123456789" );
            page.Canvas.DrawBarcode( coop25, 200, 150 );

            page.Canvas.DrawText( "13. EAN-13", textFont, null, brush, 200, 210 );
            PDFEAN13Barcode ean13 = new PDFEAN13Barcode( "012345678901" );
            page.Canvas.DrawBarcode( ean13, 200, 220 );

            page.Canvas.DrawText( "14. EAN-8", textFont, null, brush, 200, 280 );
            PDFEAN8Barcode ean8 = new PDFEAN8Barcode( "0123456" );
            page.Canvas.DrawBarcode( ean8, 200, 290 );

            page.Canvas.DrawText( "15. IATA 25", textFont, null, brush, 200, 350 );
            PDFIATA25Barcode i25 = new PDFIATA25Barcode( "0123456789" );
            page.Canvas.DrawBarcode( i25, 200, 360 );

            page.Canvas.DrawText( "16. ISBN", textFont, null, brush, 200, 420 );
            PDFISBNBarcode isbn = new PDFISBNBarcode( "123456789" );
            page.Canvas.DrawBarcode( isbn, 200, 430 );

            page.Canvas.DrawText( "17. ISMN", textFont, null, brush, 200, 490 );
            PDFISMNBarcode ismn = new PDFISMNBarcode( "123456789" );
            page.Canvas.DrawBarcode( ismn, 200, 500 );

            page.Canvas.DrawText( "18. ISSN", textFont, null, brush, 200, 560 );
            PDFISSNBarcode issn = new PDFISSNBarcode( "123456789" );
            page.Canvas.DrawBarcode( issn, 200, 570 );

            page.Canvas.DrawText( "19. JAN-13", textFont, null, brush, 200, 630 );
            PDFJAN13Barcode jan13 = new PDFJAN13Barcode( "1234567890" );
            page.Canvas.DrawBarcode( jan13, 200, 640 );

            page.Canvas.DrawText( "20. Matrix 25", textFont, null, brush, 200, 700 );
            PDFMatrix25Barcode m25 = new PDFMatrix25Barcode( "0123456789" );
            page.Canvas.DrawBarcode( m25, 200, 710 );

            page.Canvas.DrawText( "21. Msi/Plessey", textFont, null, brush, 350, 70 );
            PDFMSIPlesseyBarcode msi = new PDFMSIPlesseyBarcode( "0123456789" );
            page.Canvas.DrawBarcode( msi, 350, 80 );

            page.Canvas.DrawText( "22. Planet", textFont, null, brush, 350, 140 );
            PDFPlanetBarcode planet = new PDFPlanetBarcode( "012345678901" );
            page.Canvas.DrawBarcode( planet, 350, 150 );

            page.Canvas.DrawText( "23. Postnet", textFont, null, brush, 350, 210 );
            PDFPostNetBarcode postnet = new PDFPostNetBarcode( "012345678" );
            page.Canvas.DrawBarcode( postnet, 350, 220 );

            page.Canvas.DrawText( "24. RM4SCC", textFont, null, brush, 350, 280 );
            PDFRM4SCCBarcode rm4scc = new PDFRM4SCCBarcode( "RM4SCC" );
            page.Canvas.DrawBarcode( rm4scc, 350, 290 );

            page.Canvas.DrawText( "25. SCC-14", textFont, null, brush, 350, 350 );
            PDFSCC14Barcode scc14 = new PDFSCC14Barcode( "0123456789012" );
            page.Canvas.DrawBarcode( scc14, 350, 360 );

            page.Canvas.DrawText( "26. SSCC-18", textFont, null, brush, 350, 420 );
            PDFSSCC18Barcode sscc18 = new PDFSSCC18Barcode( "00000012331234567" );
            page.Canvas.DrawBarcode( sscc18, 350, 430 );

            page.Canvas.DrawText( "27. UPC-A", textFont, null, brush, 350, 490 );
            PDFUPCABarcode upca = new PDFUPCABarcode( "87567816412" );
            upca.Supplement = "59999";
            upca.SupplementYDimension = 20;
            upca.SupplementDisplayLocation = BarcodeTextLocation.Above;
            page.Canvas.DrawBarcode( upca, 350, 500 );

            page.Canvas.DrawText( "28. UPC-E", textFont, null, brush, 350, 560 );
            PDFUPCEBarcode upce = new PDFUPCEBarcode( "0425261" );
            page.Canvas.DrawBarcode( upce, 350, 570 );

            // Second page for linear barcodes.
            page = doc.AddPage();
            page.Canvas.DrawText("1D/Linear barcodes (continued)", titleFont, null, brush, 20, 50);

            page.Canvas.DrawText("29. Singapore Post", textFont, null, brush, 20, 70);
            PDFSingaporePostBarcode singPost = new PDFSingaporePostBarcode("0123456789");
            page.Canvas.DrawBarcode(singPost, 20, 80);

            page.Canvas.DrawText("30. Royal Dutch TPG Post", textFont, null, brush, 20, 140);
            PDFKixBarcode kix = new PDFKixBarcode("0123456789");
            page.Canvas.DrawBarcode(kix, 20, 150);

            page.Canvas.DrawText("31. PZN", textFont, null, brush, 20, 210);
            PDFPZNBarcode pzn = new PDFPZNBarcode("123456");
            page.Canvas.DrawBarcode(pzn, 20, 220);

            page.Canvas.DrawText("32. Deutsche Post Identcode", textFont, null, brush, 20, 280);
            PDFIdentcodeBarcode identcode = new PDFIdentcodeBarcode("01234567890");
            page.Canvas.DrawBarcode(identcode, 20, 290);

            page.Canvas.DrawText("33. Deutsche Post Leitcode", textFont, null, brush, 20, 350);
            PDFLeitcodeBarcode leitcode = new PDFLeitcodeBarcode("0123456789012");
            page.Canvas.DrawBarcode(leitcode, 20, 360);

            page.Canvas.DrawText("34. USPS Facing Identification Mark", textFont, null, brush, 20, 420);
            PDFUSPSFIMBarcode fim = new PDFUSPSFIMBarcode("A");
            page.Canvas.DrawBarcode(fim, 20, 430);

            page.Canvas.DrawText("35. USPS Horizontal Bars", textFont, null, brush, 20, 490);
            PDFUSPSHorizontalBarcode hb = new PDFUSPSHorizontalBarcode("111");
            page.Canvas.DrawBarcode(hb, 20, 500);

            page.Canvas.DrawText("36. USPS Package Identification Code", textFont, null, brush, 20, 560);
            PDFUSPSPICBarcode pic = new PDFUSPSPICBarcode("910123456789012345678");
            page.Canvas.DrawBarcode(pic, 20, 570);

            page.Canvas.DrawText("37. FedEx Ground 96", textFont, null, brush, 20, 630);
            PDFFedExGround96Barcode fg96 = new PDFFedExGround96Barcode("960123456789012345678");
            page.Canvas.DrawBarcode(fg96, 20, 640);

            page.Canvas.DrawText("38. Pharmacode", textFont, null, brush, 20, 700);
            PDFPharmacodeBarcode pharma = new PDFPharmacodeBarcode("12345");
            page.Canvas.DrawBarcode(pharma, 20, 710);

            page.Canvas.DrawText("39. Code 32 - Italian Pharmacode", textFont, null, brush, 200, 70);
            PDFCode32Barcode c32 = new PDFCode32Barcode("12345678");
            page.Canvas.DrawBarcode(c32, 200, 80);

            page.Canvas.DrawText("40. UCC/EAN 128", textFont, null, brush, 200, 140);
            PDFEAN128Barcode ean128 = new PDFEAN128Barcode("0123456789");
            ean128.ApplicationIdentifier = "101";
            page.Canvas.DrawBarcode(ean128, 200, 150);

            // Create the 3rd page to display 2D barcodes.
            page = doc.AddPage( );

            page.Canvas.DrawText( "2D/Bidimensional barcodes", titleFont, null, brush, 20, 50 );

            page.Canvas.DrawText( "1. Codablock F", textFont, null, brush, 20, 70 );
            PDFCodablockFBarcode cf = new PDFCodablockFBarcode( );
            cf.Rows = 5;
            cf.Columns = 7;
            cf.Data = "1234567890";
            page.Canvas.DrawBarcode( cf, 20, 80 );

            page.Canvas.DrawText( "2. Code 16K", textFont, null, brush, 20, 140 );
            PDFCode16KBarcode c16k = new PDFCode16KBarcode( );
            c16k.Rows = 0;
            c16k.Data = "Abcd-1234567890-wxyZ";
            page.Canvas.DrawBarcode( c16k, 20, 150 );

            page.Canvas.DrawText( "3. DataMatrix", textFont, null, brush, 20, 210 );
            PDFDataMatrixBarcode dm = new PDFDataMatrixBarcode( );
            dm.Encoding = DataMatrixEncoding.ASCII;
            dm.SymbolSize = DataMatrixSymbolSize.Auto;
            dm.Data = "ABCDabcd";
            dm.XDimension = 3;
            page.Canvas.DrawBarcode( dm, 20, 220 );

            page.Canvas.DrawText( "4. MicroPDF417", textFont, null, brush, 20, 280 );
            PDFMicroPDF417Barcode mpdf417 = new PDFMicroPDF417Barcode( );
            mpdf417.CompactionMode = PDF417DataCompactionMode.Text;
            mpdf417.Data = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZAB";
            mpdf417.XDimension = 1;
            mpdf417.YDimension = 2.5f;
            mpdf417.SymbolSize = MicroPDF417SymbolSize.Size20x4;
            page.Canvas.DrawBarcode( mpdf417, 20, 290 );

            page.Canvas.DrawText( "5. PDF417", textFont, null, brush, 20, 370 );
            PDF417Barcode pdf417 = new PDF417Barcode( );
            pdf417.CompactionMode = PDF417DataCompactionMode.Text;
            pdf417.Data = "ABCDEF";
            pdf417.Rows = 5;
            pdf417.Columns = 5;
            pdf417.XDimension = 1;
            pdf417.YDimension = 10;
            pdf417.ErrorCorrectionLevel = PDF417ErrorCorrectionLevel.Level2;
            page.Canvas.DrawBarcode( pdf417, 20, 380 );

            doc.SaveToFile( "barcodes.pdf" );
        }
    }
}


Barcodes.vb

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Barcodes
Imports O2S.Components.PDF4NET.Graphics.Fonts

Namespace O2S.Samples.PDF4NET.Barcodes
    '/ <summary>
    '/ This sample shows how to display barcodes in a PDF document.
    '/ </summary>
    Class Barcodes
        Shared Sub Main()
            ' Create the PDF document
            Dim doc As New PDFDocument
            Dim page As PDFPage = doc.AddPage()

            ' Create the helper graphic objects.
            Dim titleFont As New PDFFont(FontFace.Helvetica, 10)
            titleFont.Bold = True
            Dim textFont As New PDFFont(FontFace.Helvetica, 8)
            Dim brush As New PDFBrush(New PDFColor(Color.Black))

            page.Canvas.DrawText("1D/Linear barcodes", titleFont, Nothing, brush, 20, 50)

            page.Canvas.DrawText("1. Codabar", textFont, Nothing, brush, 20, 70)
            Dim cb As New PDFCodabarBarcode("0123456789")
            page.Canvas.DrawBarcode(cb, 20, 80)

            page.Canvas.DrawText("2. Code 11", textFont, Nothing, brush, 20, 140)
            Dim c11 As New PDFCode11Barcode("0123456789")
            page.Canvas.DrawBarcode(c11, 20, 150)

            page.Canvas.DrawText("3. Code 128A", textFont, Nothing, brush, 20, 210)
            Dim c128a As New PDFCode128ABarcode("CODE128A")
            page.Canvas.DrawBarcode(c128a, 20, 220)

            page.Canvas.DrawText("4. Code 128B", textFont, Nothing, brush, 20, 280)
            Dim c128b As New PDFCode128BBarcode("CODE128B")
            page.Canvas.DrawBarcode(c128b, 20, 290)

            page.Canvas.DrawText("5. Code 128C", textFont, Nothing, brush, 20, 350)
            Dim c128c As New PDFCode128CBarcode("0123456789")
            page.Canvas.DrawBarcode(c128c, 20, 360)

            page.Canvas.DrawText("6. Code 25", textFont, Nothing, brush, 20, 420)
            Dim c25 As New PDFCode25Barcode("0123456789")
            page.Canvas.DrawBarcode(c25, 20, 430)

            page.Canvas.DrawText("7. Code 25 Interleaved", textFont, Nothing, brush, 20, 490)
            Dim c25i As New PDFCode25InterleavedBarcode("0123456789")
            page.Canvas.DrawBarcode(c25i, 20, 500)

            page.Canvas.DrawText("8. Code 39", textFont, Nothing, brush, 20, 560)
            Dim c39 As New PDFCode39Barcode("CODE39")
            page.Canvas.DrawBarcode(c39, 20, 570)

            page.Canvas.DrawText("9. Code 39 Extended", textFont, Nothing, brush, 20, 630)
            Dim c39x As New PDFCode39ExtendedBarcode("C39Ext")
            page.Canvas.DrawBarcode(c39x, 20, 640)

            page.Canvas.DrawText("10. Code 93", textFont, Nothing, brush, 20, 700)
            Dim c93 As New PDFCode93Barcode("CODE93")
            page.Canvas.DrawBarcode(c93, 20, 710)

            page.Canvas.DrawText("11. Code 93 Extended", textFont, Nothing, brush, 200, 70)
            Dim c93x As New PDFCode93ExtendedBarcode("C93Ext")
            page.Canvas.DrawBarcode(c93x, 200, 80)

            page.Canvas.DrawText("12. COOP 25", textFont, Nothing, brush, 200, 140)
            Dim coop25 As New PDFCOOP25Barcode("0123456789")
            page.Canvas.DrawBarcode(coop25, 200, 150)

            page.Canvas.DrawText("13. EAN-13", textFont, Nothing, brush, 200, 210)
            Dim ean13 As New PDFEAN13Barcode("012345678901")
            page.Canvas.DrawBarcode(ean13, 200, 220)

            page.Canvas.DrawText("14. EAN-8", textFont, Nothing, brush, 200, 280)
            Dim ean8 As New PDFEAN8Barcode("0123456")
            page.Canvas.DrawBarcode(ean8, 200, 290)

            page.Canvas.DrawText("15. IATA 25", textFont, Nothing, brush, 200, 350)
            Dim i25 As New PDFIATA25Barcode("0123456789")
            page.Canvas.DrawBarcode(i25, 200, 360)

            page.Canvas.DrawText("16. ISBN", textFont, Nothing, brush, 200, 420)
            Dim isbn As New PDFISBNBarcode("123456789")
            page.Canvas.DrawBarcode(isbn, 200, 430)

            page.Canvas.DrawText("17. ISMN", textFont, Nothing, brush, 200, 490)
            Dim ismn As New PDFISMNBarcode("123456789")
            page.Canvas.DrawBarcode(ismn, 200, 500)

            page.Canvas.DrawText("18. ISSN", textFont, Nothing, brush, 200, 560)
            Dim issn As New PDFISSNBarcode("123456789")
            page.Canvas.DrawBarcode(issn, 200, 570)

            page.Canvas.DrawText("19. JAN-13", textFont, Nothing, brush, 200, 630)
            Dim jan13 As New PDFJAN13Barcode("1234567890")
            page.Canvas.DrawBarcode(jan13, 200, 640)

            page.Canvas.DrawText("20. Matrix 25", textFont, Nothing, brush, 200, 700)
            Dim m25 As New PDFMatrix25Barcode("0123456789")
            page.Canvas.DrawBarcode(m25, 200, 710)

            page.Canvas.DrawText("21. Msi/Plessey", textFont, Nothing, brush, 350, 70)
            Dim msi As New PDFMSIPlesseyBarcode("0123456789")
            page.Canvas.DrawBarcode(msi, 350, 80)

            page.Canvas.DrawText("22. Planet", textFont, Nothing, brush, 350, 140)
            Dim planet As New PDFPlanetBarcode("012345678901")
            page.Canvas.DrawBarcode(planet, 350, 150)

            page.Canvas.DrawText("23. Postnet", textFont, Nothing, brush, 350, 210)
            Dim postnet As New PDFPostNetBarcode("012345678")
            page.Canvas.DrawBarcode(postnet, 350, 220)

            page.Canvas.DrawText("24. RM4SCC", textFont, Nothing, brush, 350, 280)
            Dim rm4scc As New PDFRM4SCCBarcode("RM4SCC")
            page.Canvas.DrawBarcode(rm4scc, 350, 290)

            page.Canvas.DrawText("25. SCC-14", textFont, Nothing, brush, 350, 350)
            Dim scc14 As New PDFSCC14Barcode("0123456789012")
            page.Canvas.DrawBarcode(scc14, 350, 360)

            page.Canvas.DrawText("26. SSCC-18", textFont, Nothing, brush, 350, 420)
            Dim sscc18 As New PDFSSCC18Barcode("00000012331234567")
            page.Canvas.DrawBarcode(sscc18, 350, 430)

            page.Canvas.DrawText("27. UPC-A", textFont, Nothing, brush, 350, 490)
            Dim upca As New PDFUPCABarcode("87567816412")
            upca.Supplement = "59999"
            upca.SupplementYDimension = 20
            upca.SupplementDisplayLocation = BarcodeTextLocation.Above
            page.Canvas.DrawBarcode(upca, 350, 500)

            page.Canvas.DrawText("28. UPC-E", textFont, Nothing, brush, 350, 560)
            Dim upce As New PDFUPCEBarcode("0425261")
            page.Canvas.DrawBarcode(upce, 350, 570)

            ' Second page for linear barcodes.
            page = doc.AddPage()
            page.Canvas.DrawText("1D/Linear barcodes (continued)", titleFont, Nothing, brush, 20, 50)

            page.Canvas.DrawText("29. Singapore Post", textFont, Nothing, brush, 20, 70)
            Dim singPost As PDFSingaporePostBarcode = New PDFSingaporePostBarcode("0123456789")
            page.Canvas.DrawBarcode(singPost, 20, 80)

            page.Canvas.DrawText("30. Royal Dutch TPG Post", textFont, Nothing, brush, 20, 140)
            Dim kix As PDFKixBarcode = New PDFKixBarcode("0123456789")
            page.Canvas.DrawBarcode(kix, 20, 150)

            page.Canvas.DrawText("31. PZN", textFont, Nothing, brush, 20, 210)
            Dim pzn As PDFPZNBarcode = New PDFPZNBarcode("123456")
            page.Canvas.DrawBarcode(pzn, 20, 220)

            page.Canvas.DrawText("32. Deutsche Post Identcode", textFont, Nothing, brush, 20, 280)
            Dim identcode As PDFIdentcodeBarcode = New PDFIdentcodeBarcode("01234567890")
            page.Canvas.DrawBarcode(identcode, 20, 290)

            page.Canvas.DrawText("33. Deutsche Post Leitcode", textFont, Nothing, brush, 20, 350)
            Dim leitcode As PDFLeitcodeBarcode = New PDFLeitcodeBarcode("0123456789012")
            page.Canvas.DrawBarcode(leitcode, 20, 360)

            page.Canvas.DrawText("34. USPS Facing Identification Mark", textFont, Nothing, brush, 20, 420)
            Dim fim As PDFUSPSFIMBarcode = New PDFUSPSFIMBarcode("A")
            page.Canvas.DrawBarcode(fim, 20, 430)

            page.Canvas.DrawText("35. USPS Horizontal Bars", textFont, Nothing, brush, 20, 490)
            Dim hb As PDFUSPSHorizontalBarcode = New PDFUSPSHorizontalBarcode("111")
            page.Canvas.DrawBarcode(hb, 20, 500)

            page.Canvas.DrawText("36. USPS Package Identification Code", textFont, Nothing, brush, 20, 560)
            Dim pic As PDFUSPSPICBarcode = New PDFUSPSPICBarcode("910123456789012345678")
            page.Canvas.DrawBarcode(pic, 20, 570)

            page.Canvas.DrawText("37. FedEx Ground 96", textFont, Nothing, brush, 20, 630)
            Dim fg96 As PDFFedExGround96Barcode = New PDFFedExGround96Barcode("960123456789012345678")
            page.Canvas.DrawBarcode(fg96, 20, 640)

            page.Canvas.DrawText("38. Pharmacode", textFont, Nothing, brush, 20, 700)
            Dim pharma As PDFPharmacodeBarcode = New PDFPharmacodeBarcode("12345")
            page.Canvas.DrawBarcode(pharma, 20, 710)

            page.Canvas.DrawText("39. Code 32 - Italian Pharmacode", textFont, Nothing, brush, 200, 70)
            Dim c32 As PDFCode32Barcode = New PDFCode32Barcode("12345678")
            page.Canvas.DrawBarcode(c32, 200, 80)

            page.Canvas.DrawText("40. UCC/EAN 128", textFont, Nothing, brush, 200, 140)
            Dim ean128 As PDFEAN128Barcode = New PDFEAN128Barcode("0123456789")
            ean128.ApplicationIdentifier = "101"
            page.Canvas.DrawBarcode(ean128, 200, 150)

            ' Create the third page to display 2D barcodes.
            page = doc.AddPage()

            page.Canvas.DrawText("2D/Bidimensional barcodes", titleFont, Nothing, brush, 20, 50)

            page.Canvas.DrawText("1. Codablock F", textFont, Nothing, brush, 20, 70)
            Dim cf As New PDFCodablockFBarcode
            cf.Rows = 5
            cf.Columns = 7
            cf.Data = "1234567890"
            page.Canvas.DrawBarcode(cf, 20, 80)

            page.Canvas.DrawText("2. Code 16K", textFont, Nothing, brush, 20, 140)
            Dim c16k As New PDFCode16KBarcode
            c16k.Rows = 0
            c16k.Data = "Abcd-1234567890-wxyZ"
            page.Canvas.DrawBarcode(c16k, 20, 150)

            page.Canvas.DrawText("3. DataMatrix", textFont, Nothing, brush, 20, 210)
            Dim dm As New PDFDataMatrixBarcode
            dm.Encoding = DataMatrixEncoding.ASCII
            dm.SymbolSize = DataMatrixSymbolSize.Auto
            dm.Data = "ABCDabcd"
            dm.XDimension = 3
            page.Canvas.DrawBarcode(dm, 20, 220)

            page.Canvas.DrawText("4. MicroPDF417", textFont, Nothing, brush, 20, 280)
            Dim mpdf417 As New PDFMicroPDF417Barcode
            mpdf417.CompactionMode = PDF417DataCompactionMode.Text
            mpdf417.Data = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" + _
                "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZAB"
            mpdf417.XDimension = 1
            mpdf417.YDimension = 2.5F
            mpdf417.SymbolSize = MicroPDF417SymbolSize.Size20x4
            page.Canvas.DrawBarcode(mpdf417, 20, 290)

            page.Canvas.DrawText("5. PDF417", textFont, Nothing, brush, 20, 370)
            Dim pdf417 As New PDF417Barcode
            pdf417.CompactionMode = PDF417DataCompactionMode.Text
            pdf417.Data = "ABCDEF"
            pdf417.Rows = 5
            pdf417.Columns = 5
            pdf417.XDimension = 1
            pdf417.YDimension = 10
            pdf417.ErrorCorrectionLevel = PDF417ErrorCorrectionLevel.Level2
            page.Canvas.DrawBarcode(pdf417, 20, 380)

            doc.SaveToFile("barcodes.pdf")
        End Sub 'Main
    End Class 'Barcodes
End Namespace 'O2S.Samples.PDF4NET.Barcodes


Samples: Bezier

Samples

Bezier

This samples demonstrates the bezier splines drawing capabilities of the PDF4NET library. It creates a 1 page document. On the first page, it draws 50 bezier splines positioned at random locations. The colors of the bezier splines are generated randomly.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Bezier.cs

/// <fileName>
/// File name: Bezier.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Bezier
{
    /// <summary>
    /// This sample will show how to draw Bezier splines
    /// on the page.
    /// </summary>
    class Bezier
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create first page
            PDFPage pdfPage1 = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            Random rnd = new Random( );
            for( int i = 0; i < 50; i++ )
            {
                // Create random colors for drawing the spline
                PDFColor penColor = new PDFColor( ( byte )rnd.Next( 256 ),
                    ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );

                // Create the pen to draw the border
                PDFPen randomPen = new PDFPen( penColor, 1 );

                // Generate random control points
                float x1 = rnd.Next( ( int )pdfPage1.Width );
                float y1 = rnd.Next( ( int )pdfPage1.Height );
                float x2 = rnd.Next( ( int )pdfPage1.Width );
                float y2 = rnd.Next( ( int )pdfPage1.Height );
                float x3 = rnd.Next( ( int )pdfPage1.Width );
                float y3 = rnd.Next( ( int )pdfPage1.Height );
                float x4 = rnd.Next( ( int )pdfPage1.Width );
                float y4 = rnd.Next( ( int )pdfPage1.Height );

                // Draw the Bezier spline
                pdfPage1.Canvas.DrawBezier( randomPen, x1, y1, x2, y2, x3, y3, x4, y4 );
            }

            // Draw a label
            pdfPage1.Canvas.DrawText( "Random Bezier splines",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Save the document to disk
            pdfDoc.SaveToFile( "bezier.pdf" );
        }
    }
}


Bezier.vb

'
' File name: Bezier.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.Bezier
    '/ <summary>
    '/ This sample will show how to draw Bezier splines
    '/ on the page.
    '/ </summary>
    Class Bezier
        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create first page
            Dim pdfPage1 As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())

            Dim rnd As New Random()
            Dim i As Integer
            For i = 0 To 49
                ' Create random colors for drawing the spline
                Dim penColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))

                ' Create the pen to draw the border
                Dim randomPen As New PDFPen(penColor, 1)

                ' Generate random control points
                Dim x1 As Single = rnd.Next(CInt(pdfPage1.Width))
                Dim y1 As Single = rnd.Next(CInt(pdfPage1.Height))
                Dim x2 As Single = rnd.Next(CInt(pdfPage1.Width))
                Dim y2 As Single = rnd.Next(CInt(pdfPage1.Height))
                Dim x3 As Single = rnd.Next(CInt(pdfPage1.Width))
                Dim y3 As Single = rnd.Next(CInt(pdfPage1.Height))
                Dim x4 As Single = rnd.Next(CInt(pdfPage1.Width))
                Dim y4 As Single = rnd.Next(CInt(pdfPage1.Height))

                ' Draw the Bezier spline
                pdfPage1.Canvas.DrawBezier(randomPen, x1, y1, x2, y2, x3, y3, x4, y4)
            Next i

            ' Draw a label
            pdfPage1.Canvas.DrawText("Random Bezier splines", fontText, Nothing, blackBrush, 20, 20)

            ' Save the document to disk
            pdfDoc.SaveToFile("bezier.pdf")
        End Sub 'Main
    End Class 'Bezier
End Namespace 'O2S.Samples.PDF4NET.Bezier


Samples: Bookmarks

Samples

Bookmarks

This samples demonstrates the bookmarks capabilities of the PDF4NET library. It creates a 10 pages document. Each page is considered to be a chapter. Each chapter has 2 sections, and each section has 3 paragraphs. Then, the sample builds the corresponding outlines tree, allowing to quickly navigate to each chapter / section / paragraph.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Bookmarks.cs

/// <fileName>
/// File name: Bookmarks.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Bookmarks
{
    /// <summary>
    /// This sample will show how to create a bookmarks/outlines tree
    /// for a document
    /// </summary>
    class Bookmarks
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the graphic objects
            PDFFont fontChapter = new PDFFont( FontFace.Helvetica, 20 );
            fontChapter.Bold = true;
            PDFFont fontSection = new PDFFont( FontFace.Helvetica, 16 );
            fontSection.Italic = true;
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Display the outlines when opening the document
            pdfDoc.ViewerPreferences.DisplayMode = DisplayMode.DisplayOutlines;

            // Create 10 pages
            for( int i = 0; i < 10; i++ )
            {
                PDFPage pdfPage = pdfDoc.AddPage( );
                pdfPage.Canvas.DrawText( "Chapter " + ( i + 1 ).ToString( ),
                    fontChapter, null, blackBrush, 10, 10, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Section " + ( i + 1 ).ToString( ) + ".1",
                    fontSection, null, blackBrush, 20, 32, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Paragraph " + ( i + 1 ).ToString( ) + ".1.1",
                    fontText, null, blackBrush, 30, 50, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Paragraph " + ( i + 1 ).ToString( ) + ".1.2",
                    fontText, null, blackBrush, 30, 200, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Paragraph " + ( i + 1 ).ToString( ) + ".1.3",
                    fontText, null, blackBrush, 30, 300, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Section " + ( i + 1 ).ToString( ) + ".2",
                    fontSection, null, blackBrush, 20, 400, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Paragraph " + ( i + 1 ).ToString( ) + ".2.1",
                    fontText, null, blackBrush, 30, 420, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Paragraph " + ( i + 1 ).ToString( ) + ".2.2",
                    fontText, null, blackBrush, 30, 570, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "Paragraph " + ( i + 1 ).ToString( ) + ".2.3",
                    fontText, null, blackBrush, 30, 650, 0, TextAlign.TopLeft );
            }

            // Create the bookmarks tree
            // Create a root outline
            PDFOutline root = pdfDoc.Outlines.Add( "Bookmarks", new PDFColor( Color.Black ), true,
                OutlineDisplay.Bold, pdfDoc.Pages[0], 0 );

            // Create document bookmarks
            for( int i = 0; i < pdfDoc.Pages.Count; i++ )
            {
                // Create chapter bookmark
                PDFOutline chapter = root.Outlines.Add( "Chapter " + ( i + 1 ).ToString( ),
                    new PDFColor( Color.Blue ), true, OutlineDisplay.Italic, pdfDoc.Pages[i], 0 );
                // Create section 1 bookmark
                PDFOutline section1 = chapter.Outlines.Add( "Section " + ( i + 1 ).ToString( ) + ".1",
                    new PDFColor( Color.Green ), true, OutlineDisplay.Italic, pdfDoc.Pages[i], 32 );
                // Create paragraph bookmarks
                section1.Outlines.Add( "Paragraph " + ( i + 1 ).ToString( ) + ".1.1",
                    new PDFColor( Color.Red ), true, OutlineDisplay.Regular, pdfDoc.Pages[i], 50 );
                section1.Outlines.Add( "Paragraph " + ( i + 1 ).ToString( ) + ".1.2",
                    new PDFColor( Color.Red ), true, OutlineDisplay.Regular, pdfDoc.Pages[i], 200 );
                section1.Outlines.Add( "Paragraph " + ( i + 1 ).ToString( ) + ".1.3",
                    new PDFColor( Color.Red ), true, OutlineDisplay.Regular, pdfDoc.Pages[i], 300 );
                // Create section 2 bookmark
                PDFOutline section2 = chapter.Outlines.Add( "Section " + ( i + 1 ).ToString( ) + ".2",
                    new PDFColor( Color.Green ), true, OutlineDisplay.Italic, pdfDoc.Pages[i], 400 );
                // Create paragraph bookmarks
                section2.Outlines.Add( "Paragraph " + ( i + 1 ).ToString( ) + ".2.1",
                    new PDFColor( Color.Red ), true, OutlineDisplay.Regular, pdfDoc.Pages[i], 420 );
                section2.Outlines.Add( "Paragraph " + ( i + 1 ).ToString( ) + ".2.2",
                    new PDFColor( Color.Red ), true, OutlineDisplay.Regular, pdfDoc.Pages[i], 570 );
                section2.Outlines.Add( "Paragraph " + ( i + 1 ).ToString( ) + ".2.3",
                    new PDFColor( Color.Red ), true, OutlineDisplay.Regular, pdfDoc.Pages[i], 650 );
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "bookmarks.pdf" );
        }
    }
}


Bookmarks.vb

'
' File name: Bookmarks.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.Bookmarks
    '/ <summary>
    '/ This sample will show how to create a bookmarks/outlines tree
    '/ for a document
    '/ </summary>
    Class Bookmarks

        Shared Sub Main()
            ' Create the graphic objects
            Dim fontChapter As New PDFFont(FontFace.Helvetica, 20)
            fontChapter.Bold = True
            Dim fontSection As New PDFFont(FontFace.Helvetica, 16)
            fontSection.Italic = True
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Display the outlines when opening the document
            pdfDoc.ViewerPreferences.DisplayMode = DisplayMode.DisplayOutlines

            ' Create 10 pages
            Dim i As Integer
            For i = 0 To 9
                Dim pdfPage As PDFPage = pdfDoc.AddPage()
                pdfPage.Canvas.DrawText("Chapter " + (i + 1).ToString(), fontChapter, Nothing, blackBrush, 10, 10)
                pdfPage.Canvas.DrawText("Section " + (i + 1).ToString() + ".1", fontSection, Nothing, blackBrush, 20, 32)
                pdfPage.Canvas.DrawText("Paragraph " + (i + 1).ToString() + ".1.1", fontText, Nothing, blackBrush, 30, 50)
                pdfPage.Canvas.DrawText("Paragraph " + (i + 1).ToString() + ".1.2", fontText, Nothing, blackBrush, 30, 200)
                pdfPage.Canvas.DrawText("Paragraph " + (i + 1).ToString() + ".1.3", fontText, Nothing, blackBrush, 30, 300)
                pdfPage.Canvas.DrawText("Section " + (i + 1).ToString() + ".2", fontSection, Nothing, blackBrush, 20, 400)
                pdfPage.Canvas.DrawText("Paragraph " + (i + 1).ToString() + ".2.1", fontText, Nothing, blackBrush, 30, 420)
                pdfPage.Canvas.DrawText("Paragraph " + (i + 1).ToString() + ".2.2", fontText, Nothing, blackBrush, 30, 570)
                pdfPage.Canvas.DrawText("Paragraph " + (i + 1).ToString() + ".2.3", fontText, Nothing, blackBrush, 30, 650)
            Next i

            ' Create the bookmarks tree
            ' Create a root outline
            Dim root As PDFOutline = pdfDoc.Outlines.Add("Bookmarks", New PDFColor(Color.Black), True, OutlineDisplay.Bold, pdfDoc.Pages(0), 0)

            ' Create document bookmarks
            'Dim i As Integer
            For i = 0 To pdfDoc.Pages.Count - 1
                ' Create chapter bookmark
                Dim chapter As PDFOutline = root.Outlines.Add("Chapter " + (i + 1).ToString(), New PDFColor(Color.Blue), True, OutlineDisplay.Italic, pdfDoc.Pages(i), 0)
                ' Create section 1 bookmark
                Dim section1 As PDFOutline = chapter.Outlines.Add("Section " + (i + 1).ToString() + ".1", New PDFColor(Color.Green), True, OutlineDisplay.Italic, pdfDoc.Pages(i), 32)
                ' Create paragraph bookmarks
                section1.Outlines.Add("Paragraph " + (i + 1).ToString() + _
                    ".1.1", New PDFColor(Color.Red), True, OutlineDisplay.Regular, _
                    pdfDoc.Pages(i), 50)
                section1.Outlines.Add("Paragraph " + (i + 1).ToString() + _
                    ".1.2", New PDFColor(Color.Red), True, OutlineDisplay.Regular, _
                    pdfDoc.Pages(i), 200)
                section1.Outlines.Add("Paragraph " + (i + 1).ToString() + _
                    ".1.3", New PDFColor(Color.Red), True, OutlineDisplay.Regular, _
                    pdfDoc.Pages(i), 300)
                ' Create section 2 bookmark
                Dim section2 As PDFOutline = chapter.Outlines.Add("Section " + (i + 1).ToString() + _
                    ".2", New PDFColor(Color.Green), True, OutlineDisplay.Italic, pdfDoc.Pages(i), 400)
                ' Create paragraph bookmarks
                section2.Outlines.Add("Paragraph " + (i + 1).ToString() + _
                    ".2.1", New PDFColor(Color.Red), True, OutlineDisplay.Regular, _
                    pdfDoc.Pages(i), 420)
                section2.Outlines.Add("Paragraph " + (i + 1).ToString() + _
                    ".2.2", New PDFColor(Color.Red), True, OutlineDisplay.Regular, _
                    pdfDoc.Pages(i), 570)
                section2.Outlines.Add("Paragraph " + (i + 1).ToString() + _
                    ".2.3", New PDFColor(Color.Red), True, OutlineDisplay.Regular, _
                    pdfDoc.Pages(i), 650)
            Next i

            ' Save the document to disk
            pdfDoc.SaveToFile("bookmarks.pdf")
        End Sub 'Main
    End Class 'Bookmarks
End Namespace 'O2S.Samples.PDF4NET.Bookmarks


Samples: CharacterMap

Samples

CharacterMap

This samples prints all the font glyphs in a standard latin font, as they are represented by the pdf. For each glyph, its decimal and hex code are printed. On the second page, it prints all the glyphs in Symbol font, together with their decimal and hex codes. The third page is similar to second page, but it uses the ZapfDingbats font.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


CharacterMap.cs

/// <fileName>
/// File name: CharacterMap.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.CharacterMap
{
    /// <summary>
    /// This sample prints all available characters in WinAnsiEncoding, plus
    /// those available in ZapfDingbats and Symbol fonts.
    /// </summary>
    class CharacterMap
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            DrawFirstPage( pdfDoc );
            DrawSecondPage( pdfDoc );
            DrawThirdPage( pdfDoc );

            // Save the document to disk
            pdfDoc.SaveToFile( "charactermap.pdf" );
        }

        private static void DrawFirstPage( PDFDocument pdfDoc )
        {
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFFont fontCode = new PDFFont( FontFace.Helvetica, 11 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            pdfPage.Canvas.DrawText( "Latin font - WinAnsiEncoding", fontText, null, blackBrush,
                10, 30, 0, TextAlign.TopLeft );

            // Draw the header for the first column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 10, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 70, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 100, 50, 0, TextAlign.TopLeft );
            // Draw the header for the second column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 170, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 230, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 260, 50, 0, TextAlign.TopLeft );
            // Draw the header for the third column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 330, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 390, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 420, 50, 0, TextAlign.TopLeft );
            // Draw the header for the fourth column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 490, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 550, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 580, 50, 0, TextAlign.TopLeft );

            // Draw the codes and characters
            float xDec = 10;
            float xHex = 70;
            float xChar = 100;
            float xDelta = 160;
            float y = 65;
            byte i = 31;
            while( i <= 255 )
            {
                i++;
                if( ( ( i - 32 ) % 60 == 0 ) && i != 32 )
                {
                    xDec = xDec + xDelta;
                    xHex = xHex + xDelta;
                    xChar = xChar + xDelta;
                    y = 65;
                }

                char c = ( char )i;
                pdfPage.Canvas.DrawText( i.ToString( ), fontCode, null, blackBrush, xDec, y, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "\\x" + i.ToString( "X" ),
                    fontCode, null, blackBrush, xHex, y, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( c.ToString( ), fontCode, null, blackBrush, xChar, y, 0, TextAlign.TopLeft );
                y = y + 12;

                if( i == 255 )
                {
                    break;
                }
            }
        }

        private static void DrawSecondPage( PDFDocument pdfDoc )
        {
            // Create second page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontChar = new PDFFont( FontFace.Symbol, 11 );
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFFont fontCode = new PDFFont( FontFace.Helvetica, 11 );

            pdfPage.Canvas.DrawText( "Symbol font", fontText, null, blackBrush,
                10, 30, 0, TextAlign.TopLeft );

            // Draw the header for the first column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 10, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 70, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 100, 50, 0, TextAlign.TopLeft );
            // Draw the header for the second column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 170, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 230, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 260, 50, 0, TextAlign.TopLeft );
            // Draw the header for the third column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 330, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 390, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 420, 50, 0, TextAlign.TopLeft );
            // Draw the header for the fourth column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 490, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 550, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 580, 50, 0, TextAlign.TopLeft );

            // Draw the codes and characters
            float xDec = 10;
            float xHex = 70;
            float xChar = 100;
            float xDelta = 160;
            float y = 65;
            byte i = 31;
            while( i <= 255 )
            {
                i++;
                if( ( ( i - 32 ) % 60 == 0 ) && i != 32 )
                {
                    xDec = xDec + xDelta;
                    xHex = xHex + xDelta;
                    xChar = xChar + xDelta;
                    y = 65;
                }

                char c = ( char )i;
                pdfPage.Canvas.DrawText( i.ToString( ), fontCode, null, blackBrush, xDec, y, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "\\x" + i.ToString( "X" ), fontCode, null, blackBrush, xHex, y, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( c.ToString( ), fontChar, null, blackBrush, xChar, y, 0, TextAlign.TopLeft );
                y = y + 12;

                if( i == 255 )
                {
                    break;
                }
            }
        }

        private static void DrawThirdPage( PDFDocument pdfDoc )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontChar = new PDFFont( FontFace.ZapfDingbats, 11 );
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFFont fontCode = new PDFFont( FontFace.Helvetica, 11 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            pdfPage.Canvas.DrawText( "ZapfDingbats font", fontText, null, blackBrush, 10, 30, 0, TextAlign.TopLeft );

            // Draw the header for the first column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 10, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 70, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 100, 50, 0, TextAlign.TopLeft );
            // Draw the header for the second column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 170, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 230, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 260, 50, 0, TextAlign.TopLeft );
            // Draw the header for the third column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 330, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 390, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 420, 50, 0, TextAlign.TopLeft );
            // Draw the header for the fourth column
            pdfPage.Canvas.DrawText( "Decimal", fontText, null, blackBrush, 490, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Hex", fontText, null, blackBrush, 550, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Char", fontText, null, blackBrush, 580, 50, 0, TextAlign.TopLeft );

            // Draw the codes and characters
            float xDec = 10;
            float xHex = 70;
            float xChar = 100;
            float xDelta = 160;
            float y = 65;
            byte i = 31;
            while( i <= 255 )
            {
                i++;
                if( ( ( i - 32 ) % 60 == 0 ) && i != 32 )
                {
                    xDec = xDec + xDelta;
                    xHex = xHex + xDelta;
                    xChar = xChar + xDelta;
                    y = 65;
                }

                char c = ( char )i;
                pdfPage.Canvas.DrawText( i.ToString( ), fontCode, null, blackBrush, xDec, y, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( "\\x" + i.ToString( "X" ), fontCode, null, blackBrush, xHex, y, 0, TextAlign.TopLeft );
                pdfPage.Canvas.DrawText( c.ToString( ), fontChar, null, blackBrush, xChar, y, 0, TextAlign.TopLeft );
                y = y + 12;

                if( i == 255 )
                {
                    break;
                }
            }
        }
    }
}


CharacterMap.vb

'
' File name: CharacterMap.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Namespace O2S.Samples.PDF4NET.CharacterMap
    ''' <summary>
    ''' Summary description for CharacterMap.
    ''' </summary>
    Class CharacterMap
        ''' <summary>
        ''' This sample prints all available characters in WinAnsiEncoding, plus
        ''' those available in ZapfDingbats and Symbol fonts.
        ''' </summary>
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            ' Create the pdf document
            Dim pdfDoc As PDFDocument = New PDFDocument
            DrawFirstPage(pdfDoc)
            DrawSecondPage(pdfDoc)
            DrawThirdPage(pdfDoc)
            ' Save the document to disk
            pdfDoc.SaveToFile("charactermap.pdf")
        End Sub
        Private Shared Sub DrawFirstPage(ByVal pdfDoc As PDFDocument)
            Dim pdfPage As PDFPage = pdfDoc.AddPage()
            ' Create the graphic objects
            Dim fontText As PDFFont = New PDFFont(FontFace.Helvetica, 12)
            Dim fontCode As PDFFont = New PDFFont(FontFace.Helvetica, 11)
            Dim blackBrush As PDFBrush = New PDFBrush(New PDFColor)
            pdfPage.Canvas.DrawText("Latin font - WinAnsiEncoding", fontText, Nothing, blackBrush, 10, 30, _
             0, TextAlign.TopLeft)
            ' Draw the header for the first column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 10, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 70, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 100, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the second column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 170, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 230, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 260, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the third column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 330, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 390, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 420, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the fourth column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 490, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 550, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 580, 50, _
             0, TextAlign.TopLeft)
            ' Draw the codes and characters
            Dim xDec As Single = 10
            Dim xHex As Single = 70
            Dim xChar As Single = 100
            Dim xDelta As Single = 160
            Dim y As Single = 65
            Dim i As Byte = 31
            While i <= 255
                i += 1
                If ((i - 32) Mod 60 = 0) AndAlso i <> 32 Then
                    xDec = xDec + xDelta
                    xHex = xHex + xDelta
                    xChar = xChar + xDelta
                    y = 65
                End If
                Dim c As Char = Microsoft.VisualBasic.ChrW(i)
                pdfPage.Canvas.DrawText(i.ToString(), fontCode, Nothing, blackBrush, xDec, y, _
                 0, TextAlign.TopLeft)
                pdfPage.Canvas.DrawText("\x" + i.ToString("X"), fontCode, Nothing, blackBrush, xHex, y, _
                 0, TextAlign.TopLeft)
                pdfPage.Canvas.DrawText(c.ToString(), fontCode, Nothing, blackBrush, xChar, y, _
                 0, TextAlign.TopLeft)
                y = y + 12
                If i = 255 Then
                    Exit While
                End If
            End While
        End Sub
        Private Shared Sub DrawSecondPage(ByVal pdfDoc As PDFDocument)
            ' Create second page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()
            ' Create the graphic objects
            Dim fontChar As PDFFont = New PDFFont(FontFace.Symbol, 11)
            Dim fontText As PDFFont = New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As PDFBrush = New PDFBrush(New PDFColor)
            Dim fontCode As PDFFont = New PDFFont(FontFace.Helvetica, 11)
            pdfPage.Canvas.DrawText("Symbol font", fontText, Nothing, blackBrush, 10, 30, _
             0, TextAlign.TopLeft)
            ' Draw the header for the first column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 10, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 70, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 100, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the second column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 170, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 230, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 260, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the third column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 330, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 390, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 420, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the fourth column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 490, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 550, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 580, 50, _
             0, TextAlign.TopLeft)
            ' Draw the codes and characters
            Dim xDec As Single = 10
            Dim xHex As Single = 70
            Dim xChar As Single = 100
            Dim xDelta As Single = 160
            Dim y As Single = 65
            Dim i As Byte = 31
            While i <= 255
                i += 1
                If ((i - 32) Mod 60 = 0) AndAlso i <> 32 Then
                    xDec = xDec + xDelta
                    xHex = xHex + xDelta
                    xChar = xChar + xDelta
                    y = 65
                End If
                Dim c As Char = Microsoft.VisualBasic.ChrW(i)
                pdfPage.Canvas.DrawText(i.ToString(), fontCode, Nothing, blackBrush, xDec, y, _
                 0, TextAlign.TopLeft)
                pdfPage.Canvas.DrawText("\x" + i.ToString("X"), fontCode, Nothing, blackBrush, xHex, y, _
                 0, TextAlign.TopLeft)
                pdfPage.Canvas.DrawText(c.ToString(), fontChar, Nothing, blackBrush, xChar, y, _
                 0, TextAlign.TopLeft)
                y = y + 12
                If i = 255 Then
                    Exit While
                End If
            End While
        End Sub
        Private Shared Sub DrawThirdPage(ByVal pdfDoc As PDFDocument)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()
            ' Create the graphic objects
            Dim fontChar As PDFFont = New PDFFont(FontFace.ZapfDingbats, 11)
            Dim fontText As PDFFont = New PDFFont(FontFace.Helvetica, 12)
            Dim fontCode As PDFFont = New PDFFont(FontFace.Helvetica, 11)
            Dim blackBrush As PDFBrush = New PDFBrush(New PDFColor)
            pdfPage.Canvas.DrawText("ZapfDingbats font", fontText, Nothing, blackBrush, 10, 30, _
             0, TextAlign.TopLeft)
            ' Draw the header for the first column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 10, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 70, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 100, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the second column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 170, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 230, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 260, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the third column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 330, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 390, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 420, 50, _
             0, TextAlign.TopLeft)
            ' Draw the header for the fourth column
            pdfPage.Canvas.DrawText("Decimal", fontText, Nothing, blackBrush, 490, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Hex", fontText, Nothing, blackBrush, 550, 50, _
             0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Char", fontText, Nothing, blackBrush, 580, 50, _
             0, TextAlign.TopLeft)
            ' Draw the codes and characters
            Dim xDec As Single = 10
            Dim xHex As Single = 70
            Dim xChar As Single = 100
            Dim xDelta As Single = 160
            Dim y As Single = 65
            Dim i As Byte = 31
            While i <= 255
                i += 1
                If ((i - 32) Mod 60 = 0) AndAlso i <> 32 Then
                    xDec = xDec + xDelta
                    xHex = xHex + xDelta
                    xChar = xChar + xDelta
                    y = 65
                End If
                Dim c As Char = Microsoft.VisualBasic.ChrW(i)
                pdfPage.Canvas.DrawText(i.ToString(), fontCode, Nothing, blackBrush, xDec, y, _
                 0, TextAlign.TopLeft)
                pdfPage.Canvas.DrawText("\x" + i.ToString("X"), fontCode, Nothing, blackBrush, xHex, y, _
                 0, TextAlign.TopLeft)
                pdfPage.Canvas.DrawText(c.ToString(), fontChar, Nothing, blackBrush, xChar, y, _
                 0, TextAlign.TopLeft)
                y = y + 12
                If i = 255 Then
                    Exit While
                End If
            End While
        End Sub
    End Class
End Namespace


Samples: ColorSpaces

Samples

ColorSpaces

This sample shows how to work with various PDF colorspaces. New color classes have been introduced to allow creation of colors based on specific colorspaces. The new colors can be used instead of existing PDFColor objects.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


ColorSpaces.cs

using System;
using System.IO;
using System.Text;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Functions;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Graphics.ColorSpaces;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to work with various PDF colorspaces when creating a PDF document.
    /// </summary>
    class ColorSpaces
    {
        [STAThread]
        static void Main(string[] args)
        {
            PDFDocument doc = new PDFDocument();

            PDFPage page = doc.AddPage();
            DrawDeviceColorSpace(page);

            page = doc.AddPage();
            DrawIndexedColorSpace(page);

            page = doc.AddPage();
            DrawCalGrayColorSpace(page);

            page = doc.AddPage();
            DrawCalRgbColorSpace(page);

            page = doc.AddPage();
            DrawLabColorSpace(page);

            page = doc.AddPage();
            DrawICCColorSpace(page);

            page = doc.AddPage();
            DrawSeparationColorSpace(page);

            doc.Save("colorspaces.pdf");
            doc.Dispose();
        }

        /// <summary>
        /// Draws content on a page using colors created from a device colorspace.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        /// <remarks>RGB, CMYK and Gray are device colorspaces.
        /// The PDFRgbColor, PDFCmykColor and PDFGrayColor classes create automatically the
        /// required colorspaces.</remarks>
        private static void DrawDeviceColorSpace(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("Device colorspaces: RGB, CMYK and Gray", font, null, blackBrush, 50, 50);

            // Draw RGB content.
            page.Canvas.DrawText("RGB", font, null, blackBrush, 50, 80);
            PDFRgbColor red = new PDFRgbColor(255, 0, 0);
            PDFRgbColor blue = new PDFRgbColor(0, 0, 255);
            PDFBrush redBrush = new PDFBrush(red);
            PDFPen bluePen = new PDFPen(blue, 5);
            page.Canvas.DrawRoundRectangle(bluePen, redBrush, 50, 100, 400, 150, 20, 20);

            // Draw CMYK content.
            page.Canvas.DrawText("CMYK", font, null, blackBrush, 50, 280);
            PDFCmykColor cyan = new PDFCmykColor(1, 0, 0, 0);
            PDFCmykColor magenta = new PDFCmykColor(0, 1, 0, 0);
            PDFBrush cyanBrush = new PDFBrush(cyan);
            PDFPen magentaPen = new PDFPen(magenta, 5);
            page.Canvas.DrawRoundRectangle(magentaPen, cyanBrush, 50, 300, 400, 150, 20, 20);

            // Draw Gray content.
            page.Canvas.DrawText("Gray", font, null, blackBrush, 50, 480);
            PDFGrayColor lightGray = new PDFGrayColor(0.85);
            PDFGrayColor darkGray = new PDFGrayColor(0.1);
            PDFBrush lgBrush = new PDFBrush(lightGray);
            PDFPen dgPen = new PDFPen(darkGray, 5);
            page.Canvas.DrawRoundRectangle(dgPen, lgBrush, 50, 500, 400, 150, 20, 20);
        }

        /// <summary>
        /// Draws content on a page using colors created from an indexed colorspace.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        private static void DrawIndexedColorSpace(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("Indexed colorspace with 2 colors", font, null, blackBrush, 50, 50);

            // Create an indexed colorspace with 2 RGB colors, 24bits (3*8bytes) per color.
            PDFIndexedColorSpace ixCS = new PDFIndexedColorSpace();
            ixCS.MaxIndex = 1;
            ixCS.ColorTable = new byte[] { 255, 0, 0, 192, 0, 255 };
            PDFIndexedColor red = new PDFIndexedColor(ixCS);
            red.ColorIndex = 0;
            PDFIndexedColor violet = new PDFIndexedColor(ixCS);
            violet.ColorIndex = 1;
            PDFBrush redBrush = new PDFBrush(red);
            PDFPen violetPen = new PDFPen(violet, 5);
            page.Canvas.DrawRoundRectangle(violetPen, redBrush, 50, 100, 400, 150, 20, 20);
        }

        /// <summary>
        /// Draws content on a page using colors created from a calibrated gray colorspace.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        private static void DrawCalGrayColorSpace(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("CalGray colorspace", font, null, blackBrush, 50, 50);

            PDFCalGrayColorSpace calGrayCS = new PDFCalGrayColorSpace();
            PDFCalGrayColor dkGray = new PDFCalGrayColor(calGrayCS);
            dkGray.Gray = 0.1;
            PDFCalGrayColor ltGray = new PDFCalGrayColor(calGrayCS);
            ltGray.Gray = 0.8;
            PDFBrush dkBrush = new PDFBrush(dkGray);
            PDFPen ltPen = new PDFPen(ltGray, 5);
            page.Canvas.DrawRoundRectangle(ltPen, dkBrush, 50, 100, 400, 150, 20, 20);
        }

        /// <summary>
        /// Draws content on a page using colors created from a calibrated RGB colorspace.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        private static void DrawCalRgbColorSpace(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("CalRGB colorspace", font, null, blackBrush, 50, 50);

            PDFCalRgbColorSpace calRgbCS = new PDFCalRgbColorSpace();
            PDFCalRgbColor red = new PDFCalRgbColor(calRgbCS);
            red.Red = 1;
            red.Green = 0;
            red.Blue = 0;
            PDFCalRgbColor blue = new PDFCalRgbColor(calRgbCS);
            blue.Red = 0;
            blue.Green = 0;
            blue.Blue = 1;
            PDFBrush blueBrush = new PDFBrush(blue);
            PDFPen redPen = new PDFPen(red, 5);
            page.Canvas.DrawRoundRectangle(redPen, blueBrush, 50, 100, 400, 150, 20, 20);
        }

        /// <summary>
        /// Draws content on a page using colors created from a calibrated Lab colorspace.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        private static void DrawLabColorSpace(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("L*a*b* colorspace", font, null, blackBrush, 50, 50);

            PDFLabColorSpace labCS = new PDFLabColorSpace();
            PDFLabColor labClr1 = new PDFLabColor(labCS);
            labClr1.L = 90;
            labClr1.A = 20;
            labClr1.B = -10;
            PDFLabColor labClr2 = new PDFLabColor(labCS);
            labClr2.L = 10;
            labClr2.A = 70;
            labClr2.B = -50;
            PDFBrush brush = new PDFBrush(labClr1);
            PDFPen pen = new PDFPen(labClr2, 5);
            page.Canvas.DrawRoundRectangle(pen, brush, 50, 100, 400, 150, 20, 20);
        }

        /// <summary>
        /// Draws content on a page using colors created from a calibrated ICC colorspace.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        private static void DrawICCColorSpace(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("ICC colorspace", font, null, blackBrush, 50, 50);

            // Read the ICC profile from disk.
            FileStream fs = new FileStream("rgb.icc", FileMode.Open, FileAccess.Read);
            byte[] profileData = new byte[fs.Length];
            fs.Read(profileData, 0, profileData.Length);
            fs.Close();

            PDFICCColorSpace iccCS = new PDFICCColorSpace();
            iccCS.ProfileData = profileData;
            PDFICCColor red = new PDFICCColor(iccCS);
            red.ColorComponents = new double[] { 192, 0, 0 };
            PDFICCColor blue = new PDFICCColor(iccCS);
            blue.ColorComponents = new double[] { 0, 0, 192 };
            PDFBrush blueBrush = new PDFBrush(blue);
            PDFPen redPen = new PDFPen(red, 5);
            page.Canvas.DrawRoundRectangle(redPen, blueBrush, 50, 100, 400, 150, 20, 20);
        }

        /// <summary>
        /// Draws content on a page using colors created from a separation colorspace.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        private static void DrawSeparationColorSpace(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("Separation colorspace", font, null, blackBrush, 50, 50);

            PDFType2Function tintTransform = new PDFType2Function();
            tintTransform.C1 = new float[] { 0, 0.53f, 1, 0 };
            PDFSeparationColorSpace separationCS = new PDFSeparationColorSpace();
            separationCS.Colorant = "PANTONE Orange 021 C";
            separationCS.TintTransform = tintTransform;
            PDFSeparationColor orange = new PDFSeparationColor(separationCS);
            orange.Tint = 0.9;

            tintTransform = new PDFType2Function();
            tintTransform.C1 = new float[] { 0, 0.75f, 0.9f, 0 };
            separationCS = new PDFSeparationColorSpace();
            separationCS.Colorant = "PANTONE Warm Red C";
            separationCS.TintTransform = tintTransform;
            PDFSeparationColor warmRed = new PDFSeparationColor(separationCS);
            warmRed.Tint = 0.4;

            PDFBrush orangeBrush = new PDFBrush(orange);
            PDFPen warmRedPen = new PDFPen(warmRed, 5);
            page.Canvas.DrawRoundRectangle(warmRedPen, orangeBrush, 50, 100, 400, 150, 20, 20);
        }
    }
}


ColorSpaces.vb

Imports System
Imports System.IO
Imports System.Text
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Functions
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Graphics.ColorSpaces

Namespace O2S.Samples.PDF4NET
    '/ <summary>
    '/ This sample shows how to work with various PDF colorspaces when creating a PDF document.
    '/ </summary>
    Class ColorSpaces
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            Dim doc As PDFDocument = New PDFDocument()

            Dim page As PDFPage = doc.AddPage()
            DrawDeviceColorSpace(page)

            page = doc.AddPage()
            DrawIndexedColorSpace(page)

            page = doc.AddPage()
            DrawCalGrayColorSpace(page)

            page = doc.AddPage()
            DrawCalRgbColorSpace(page)

            page = doc.AddPage()
            DrawLabColorSpace(page)

            page = doc.AddPage()
            DrawICCColorSpace(page)

            page = doc.AddPage()
            DrawSeparationColorSpace(page)

            doc.Save("colorspaces.pdf")
            doc.Dispose()
        End Sub

        '/ <summary>
        '/ Draws content on a page using colors created from a device colorspace.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        '/ <remarks>RGB, CMYK and Gray are device colorspaces.
        '/ The PDFRgbColor, PDFCmykColor and PDFGrayColor classes create automatically the
        '/ required colorspaces.</remarks>
        Private Shared Sub DrawDeviceColorSpace(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("Device colorspaces: RGB, CMYK and Gray", font, Nothing, blackBrush, 50, 50)

            ' Draw RGB content.
            page.Canvas.DrawText("RGB", font, Nothing, blackBrush, 50, 80)
            Dim red As PDFRgbColor = New PDFRgbColor(255, 0, 0)
            Dim blue As PDFRgbColor = New PDFRgbColor(0, 0, 255)
            Dim redBrush As PDFBrush = New PDFBrush(red)
            Dim bluePen As PDFPen = New PDFPen(blue, 5)
            page.Canvas.DrawRoundRectangle(bluePen, redBrush, 50, 100, 400, 150, 20, 20)

            ' Draw CMYK content.
            page.Canvas.DrawText("CMYK", font, Nothing, blackBrush, 50, 280)
            Dim cyan As PDFCmykColor = New PDFCmykColor(1, 0, 0, 0)
            Dim magenta As PDFCmykColor = New PDFCmykColor(0, 1, 0, 0)
            Dim cyanBrush As PDFBrush = New PDFBrush(cyan)
            Dim magentaPen As PDFPen = New PDFPen(magenta, 5)
            page.Canvas.DrawRoundRectangle(magentaPen, cyanBrush, 50, 300, 400, 150, 20, 20)

            ' Draw Gray content.
            page.Canvas.DrawText("Gray", font, Nothing, blackBrush, 50, 480)
            Dim lightGray As PDFGrayColor = New PDFGrayColor(0.85)
            Dim darkGray As PDFGrayColor = New PDFGrayColor(0.1)
            Dim lgBrush As PDFBrush = New PDFBrush(lightGray)
            Dim dgPen As PDFPen = New PDFPen(darkGray, 5)
            page.Canvas.DrawRoundRectangle(dgPen, lgBrush, 50, 500, 400, 150, 20, 20)
        End Sub

        '/ <summary>
        '/ Draws content on a page using colors created from an indexed colorspace.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        Private Shared Sub DrawIndexedColorSpace(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("Indexed colorspace with 2 colors", font, Nothing, blackBrush, 50, 50)

            ' Create an indexed colorspace with 2 RGB colors, 24bits (3*8bytes) per color.
            Dim ixCS As PDFIndexedColorSpace = New PDFIndexedColorSpace()
            ixCS.MaxIndex = 1
            Dim colors As Byte() = {255, 0, 0, 192, 0, 255}
            ixCS.ColorTable = colors

            Dim red As PDFIndexedColor = New PDFIndexedColor(ixCS)
            red.ColorIndex = 0
            Dim violet As PDFIndexedColor = New PDFIndexedColor(ixCS)
            violet.ColorIndex = 1
            Dim redBrush As PDFBrush = New PDFBrush(red)
            Dim violetPen As PDFPen = New PDFPen(violet, 5)
            page.Canvas.DrawRoundRectangle(violetPen, redBrush, 50, 100, 400, 150, 20, 20)
        End Sub

        '/ <summary>
        '/ Draws content on a page using colors created from a calibrated gray colorspace.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        Private Shared Sub DrawCalGrayColorSpace(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("CalGray colorspace", font, Nothing, blackBrush, 50, 50)

            Dim calGrayCS As PDFCalGrayColorSpace = New PDFCalGrayColorSpace()
            Dim dkGray As PDFCalGrayColor = New PDFCalGrayColor(calGrayCS)
            dkGray.Gray = 0.1
            Dim ltGray As PDFCalGrayColor = New PDFCalGrayColor(calGrayCS)
            ltGray.Gray = 0.8
            Dim dkBrush As PDFBrush = New PDFBrush(dkGray)
            Dim ltPen As PDFPen = New PDFPen(ltGray, 5)
            page.Canvas.DrawRoundRectangle(ltPen, dkBrush, 50, 100, 400, 150, 20, 20)
        End Sub

        '/ <summary>
        '/ Draws content on a page using colors created from a calibrated RGB colorspace.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        Private Shared Sub DrawCalRgbColorSpace(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("CalRGB colorspace", font, Nothing, blackBrush, 50, 50)

            Dim calRgbCS As PDFCalRgbColorSpace = New PDFCalRgbColorSpace()
            Dim red As PDFCalRgbColor = New PDFCalRgbColor(calRgbCS)
            red.Red = 1
            red.Green = 0
            red.Blue = 0
            Dim blue As PDFCalRgbColor = New PDFCalRgbColor(calRgbCS)
            blue.Red = 0
            blue.Green = 0
            blue.Blue = 1
            Dim blueBrush As PDFBrush = New PDFBrush(blue)
            Dim redPen As PDFPen = New PDFPen(red, 5)
            page.Canvas.DrawRoundRectangle(redPen, blueBrush, 50, 100, 400, 150, 20, 20)
        End Sub

        '/ <summary>
        '/ Draws content on a page using colors created from a calibrated Lab colorspace.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        Private Shared Sub DrawLabColorSpace(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("L*a*b* colorspace", font, Nothing, blackBrush, 50, 50)

            Dim labCS As PDFLabColorSpace = New PDFLabColorSpace()
            Dim labClr1 As PDFLabColor = New PDFLabColor(labCS)
            labClr1.L = 90
            labClr1.A = 20
            labClr1.B = -10
            Dim labClr2 As PDFLabColor = New PDFLabColor(labCS)
            labClr2.L = 10
            labClr2.A = 70
            labClr2.B = -50
            Dim brush As PDFBrush = New PDFBrush(labClr1)
            Dim pen As PDFPen = New PDFPen(labClr2, 5)
            page.Canvas.DrawRoundRectangle(pen, brush, 50, 100, 400, 150, 20, 20)
        End Sub

        '/ <summary>
        '/ Draws content on a page using colors created from a calibrated ICC colorspace.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        Private Shared Sub DrawICCColorSpace(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("ICC colorspace", font, Nothing, blackBrush, 50, 50)

            ' Read the ICC profile from disk.
            Dim fs As FileStream = New FileStream("rgb.icc", FileMode.Open, FileAccess.Read)
            Dim profileData() As Byte = New Byte(fs.Length) {}
            fs.Read(profileData, 0, profileData.Length)
            fs.Close()

            Dim iccCS As PDFICCColorSpace = New PDFICCColorSpace()
            iccCS.ProfileData = profileData
            Dim red As PDFICCColor = New PDFICCColor(iccCS)
            Dim redColorComponents As Double() = {192, 0, 0 }
            red.ColorComponents = redColorComponents

            Dim blue As PDFICCColor = New PDFICCColor(iccCS)
            Dim blueColorComponents As Double() = {0, 0, 192}
            blue.ColorComponents = blueColorComponents

            Dim blueBrush As PDFBrush = New PDFBrush(blue)
            Dim redPen As PDFPen = New PDFPen(red, 5)
            page.Canvas.DrawRoundRectangle(redPen, blueBrush, 50, 100, 400, 150, 20, 20)
        End Sub

        '/ <summary>
        '/ Draws content on a page using colors created from a separation colorspace.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        Private Shared Sub DrawSeparationColorSpace(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("Separation colorspace", font, Nothing, blackBrush, 50, 50)

            Dim tintTransform As PDFType2Function = New PDFType2Function()
            Dim c1_1 As Single() = {0, 0.53F, 1, 0}
            tintTransform.C1 = c1_1

            Dim separationCS As PDFSeparationColorSpace = New PDFSeparationColorSpace()
            separationCS.Colorant = "PANTONE Orange 021 C"
            separationCS.TintTransform = tintTransform
            Dim orange As PDFSeparationColor = New PDFSeparationColor(separationCS)
            orange.Tint = 0.9

            tintTransform = New PDFType2Function()
            Dim c1_2 As Single() = {0, 0.75F, 0.9F, 0}
            tintTransform.C1 = c1_2

            separationCS = New PDFSeparationColorSpace()
            separationCS.Colorant = "PANTONE Warm Red C"
            separationCS.TintTransform = tintTransform
            Dim warmRed As PDFSeparationColor = New PDFSeparationColor(separationCS)
            warmRed.Tint = 0.4

            Dim orangeBrush As PDFBrush = New PDFBrush(orange)
            Dim warmRedPen As PDFPen = New PDFPen(warmRed, 5)
            page.Canvas.DrawRoundRectangle(warmRedPen, orangeBrush, 50, 100, 400, 150, 20, 20)
        End Sub
    End Class
End Namespace


Samples: Digital Signature

Samples

Digital Signature

This sample shows how to add digital signatures, based on X.509 certificates, to PDF files.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


DigitalSignature.cs

using System;
using System.IO;
using System.Drawing;
using System.Security.Cryptography.X509Certificates;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Forms;
using O2S.Components.PDF4NET.Security;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to sign a PDF file using X.509 certificates.
    /// </summary>
    class DigitalSignature
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument();

            // Create a blank page
            PDFPage page = doc.AddPage();

            // Create the signature field.
            PDFSignatureField sign = new PDFSignatureField("Signature");
            sign.Appearance.Rectangle = new RectangleF(50, 100, 200, 40);
            // Create the digital signature.
            sign.Signature = new PDFDigitalSignature();
            // The certificate is loaded from disk, but it also can be loaded from a certificate store.
            sign.Signature.Certificate = new X509Certificate2("samplesign.pfx", "password");
            sign.Signature.Location = "Romania";
            sign.Signature.Reason = "For demo";
            sign.Signature.ContactInfo = "techsupport@o2sol.com";
            page.Fields.Add(sign);

            doc.Save("digitalsign.pdf", true);
        }
    }
}


DigitalSignature.vb

Imports System
Imports System.IO
Imports System.Drawing
Imports System.Security.Cryptography.X509Certificates
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Forms
Imports O2S.Components.PDF4NET.Security

'/ <summary>
'/ This sample shows how to sign a PDF file using X.509 certificates.
'/ </summary>

Class DigitalSignature

    '/ <summary>
    '/ The main entry point for the application.
    '/ </summary>
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument()

        '// Create a blank page
        Dim page As PDFPage = doc.AddPage()

        '// Create the signature field.
        Dim sign As PDFSignatureField = New PDFSignatureField("Signature")
        sign.Appearance.Rectangle = New RectangleF(50, 100, 200, 40)
        '// Create the digital signature.
        sign.Signature = New PDFDigitalSignature()
        '// The certificate is loaded from disk, but it also can be loaded from a certificate store.
        sign.Signature.Certificate = New X509Certificate2("samplesign.pfx", "password")
        sign.Signature.Location = "Romania"
        sign.Signature.Reason = "For demo"
        sign.Signature.ContactInfo = "techsupport@o2sol.com"
        page.Fields.Add(sign)

        doc.Save("digitalsign.pdf", True)

    End Sub 'Main
End Class 'DigitalSignature


Samples: DocAndViewer

Samples

DocAndViewer

This samples shows how to set the metadata information for a pdf document. Also, it demonstrates how to set the way the pdf document is open in the viewer. In this sample, when the pdf document is open in the viewer, the whole user interface of the viewer is hidden. This sample has been enhanced to show how to add custom properties to a document. To view the custom properties, in Adobe Acrobat (Reader) go to File > Document Properties > Document Metadata.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


DocAndViewer.cs

/// <fileName>
/// File name: DocAndViewer.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.DocAndViewer
{
    /// <summary>
    /// This sample will show how to set the document information
    /// and the way the viewer will behave when will open the document.
    /// It also shows how to create custom properties for the document.
    /// </summary>
    class DocAndViewer
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Set the document information
            pdfDoc.DocumentInformation.Author = "O2 Solutions (http://www.o2sol.com)";
            pdfDoc.DocumentInformation.Title = "Sample document";
            pdfDoc.DocumentInformation.Subject = "The abilities of the PDF4NET library";
            pdfDoc.DocumentInformation.Keywords = "pdf4net, pdf, .net, sample";
            pdfDoc.DocumentInformation.Creator = "DocAndViewer";

            // Set viewer preferences
            // Change HideMenubar to false in order to
            // access the Preferences menu item.
            pdfDoc.ViewerPreferences.HideMenubar = false;
            pdfDoc.ViewerPreferences.HideToolbar = true;
            pdfDoc.ViewerPreferences.HideWindowUI = true;
            pdfDoc.ViewerPreferences.DisplayDocTitle = true;

            // Set up custom properties
            PDFMetadataSchema ms = new PDFMetadataSchema( );
            ms["Company"] = "O2 Solutions";
            ms["Website"] = "http://www.o2sol.com/";
            ms["Product"] = "PDF4NET Library";

            // Add schema to document
            pdfDoc.MetadataSchemas.Add( ms );

            // Create one page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFFont fontTitle = new PDFFont( FontFace.Helvetica, 12 );
            fontTitle.Bold = true;
            PDFBrush brush = new PDFBrush( new PDFColor( ) );

            // Write on the page the current settings
            pdfPage.Canvas.DrawText( "Document information",
                fontTitle, null, brush, 20, 20, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Author: " + pdfDoc.DocumentInformation.Author,
                fontText, null, brush, 20, 35, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Title: " + pdfDoc.DocumentInformation.Title,
                fontText, null, brush, 20, 50, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Subject: " + pdfDoc.DocumentInformation.Subject,
                fontText, null, brush, 20, 65, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Keywords: " + pdfDoc.DocumentInformation.Keywords,
                fontText, null, brush, 20, 80, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Creator: " + pdfDoc.DocumentInformation.Creator,
                fontText, null, brush, 20, 95, 0, TextAlign.TopLeft );

            pdfPage.Canvas.DrawText( "Viewer preferences",
                fontTitle, null, brush, 20, 120, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "HideMenubar: " +
                pdfDoc.ViewerPreferences.HideMenubar.ToString( ),
                fontText, null, brush, 20, 135, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "HideToolbar: " +
                pdfDoc.ViewerPreferences.HideToolbar.ToString( ),
                fontText, null, brush, 20, 150, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "HideWindowUI: " +
                pdfDoc.ViewerPreferences.HideWindowUI.ToString( ),
                fontText, null, brush, 20, 165, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "DisplayDocTitle: " +
                pdfDoc.ViewerPreferences.DisplayDocTitle.ToString( ),
                fontText, null, brush, 20, 180, 0, TextAlign.TopLeft );

            // Save the document to disk
            pdfDoc.SaveToFile( "docandviewer.pdf" );
        }
    }
}


DocAndViewer.vb

'
' File name: DocAndViewer.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.DocAndViewer
    '/ <summary>
    '/ This sample will show how to set the document information
    '/ and the way the viewer will behave when will open the document.
    '/ It also shows how to create custom properties for the document.
    '/ </summary>
    Class DocAndViewer

        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Set the document information
            pdfDoc.DocumentInformation.Author = "O2 Solutions (http://www.o2sol.com)"
            pdfDoc.DocumentInformation.Title = "Sample document"
            pdfDoc.DocumentInformation.Subject = "The abilities of the PDF4NET library"
            pdfDoc.DocumentInformation.Keywords = "pdf4net, pdf, .net, sample"
            pdfDoc.DocumentInformation.Creator = "DocAndViewer"

            ' Set viewer preferences
            ' Change HideMenubar to false in order to
            ' access the Preferences menu item.
            pdfDoc.ViewerPreferences.HideMenubar = False
            pdfDoc.ViewerPreferences.HideToolbar = True
            pdfDoc.ViewerPreferences.HideWindowUI = True
            pdfDoc.ViewerPreferences.DisplayDocTitle = True

            ' Set up custom properties
            Dim ms As New PDFMetadataSchema()
            ms("Company") = "O2 Solutions"
            ms("Website") = "http://www.o2sol.com/"
            ms("Product") = "PDF4NET Library"

            ' Add schema to document
            pdfDoc.MetadataSchemas.Add(ms)

            ' Create one page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim fontTitle As New PDFFont(FontFace.Helvetica, 12)
            fontTitle.Bold = True
            Dim brush As New PDFBrush(New PDFColor())

            ' Write on the page the current settings
            pdfPage.Canvas.DrawText("Document information", fontTitle, Nothing, brush, 20, 20)
            pdfPage.Canvas.DrawText("Author: " + pdfDoc.DocumentInformation.Author, fontText, Nothing, brush, 20, 35)
            pdfPage.Canvas.DrawText("Title: " + pdfDoc.DocumentInformation.Title, fontText, Nothing, brush, 20, 50)
            pdfPage.Canvas.DrawText("Subject: " + pdfDoc.DocumentInformation.Subject, fontText, Nothing, brush, 20, 65)
            pdfPage.Canvas.DrawText("Keywords: " + pdfDoc.DocumentInformation.Keywords, fontText, Nothing, brush, 20, 80)
            pdfPage.Canvas.DrawText("Creator: " + pdfDoc.DocumentInformation.Creator, fontText, Nothing, brush, 20, 95)

            pdfPage.Canvas.DrawText("Viewer preferences", fontTitle, Nothing, brush, 20, 120)
            pdfPage.Canvas.DrawText("HideMenubar: " + pdfDoc.ViewerPreferences.HideMenubar.ToString(), fontText, Nothing, brush, 20, 135)
            pdfPage.Canvas.DrawText("HideToolbar: " + pdfDoc.ViewerPreferences.HideToolbar.ToString(), fontText, Nothing, brush, 20, 150)
            pdfPage.Canvas.DrawText("HideWindowUI: " + pdfDoc.ViewerPreferences.HideWindowUI.ToString(), fontText, Nothing, brush, 20, 165)
            pdfPage.Canvas.DrawText("DisplayDocTitle: " + pdfDoc.ViewerPreferences.DisplayDocTitle.ToString(), fontText, Nothing, brush, 20, 180)

            ' Save the document to disk
            pdfDoc.SaveToFile("docandviewer.pdf")
        End Sub 'Main
    End Class 'DocAndViewer
End Namespace 'O2S.Samples.PDF4NET.DocAndViewer


Samples: Edit PDF

Samples

Edit PDF

This sample shows the pdf editing capabilities of PDF4NET library. The following features are shown: mixing 2 different documents, merge files, apply security to existing files, page imposition and pdf file splitting.

C# Source code | VB.NET Source code

© 2003 - 2007 O2 Solutions. All rights reserved.


EditPDF.cs

/// <fileName>
/// File name: EditPDF.cs
/// </fileName>

using System;
using System.Drawing;
using System.Text;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Security;
using O2S.Components.PDF4NET.PDFFile;

namespace O2S.Samples.PDF4NET.EditPDF
{
    /// <summary>
    /// This sample shows the pdf editing capabilities of
    /// PDF4NET library. The following features are shown:
    /// Mixing 2 different documents, merge files,
    /// encryption of existing files,
    /// page imposition and pdf file splitting.
    /// </summary>
    class EditPDF
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Documents mix
            MixFiles( );

            // Apppend files
            AppendFiles( );

            // Encrypt file
            EncryptFile( );

            // Split file
            SplitFile( );

            // Page imposition
            MultiPage( );
        }

        // For this sample to work, the following files
        // need to exist: unicode.pdf and multicolumntextandimages.pdf.
        // Compile the corresponding samples to get these files
        public static void MixFiles( )
        {
            PDFFile unicodeFile = PDFFile.FromFile( "unicode.pdf" );
            PDFFile mctiFile = PDFFile.FromFile( "multicolumntextandimages.pdf" );
            PDFImportedPage ip = null;

            PDFDocument doc = new PDFDocument( );
            for( int i = 0; i < 4; i++ )
            {
                // extract the page
                ip = unicodeFile.ExtractPage( i );

                // add the page to new document
                doc.AddPage( ip );

                // extract the page
                ip = mctiFile.ExtractPage( i );

                // add the page to new document
                doc.AddPage( ip );
            }

            // save the mixed document
            doc.SaveToFile( "mix.pdf" );

            unicodeFile.Close( );
            mctiFile.Close( );
        }

        // For this sample to work, the following files
        // need to exist: unicode.pdf and multicolumntextandimages.pdf.
        // Compile the corresponding samples to get these files
        public static void AppendFiles( )
        {
            PDFFile.MergeFiles( "append.pdf", new string[]{ "unicode.pdf", "multicolumntextandimages.pdf" } );

            // or
            //PDFDocument doc =
            //    PDFFile.MergeFiles( new string[]{ "unicode.pdf", "multicolumntextandimages.pdf" } );
            //doc.SaveToStream( stream );
        }

        // For this sample to work, the following file
        // need to exist: multicolumntextandimages.pdf.
        // Compile the corresponding sample to get this file
        public static void EncryptFile( )
        {
            PDFSecurityManager securityManager = new PDFSecurityManager( );
            securityManager = securityManager;
            securityManager.KeySize = EncryptionKeySize.Use128BitKey;
            securityManager.UserPassword = Encoding.ASCII.GetBytes( "userpass" );
            securityManager.OwnerPassword = Encoding.ASCII.GetBytes( "ownerpass" );
            securityManager.AllowPrint = false;
            securityManager.FullQualityPrint = true;
            securityManager.AllowModifyDocument = false;
            securityManager.AllowExtractContent = false;
            securityManager.AllowInteractiveEdit = false;
            securityManager.AllowFormsFill = true;
            securityManager.AllowAccessibilityExtractContent = true;
            securityManager.AllowAssembleDocument = false;

            PDFFile.EncryptFile( securityManager,
                "multicolumntextandimages.pdf", "multicolumntextandimages-secure.pdf" );

            // or
            //PDFDocument doc =
            //    PDFFile.EncryptFile( securityManager, "multicolumntextandimages-secure.pdf" );
            //doc.SaveToStream( stream );
        }

        // For this sample to work, the following file
        // need to exist: unicode.pdf.
        // Compile the corresponding sample to get this file
        public static void SplitFile( )
        {
            PDFFile.SplitFile( "unicode.pdf", "unicode-page.pdf" );
        }

        // For this sample to work, the following file
        // needs to exist: multicolumntextandimages.pdf.
        // Compile the corresponding sample to get this file
        public static void MultiPage( )
        {
            PDFFile mctiFile = PDFFile.FromFile( "multicolumntextandimages-secure.pdf", Encoding.ASCII.GetBytes( "userpass" ) );
            // extract the content of first 4 pages
            PDFImportedContent[] ic = mctiFile.ExtractPagesContent( "0-3" );

            // create the new document
            PDFDocument doc = new PDFDocument( );
            // add a page to it
            PDFPage page = doc.AddPage( );

            // draw the imported content (4 pages) on the new page
            page.Canvas.DrawImportedContent( ic[0], 0, 0, page.Width/2, page.Height/2 );
            page.Canvas.DrawImportedContent( ic[1], page.Width/2, 0, page.Width/2, page.Height/2 );
            page.Canvas.DrawImportedContent( ic[2], 0, page.Height/2, page.Width/2, page.Height/2 );
            page.Canvas.DrawImportedContent( ic[3], page.Width/2, page.Height/2, page.Width/2, page.Height/2 );

            // save the mixed document
            doc.SaveToFile( "imposition.pdf" );

            mctiFile.Close( );
        }
    }
}


EditPDF.vb

'
' File name: EditPDF.vb
'

Imports System
Imports System.Drawing
Imports System.Text
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Security
Imports O2S.Components.PDF4NET.PDFFile
Imports PDFFileEx = O2S.Components.PDF4NET.PDFFile.PDFFile

'/ <summary>
'/ This sample shows the pdf editing capabilities of
'/ PDF4NET library. The following features are shown:
'/ Mixing 2 different documents, merge files,
'/ encryption of existing files,
'/ page imposition and pdf file splitting.
'/ </summary>

Class EditPDF

    '/ <summary>
    '/ The main entry point for the application.
    '/ </summary>
    <STAThread()>  _
    Shared Sub Main(ByVal args() As String)
        ' Documents mix
        MixFiles()

        ' Apppend files
        AppendFiles()

        ' Encrypt file
        EncryptFile()

        ' Split file
        SplitFile()

        ' Page imposition
        MultiPage()

    End Sub 'Main

    ' For this sample to work, the following files
    ' need to exist: unicode.pdf and multicolumntextandimages.pdf.
    ' Compile the corresponding samples to get these files
    Public Shared Sub MixFiles()
        Dim unicodeFile As PDFFileEx = PDFFileEx.FromFile("unicode.pdf")
        Dim mctiFile As PDFFileEx = PDFFileEx.FromFile("multicolumntextandimages.pdf")
        Dim ip As PDFImportedPage = Nothing

        Dim doc As New PDFDocument
        Dim i As Integer
        For i = 0 To 3
            ' extract the page
            ip = unicodeFile.ExtractPage(i)

            ' add the page to new document
            doc.AddPage(ip)

            ' extract the page
            ip = mctiFile.ExtractPage(i)

            ' add the page to new document
            doc.AddPage(ip)
        Next i

        ' save the mixed document
        doc.SaveToFile("mix.pdf")

        unicodeFile.Close()
        mctiFile.Close()

    End Sub 'MixFiles

    ' For this sample to work, the following files
    ' need to exist: unicode.pdf and multicolumntextandimages.pdf.
    ' Compile the corresponding samples to get these files
    Public Shared Sub AppendFiles()
        PDFFileEx.MergeFiles("append.pdf", New String() {"unicode.pdf", "multicolumntextandimages.pdf"})

    End Sub 'AppendFiles

    ' or
    'PDFDocument doc =
    '    PDFFileEx.MergeFilesToDoc( "append.pdf", "unicode.pdf", "multicolumntextandimages.pdf" );
    'doc.SaveToStream( stream );

    ' For this sample to work, the following file
    ' need to exist: unicode.pdf.
    ' Compile the corresponding sample to get this file
    Public Shared Sub EncryptFile()
        Dim securityManager As New PDFSecurityManager
        securityManager = securityManager
        securityManager.KeySize = EncryptionKeySize.Use128BitKey
        securityManager.UserPassword = Encoding.ASCII.GetBytes("userpass")
        securityManager.OwnerPassword = Encoding.ASCII.GetBytes("ownerpass")
        securityManager.AllowPrint = False
        securityManager.FullQualityPrint = True
        securityManager.AllowModifyDocument = False
        securityManager.AllowExtractContent = False
        securityManager.AllowInteractiveEdit = False
        securityManager.AllowFormsFill = True
        securityManager.AllowAccessibilityExtractContent = True
        securityManager.AllowAssembleDocument = False

        PDFFileEx.EncryptFile(securityManager, "unicode.pdf", "unicode_secure.pdf")

    End Sub 'EncryptFile

    ' or
    'PDFDocument doc =
    '    PDFFileEx.EncryptFile( securityManager, "unicode.pdf" );
    'doc.SaveToStream( stream );

    ' For this sample to work, the following file
    ' need to exist: unicode.pdf.
    ' Compile the corresponding sample to get this file
    Public Shared Sub SplitFile()
        PDFFileEx.SplitFile("unicode.pdf", "unicode-page.pdf")

    End Sub 'SplitFile

    ' For this sample to work, the following file
    ' needs to exist: multicolumntextandimages.pdf.
    ' Compile the corresponding sample to get this file
    Public Shared Sub MultiPage()
        Dim mctiFile As PDFFileEx = PDFFileEx.FromFile("multicolumntextandimages.pdf")
        ' extract the content of first 4 pages
        Dim ic As PDFImportedContent() = mctiFile.ExtractPagesContent("0-3")

        ' create the new document
        Dim doc As New PDFDocument
        ' add a page to it
        Dim page As PDFPage = doc.AddPage()

        ' draw the imported content (4 pages) on the new page
        page.Canvas.DrawImportedContent(ic(0), 0, 0, page.Width / 2, page.Height / 2)
        page.Canvas.DrawImportedContent(ic(1), page.Width / 2, 0, page.Width / 2, page.Height / 2)
        page.Canvas.DrawImportedContent(ic(2), 0, page.Height / 2, page.Width / 2, page.Height / 2)
        page.Canvas.DrawImportedContent(ic(3), page.Width / 2, page.Height / 2, page.Width / 2, page.Height / 2)

        ' save the mixed document
        doc.SaveToFile("imposition.pdf")

        mctiFile.Close()

    End Sub 'MultiPage
End Class 'EditPDF


Samples: Encryption

Samples

PDF security and encryption

This samples shows the pdf security features of PDF4NET library. It shows user and owner passwords, encryption strength and document access rights. The user user password for the attached document is 'userpass', and the owner password is 'ownerpass'.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Encryption.cs

/// <fileName>
/// File name: Encryption.cs
/// </fileName>

using System;
using System.Text;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Security;

namespace O2S.Samples.PDF4NET.Encryption
{
    /// <summary>
    /// This sample shows how to use the pdf
    /// security features of PDF4NET library
    /// </summary>
    class Encryption
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // set the security options
            pdfDoc.SecurityManager = new PDFSecurityManager( );
            // use 128 bit encryption
            pdfDoc.SecurityManager.KeySize = EncryptionKeySize.Use128BitKey;
            // set user password to "userpass"
            pdfDoc.SecurityManager.UserPassword = Encoding.ASCII.GetBytes( "userpass" );
            // set owner password to "ownerpass"
            pdfDoc.SecurityManager.OwnerPassword = Encoding.ASCII.GetBytes( "ownerpass" );
            // allow to print the pdf document
            pdfDoc.SecurityManager.AllowPrint = true;
            // do not allow high quality print
            pdfDoc.SecurityManager.FullQualityPrint = false;
            // do not alow to modify the document
            pdfDoc.SecurityManager.AllowModifyDocument = false;
            // do not allow to extract content (text and images) from the document
            pdfDoc.SecurityManager.AllowExtractContent = false;
            // do not allow to fill forms or to create annotations
            pdfDoc.SecurityManager.AllowInteractiveEdit = false;
            // do not allow forms fill
            pdfDoc.SecurityManager.AllowFormsFill = false;
            // allow to extract content in support for accessibility
            pdfDoc.SecurityManager.AllowAccessibilityExtractContent = true;
            // do not allow to assemble document
            pdfDoc.SecurityManager.AllowAssembleDocument = false;

            // Create one page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Draw "Encrypted Hello world" in the center of the page
            pdfPage.Canvas.DrawText( "Encrypted",
                new PDFFont( FontFace.Helvetica, 100 ), new PDFPen( new PDFColor( 255, 0, 0 ), 1 ),
                new PDFBrush( new PDFColor( 0, 0, 255 ) ), pdfPage.Width/2, pdfPage.Height/2 - 3,
                0, TextAlign.BottomCenter );
            pdfPage.Canvas.DrawText( "Hello world !",
                new PDFFont( FontFace.Helvetica, 100 ), new PDFPen( new PDFColor( 255, 0, 0 ), 1 ),
                new PDFBrush( new PDFColor( 0, 0, 255 ) ), pdfPage.Width/2, pdfPage.Height/2 + 3,
                0, TextAlign.TopCenter );

            // Save the document to disk
            pdfDoc.SaveToFile( "encryption.pdf" );
        }
    }
}


Encryption.vb

'
' File name: Encryption.vb
'

Imports System
Imports System.Text
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Security

Namespace O2S.Samples.PDF4NET.Encryption
   '/ <summary>
   '/ This sample shows how to use the pdf
   '/ security features of PDF4NET library
   '/ </summary>

   Class Encryption
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument

            ' set the security options
            pdfDoc.SecurityManager = New PDFSecurityManager
            ' use 128 bit encryption
            pdfDoc.SecurityManager.KeySize = EncryptionKeySize.Use128BitKey
            ' set user password to "userpass"
            pdfDoc.SecurityManager.UserPassword = Encoding.ASCII.GetBytes("userpass")
            ' set owner password to "ownerpass"
            pdfDoc.SecurityManager.OwnerPassword = Encoding.ASCII.GetBytes("ownerpass")
            ' allow to print the pdf document
            pdfDoc.SecurityManager.AllowPrint = True
            ' do not allow high quality print
            pdfDoc.SecurityManager.FullQualityPrint = False
            ' do not alow to modify the document
            pdfDoc.SecurityManager.AllowModifyDocument = False
            ' do not allow to extract content (text and images) from the document
            pdfDoc.SecurityManager.AllowExtractContent = False
            ' do not allow to fill forms or to create annotations
            pdfDoc.SecurityManager.AllowInteractiveEdit = False
            ' do not allow forms fill
            pdfDoc.SecurityManager.AllowFormsFill = False
            ' allow to extract content in support for accessibility
            pdfDoc.SecurityManager.AllowAccessibilityExtractContent = True
            ' do not allow to assemble document
            pdfDoc.SecurityManager.AllowAssembleDocument = False

            ' Create one page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Draw "Hello world" in the center of the page
            pdfPage.Canvas.DrawText("Encrypted Hello world !", New PDFFont(FontFace.Helvetica, 100), New PDFPen(New PDFColor(255, 0, 0), 1), New PDFBrush(New PDFColor(0, 0, 255)), pdfPage.Width / 2, pdfPage.Height / 2, 0, TextAlign.MiddleCenter)

            ' Save the document to disk
            pdfDoc.SaveToFile("encryption.pdf")
        End Sub 'Main
    End Class 'Encryption
End Namespace 'O2S.Samples.PDF4NET.Encryption


Samples: Ellipses

Samples

Ellipses

This samples shows the ellipse drawing capabilities of the PDF4NET library. On the first page, it draws an ellipse by painting its border, an ellipse by filling its interior, and an ellipse by painting its border and filling its interior. It also show how to draw a circle. On the second page it draws 50 ellipses at random locations on the page. The color of the ellipses is generated randomly.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Ellipses.cs

/// <fileName>
/// File name: Ellipses.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Ellipses
{
    /// <summary>
    /// This sample will show how to draw various ellipses
    /// on the page.
    /// </summary>
    class Ellipses
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create first page
            PDFPage pdfPage1 = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFBrush greenBrush = new PDFBrush( new PDFColor( 0, 255, 0 ) );
            PDFPen pen = new PDFPen( new PDFColor( Color.Orange ), 1 );

            // Draw an ellipse that has a border
            pdfPage1.Canvas.DrawText( "This ellipse is drawn by drawing its border",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawEllipse2( pen, null, 20, 35, 200, 100 );

            // Draw an ellipse that has no border and its interior is filled
            pdfPage1.Canvas.DrawText( "This ellipse is drawn by filling its interior",
                fontText, null, blackBrush, 300, 20, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawEllipse2( null, greenBrush, 300, 35, 300, 150 );

            // Draw an ellipse that has a border and its interior is filled
            pdfPage1.Canvas.DrawText( "This ellipse has a border and a filled interior",
                fontText, null, blackBrush, 20, 200, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawEllipse2( pen, greenBrush, 20, 215, 200, 150 );

            // Draw a circle
            pdfPage1.Canvas.DrawText( "This is a circle",
                fontText, null, blackBrush, 300, 200, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawEllipse2( pen, greenBrush, 300, 215, 200, 200 );

            // Create the second page
            PDFPage pdfPage2 = pdfDoc.AddPage( );

            Random rnd = new Random( );
            for( int i = 0; i < 50; i++ )
            {
                // Create random colors for the border and the interior
                PDFColor brushColor = new PDFColor( ( byte )rnd.Next( 256 ),
                    ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );
                PDFColor penColor = new PDFColor( ( byte )rnd.Next( 256 ),
                    ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );

                // Create the brush to fill the interior
                PDFBrush randomBrush = new PDFBrush( brushColor );
                // Create the pen to draw the border
                PDFPen randomPen = new PDFPen( penColor, 1 );

                // Generate random positions
                float left = rnd.Next( ( int )pdfPage2.Width );
                float top = rnd.Next( ( int )pdfPage2.Height );

                // Generate random sizes
                float width = rnd.Next( ( int )( pdfPage2.Width - left ) ); // try to keep the rectangle
                float height = rnd.Next( ( int )( pdfPage2.Height - top ) );   // within the page

                // Draw the ellipse
                pdfPage2.Canvas.DrawEllipse2( randomPen, randomBrush,
                    left, top, width, height );
            }

            // Draw a label
            pdfPage2.Canvas.DrawText( "Random ellipses",
                fontText, null, blackBrush, 20, 350, 0, TextAlign.TopLeft );

            // Save the document to disk
            pdfDoc.SaveToFile( "ellipses.pdf" );
        }
    }
}


Ellipses.vb

'
' File name: Ellipses.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.Ellipses
    '/ <summary>
    '/ This sample will show how to draw various ellipses
    '/ on the page.
    '/ </summary>
    Class Ellipses

        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create first page
            Dim pdfPage1 As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim greenBrush As New PDFBrush(New PDFColor(0, 255, 0))
            Dim pen As New PDFPen(New PDFColor(Color.Orange), 1)

            ' Draw an ellipse that has a border
            pdfPage1.Canvas.DrawText("This ellipse is drawn by drawing its border", fontText, Nothing, blackBrush, 20, 20)
            pdfPage1.Canvas.DrawEllipse(pen, 35, 20, 200, 100)

            ' Draw an ellipse that has no border and its interior is filled
            pdfPage1.Canvas.DrawText("This ellipse is drawn by filling its interior", fontText, Nothing, blackBrush, 300, 20)
            pdfPage1.Canvas.DrawEllipse(greenBrush, 35, 300, 300, 150)

            ' Draw an ellipse that has a border and its interior is filled
            pdfPage1.Canvas.DrawText("This ellipse has a border and a filled interior", fontText, Nothing, blackBrush, 20, 200)
            pdfPage1.Canvas.DrawEllipse(pen, greenBrush, 215, 20, 200, 150)

            ' Draw a circle
            pdfPage1.Canvas.DrawText("This is a circle", fontText, Nothing, blackBrush, 300, 200)
            pdfPage1.Canvas.DrawEllipse(pen, greenBrush, 215, 300, 200, 200)

            ' Create the second page
            Dim pdfPage2 As PDFPage = pdfDoc.AddPage()

            Dim rnd As New Random()
            Dim i As Integer
            For i = 0 To 49
                ' Create random colors for the border and the interior
                Dim brushColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))
                Dim penColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))

                ' Create the brush to fill the interior
                Dim randomBrush As New PDFBrush(brushColor)
                ' Create the pen to draw the border
                Dim randomPen As New PDFPen(penColor, 1)

                ' Generate random positions
                Dim left As Single = rnd.Next(CInt(pdfPage2.Width))
                Dim top As Single = rnd.Next(CInt(pdfPage2.Height))

                ' Generate random sizes
                Dim width As Single = rnd.Next(CInt(pdfPage2.Width - left)) ' try to keep the rectangle
                Dim height As Single = rnd.Next(CInt(pdfPage2.Height - top)) ' within the page
                ' Draw the ellipse
                pdfPage2.Canvas.DrawEllipse(randomPen, randomBrush, top, left, width, height)
            Next i

            ' Draw a label
            pdfPage2.Canvas.DrawText("Random ellipses", fontText, Nothing, blackBrush, 20, 350)

            ' Save the document to disk
            pdfDoc.SaveToFile("ellipses.pdf")
        End Sub 'Main
    End Class 'Ellipses
End Namespace 'O2S.Samples.PDF4NET.Ellipses


Samples: ExtractImages

Samples

ExtractImahes

This samples shows how to extract the images stored in a PDF file.

C# Source code | VB.NET Source code

© 2003 - 2007 O2 Solutions. All rights reserved.


ExtractImages.cs

using System;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.PDFFile;

namespace O2S.Samples.PDF4NET
{
    class ExtractImages
    {
        static void Main(string[] args)
        {
            if (!File.Exists("images.pdf"))
            {
                Console.WriteLine("File images.pdf does not exist. Compile and run the Images sample before running this sample.");
                return;
            }

            // Load the PDF file.
            PDFDocument doc = new PDFDocument("images.pdf");
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                // Convert the pages to PDFImportedPage to get access to GetImages method.
                PDFImportedPage ip = doc.Pages[i] as PDFImportedPage;
                Bitmap[] images = ip.GetImages();
                // Save the page images to disk, if there are any.
                for (int j = 0; j < images.Length; j++)
                {
                    images[j].Save("image" + i.ToString() + j.ToString() + ".png", ImageFormat.Png);
                }
            }
        }
    }
}


ExtractImages.vb

Imports System
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.PDFFile

Namespace O2S.Samples.PDF4NET
    '/ <summary>
    '/ This sample shows how to extract images from a PDF file.
    '/ </summary>
    Class ExtractImages

        Shared Sub Main()
            If Not File.Exists("images.pdf") Then
                Console.WriteLine("File images.pdf does not exist. Compile and run Images sample before running this sample.")
                Return
            End If
            ' Load the pdf document
            Dim pdfDoc As New PDFDocument("images.pdf")
            Dim i As Integer
            For i = 0 To pdfDoc.Pages.Count
                Dim ip As PDFImportedPage = pdfDoc.Pages(i)
                Dim images() As Bitmap = ip.GetImages()

                Dim j As Integer
                For j = 0 To images.Length
                    images(j).Save("image" + i.ToString() + j.ToString() + ".png", ImageFormat.Png)
                Next
            Next

        End Sub 'Main
    End Class 'ExtractImages
End Namespace 'O2S.Samples.PDF4NET


Samples: Forms

Samples

Forms

This section includes several samples related to PDF forms.

FormCreate - shows how to create a PDF form using PDF4NET library.

FormFieldsEnumerator - shows how to enumerate all the fields in a PDF form using PDF4NET library.

FormFill - shows how to fill a PDF form using PDF4NET library.

FormFillXFA - shows how to fill a XFA form using PDF4NET library.

© 2003 - 2007 O2 Solutions. All rights reserved.


Samples: FormCreate

Samples

Create Form

This samples shows how to create a PDF e-form using PDF4NET library. The sample creates all types of available fields. It also shows how to attach actions to button clicks and how to create a submit form button.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


FormCreate.cs

/// <fileName>
/// File name: FormCreate.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Actions;
using O2S.Components.PDF4NET.Forms;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This samples shows how to create a PDF e-form using PDF4NET library. The
    /// sample creates all types of available fields. It also shows how to attach
    /// actions to button clicks and how to create a submit form button.
    /// </summary>
    class FormCreate
    {

        [STAThread]
        static void Main(string[] args)
        {
            PDFDocument doc = new PDFDocument( );
            PDFPage page = doc.AddPage( );

            PDFColor blackColor = new PDFColor( 0, 0, 0 );

            // Create 4 textboxes.
            PDFTextBoxField tbx = new PDFTextBoxField( "TextBox1" );
            tbx.Appearance.Rectangle = new RectangleF( 50, 50, 200, 20 );
            tbx.Appearance.Border = new PDFFieldBorder( FieldBorderStyle.Solid, 1, blackColor );
            page.Fields.Add( tbx );

            tbx = new PDFTextBoxField( "TextBox3" );
            tbx.Appearance.Rectangle = new RectangleF( 300, 50, 200, 40 );
            tbx.Appearance.Border = new PDFFieldBorder( FieldBorderStyle.Solid, 1, blackColor );
            tbx.Text = "Sample field value";
            page.Fields.Add( tbx );

            // These 2 textboxes have no border.
            tbx = new PDFTextBoxField( "TextBox2" );
            tbx.Appearance.Rectangle = new RectangleF( 50, 100, 200, 20 );
            tbx.Text = "<Click here to fill your name>";
            tbx.Value = "";
            page.Fields.Add( tbx );

            tbx = new PDFTextBoxField( "TextBox4" );
            tbx.Appearance.Rectangle = new RectangleF( 300, 100, 200, 40 );
            page.Fields.Add( tbx );

            // Create a push button
            PDFPushbuttonField btn = new PDFPushbuttonField( "Pushbutton" );
            btn.Tooltip = "Button Tooltip";
            btn.NormalAppearance.Caption = "Push me";
            btn.NormalAppearance.Rectangle = new RectangleF( 50, 150, 200, 20 );
            btn.NormalAppearance.ForeColor = new PDFColor( 255, 0, 0 );
            btn.NormalAppearance.BackColor = new PDFColor( 0, 255, 0 );
            page.Fields.Add( btn );

            // Set an OnClick action for the button
            PDFJavaScriptAction js = new PDFJavaScriptAction( );
            js.Script = "var f = this.getField(\"TextBox1\");\r\nf.value = \"test\";";
            btn.Actions.MouseUp = js;

            // Create a submit form push button
            btn = new PDFPushbuttonField( "SubmitForm" );
            btn.Tooltip = "Submits the form fields";
            btn.NormalAppearance.Caption = "Submit form";
            btn.NormalAppearance.Rectangle = new RectangleF( 300, 150, 200, 20 );
            btn.NormalAppearance.ForeColor = new PDFColor( 255, 0, 0 );
            btn.NormalAppearance.BackColor = new PDFColor( 0, 255, 0 );
            page.Fields.Add( btn );

            // Set an OnClick action for the button
            PDFSubmitFormAction submitFormAction = new PDFSubmitFormAction( );
            submitFormAction.Url = "http://localhost/fieldsexplorer/fieldsviewer.aspx";
            submitFormAction.DataFormat = SubmitDataFormat.HTML;
            btn.Actions.MouseUp = submitFormAction;

            // Create a checkbox
            PDFCheckBoxField checkBox = new PDFCheckBoxField( "CheckBox" );
            checkBox.ExportValue = "1";
            checkBox.Checked = true;
            checkBox.Style = SymbolStyle.Check;
            checkBox.CheckedNormalAppearance.Rectangle = new RectangleF( 50, 200, 20, 20 );
            checkBox.CheckedNormalAppearance.ForeColor = new PDFColor( 0, 0, 0 );
            checkBox.CheckedNormalAppearance.BackColor = new PDFColor( 255, 255, 255 );
            page.Fields.Add( checkBox );

            // Create a radiobutton list
            PDFRadioButtonListField rbl = new PDFRadioButtonListField( "RadioButtonList" );
            rbl.Style = SymbolStyle.Diamond;
            PDFRadioButtonItem rbi = new PDFRadioButtonItem( );
            rbi.Value = "1";
            rbi.CheckedNormalAppearance.Rectangle = new RectangleF( 50, 250, 20, 20 );
            rbi.CheckedNormalAppearance.ForeColor = new PDFColor( 255, 255, 255 );
            rbi.CheckedNormalAppearance.BackColor = new PDFColor( 0, 0, 0 );
            rbl.Items.Add( rbi );
            PDFRadioButtonItem rbi2 = new PDFRadioButtonItem( );
            rbi2.Value = "2";
            rbi2.CheckedNormalAppearance.Rectangle = new RectangleF( 50, 300, 20, 20 );
            rbi2.CheckedNormalAppearance.ForeColor = new PDFColor( 255, 255, 255 );
            rbi2.CheckedNormalAppearance.BackColor = new PDFColor( 0, 0, 0 );
            rbl.Items.Add( rbi2 );
            PDFRadioButtonItem rbi3 = new PDFRadioButtonItem( );
            rbi3.Value = "3";
            rbi3.CheckedNormalAppearance.Rectangle = new RectangleF( 50, 350, 20, 20 );
            rbi3.CheckedNormalAppearance.ForeColor = new PDFColor( 255, 255, 255 );
            rbi3.CheckedNormalAppearance.BackColor = new PDFColor( 0, 0, 0 );
            rbl.Items.Add( rbi3 );
            rbl.SelectedValue = "3";
            page.Fields.Add( rbl );

            // Create a drop down list
            PDFDropDownListField ddl = new PDFDropDownListField( "DropDownList" );
            PDFListItem li = new PDFListItem( "Item 1", "1" );
            ddl.Items.Add( li );
            PDFListItem li2 = new PDFListItem( "Item 2", "2" );
            ddl.Items.Add( li2 );
            PDFListItem li3 = new PDFListItem( "Item 3", "3" );
            ddl.Items.Add( li3 );
            ddl.Appearance.Rectangle = new RectangleF( 50, 400, 200, 20 );
            ddl.Appearance.Font = new PDFFont( FontFace.Courier, 10 );
            ddl.Appearance.Border = new PDFFieldBorder( );
            ddl.Appearance.Border.Width = 1;
            ddl.Appearance.Border.Style = FieldBorderStyle.Solid;
            ddl.Appearance.Border.Color = new PDFColor( 0, 0, 255 );
            ddl.SelectedIndex = 1;
            page.Fields.Add( ddl );

            // Create a list box
            PDFListBoxField lbx = new PDFListBoxField( "ListBox" );
            PDFListItem lxi = new PDFListItem( "Item 1", "1" );
            PDFListItem lxi2 = new PDFListItem( "Item 2", "2" );
            PDFListItem lxi3 = new PDFListItem( "Item 3", "3" );
            lbx.Items.Add( lxi );
            lbx.Items.Add( lxi2 );
            lbx.Items.Add( lxi3 );
            lbx.Appearance.Rectangle = new RectangleF( 50, 450, 200, 80 );
            lbx.Appearance.Border = new PDFFieldBorder( );
            lbx.Appearance.Border.Width = 1;
            lbx.Appearance.Border.Style = FieldBorderStyle.Solid;
            lbx.Appearance.Border.Color = new PDFColor( 0, 0, 255 );
            lbx.SelectedIndex = 2;
            page.Fields.Add( lbx );

            doc.SaveToFile( "formnew.pdf" );
        }
    }
}


FormCreate.vb

'
' File name: FormCreate.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Actions
Imports O2S.Components.PDF4NET.Forms
Namespace O2S.Samples.PDF4NET
    ''' <summary>
    ''' This samples shows how to create a PDF e-form using PDF4NET library. The
    ''' sample creates all types of available fields. It also shows how to attach
    ''' actions to button clicks and how to create a submit form button.
    ''' </summary>
    Class FormCreate
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            Dim doc As PDFDocument = New PDFDocument
            Dim page As PDFPage = doc.AddPage()
            Dim blackColor As PDFColor = New PDFColor(0, 0, 0)
            ' Create 4 textboxes.
            Dim tbx As PDFTextBoxField = New PDFTextBoxField("TextBox1")
            tbx.Appearance.Rectangle = New RectangleF(50, 50, 200, 20)
            tbx.Appearance.Border = New PDFFieldBorder(FieldBorderStyle.Solid, 1, blackColor)
            page.Fields.Add(tbx)
            tbx = New PDFTextBoxField("TextBox3")
            tbx.Appearance.Rectangle = New RectangleF(300, 50, 200, 40)
            tbx.Appearance.Border = New PDFFieldBorder(FieldBorderStyle.Solid, 1, blackColor)
            tbx.Text = "Sample field value"
            page.Fields.Add(tbx)
            ' These 2 textboxes have no border.
            tbx = New PDFTextBoxField("TextBox2")
            tbx.Appearance.Rectangle = New RectangleF(50, 100, 200, 20)
            tbx.Text = "<Click here to fill your name>"
            tbx.Value = ""
            page.Fields.Add(tbx)
            tbx = New PDFTextBoxField("TextBox4")
            tbx.Appearance.Rectangle = New RectangleF(300, 100, 200, 40)
            page.Fields.Add(tbx)
            ' Create a push button
            Dim btn As PDFPushbuttonField = New PDFPushbuttonField("Pushbutton")
            btn.Tooltip = "Button Tooltip"
            btn.NormalAppearance.Caption = "Push me"
            btn.NormalAppearance.Rectangle = New RectangleF(50, 150, 200, 20)
            btn.NormalAppearance.ForeColor = New PDFColor(255, 0, 0)
            btn.NormalAppearance.BackColor = New PDFColor(0, 255, 0)
            page.Fields.Add(btn)
            ' Set an OnClick action for the button
            Dim js As PDFJavaScriptAction = New PDFJavaScriptAction
            js.Script = "var f = this.getField(""TextBox1"");" & Chr(13) & "" & Chr(10) & "f.value = ""test"";"
            btn.Actions.MouseUp = js
            ' Create a submit form push button
            btn = New PDFPushbuttonField("SubmitForm")
            btn.Tooltip = "Submits the form fields"
            btn.NormalAppearance.Caption = "Submit form"
            btn.NormalAppearance.Rectangle = New RectangleF(300, 150, 200, 20)
            btn.NormalAppearance.ForeColor = New PDFColor(255, 0, 0)
            btn.NormalAppearance.BackColor = New PDFColor(0, 255, 0)
            page.Fields.Add(btn)
            ' Set an OnClick action for the button
            Dim submitFormAction As PDFSubmitFormAction = New PDFSubmitFormAction
            submitFormAction.Url = "http://localhost/fieldsexplorer/fieldsviewer.aspx"
            submitFormAction.DataFormat = SubmitDataFormat.HTML
            btn.Actions.MouseUp = submitFormAction
            ' Create a checkbox
            Dim checkBox As PDFCheckBoxField = New PDFCheckBoxField("CheckBox")
            checkBox.ExportValue = "1"
            checkBox.Checked = True
            checkBox.Style = SymbolStyle.Check
            checkBox.CheckedNormalAppearance.Rectangle = New RectangleF(50, 200, 20, 20)
            checkBox.CheckedNormalAppearance.ForeColor = New PDFColor(0, 0, 0)
            checkBox.CheckedNormalAppearance.BackColor = New PDFColor(255, 255, 255)
            page.Fields.Add(checkBox)
            ' Create a radiobutton list
            Dim rbl As PDFRadioButtonListField = New PDFRadioButtonListField("RadioButtonList")
            rbl.Style = SymbolStyle.Diamond
            Dim rbi As PDFRadioButtonItem = New PDFRadioButtonItem
            rbi.Value = "1"
            rbi.CheckedNormalAppearance.Rectangle = New RectangleF(50, 250, 20, 20)
            rbi.CheckedNormalAppearance.ForeColor = New PDFColor(255, 255, 255)
            rbi.CheckedNormalAppearance.BackColor = New PDFColor(0, 0, 0)
            rbl.Items.Add(rbi)
            Dim rbi2 As PDFRadioButtonItem = New PDFRadioButtonItem
            rbi2.Value = "2"
            rbi2.CheckedNormalAppearance.Rectangle = New RectangleF(50, 300, 20, 20)
            rbi2.CheckedNormalAppearance.ForeColor = New PDFColor(255, 255, 255)
            rbi2.CheckedNormalAppearance.BackColor = New PDFColor(0, 0, 0)
            rbl.Items.Add(rbi2)
            Dim rbi3 As PDFRadioButtonItem = New PDFRadioButtonItem
            rbi3.Value = "3"
            rbi3.CheckedNormalAppearance.Rectangle = New RectangleF(50, 350, 20, 20)
            rbi3.CheckedNormalAppearance.ForeColor = New PDFColor(255, 255, 255)
            rbi3.CheckedNormalAppearance.BackColor = New PDFColor(0, 0, 0)
            rbl.Items.Add(rbi3)
            rbl.SelectedValue = "3"
            page.Fields.Add(rbl)
            ' Create a drop down list
            Dim ddl As PDFDropDownListField = New PDFDropDownListField("DropDownList")
            Dim li As PDFListItem = New PDFListItem("Item 1", "1")
            ddl.Items.Add(li)
            Dim li2 As PDFListItem = New PDFListItem("Item 2", "2")
            ddl.Items.Add(li2)
            Dim li3 As PDFListItem = New PDFListItem("Item 3", "3")
            ddl.Items.Add(li3)
            ddl.Appearance.Rectangle = New RectangleF(50, 400, 200, 20)
            ddl.Appearance.Font = New PDFFont(FontFace.Courier, 10)
            ddl.Appearance.Border = New PDFFieldBorder
            ddl.Appearance.Border.Width = 1
            ddl.Appearance.Border.Style = FieldBorderStyle.Solid
            ddl.Appearance.Border.Color = New PDFColor(0, 0, 255)
            ddl.SelectedIndex = 1
            page.Fields.Add(ddl)
            ' Create a list box
            Dim lbx As PDFListBoxField = New PDFListBoxField("ListBox")
            Dim lxi As PDFListItem = New PDFListItem("Item 1", "1")
            Dim lxi2 As PDFListItem = New PDFListItem("Item 2", "2")
            Dim lxi3 As PDFListItem = New PDFListItem("Item 3", "3")
            lbx.Items.Add(lxi)
            lbx.Items.Add(lxi2)
            lbx.Items.Add(lxi3)
            lbx.Appearance.Rectangle = New RectangleF(50, 450, 200, 80)
            lbx.Appearance.Border = New PDFFieldBorder
            lbx.Appearance.Border.Width = 1
            lbx.Appearance.Border.Style = FieldBorderStyle.Solid
            lbx.Appearance.Border.Color = New PDFColor(0, 0, 255)
            lbx.SelectedIndex = 2
            page.Fields.Add(lbx)
            doc.SaveToFile("formnew.pdf")
        End Sub
    End Class
End Namespace


Samples: FormFieldsEnumerator

Samples

Form Fields Enumerator

This sample shows how to enumerate the fields in a PDF document. Because PDF specification allows the same field to appear multiple times (both on the same page, and in the document), a difference is made between fields and their widgets (their visual representations). For example, if the same field appears 3 times in a PDF file, the Fields collection of the document will contain only one element, 1 field. The field tells the user how many widgets it has.
The radiobutton list is a special case: each item can have only one widget, but the list can spread over multiple pages (for example 3 items on a page, 3 items on another page, like in the PDF file used in this sample).

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


FormFieldsEnumerator.cs

/// <fileName>
/// File name: FormFieldsEnumerator.cs
/// </fileName>

using System;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Forms;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to enumerate the fields in a PDF document. Because PDF specification
    /// allows the same field to appear multiple times (both on the same page, and in the document),
    /// a difference is made between fields and their widgets (their visual representations).
    /// For example, if the same field appears 3 times in a PDF file, the Fields collection of the
    /// document will contain only one element, 1 field. The field tells the user how many
    /// widgets it has.
    /// The radiobutton list is a special case: each item can have only one widget, but the list
    /// can spread over multiple pages (for example 3 items on a page, 3 items on another page, like
    /// in the PDF file used in this sample).
    /// </summary>
    class FormFieldsEnumerator
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Load the PDF document
            PDFDocument doc = new PDFDocument( "formfieldsenumerator.pdf" );

            // Display total number of fields in the document
            // 6 fields: 1 text box (3 widgets), 1 checkbox (3 widgets), 1 combobox (1 widget)
            // 1 listbox (1 widget), 1 radiobuttonlist (6 items), 1 pushbutton (1 widget)
            Console.WriteLine( "Total number of fields in the document: {0}", doc.Form.Fields.Count );

            // Display number of fields located on page 1
            // 6 fields: 1 text box (2 widgets), 1 checkbox (3 widgets), 1 combobox (1 widget)
            // 1 listbox (1 widget), 1 radiobuttonlist (3 items on this page), 1 pushbutton
            Console.WriteLine( "Number of fields on page 1: {0}", doc.Pages[0].Fields.Count );

            // Display number of fields located on page 2
            // 2 fields: 1 text box (1 widgets), 1 radiobuttonlist (3 items on this page)
            Console.WriteLine( "Number of fields on page 2: {0}", doc.Pages[1].Fields.Count );

            // Sum of fields on both pages is different from the number of fields
            // in the document because there are fields that appear on both pages (TextBox and RadioButton)
            Console.WriteLine( "Sum of fields on both pages is different from the number of fields " +
                "in the document because there are fields that appear on both pages (TextBox and RadioButton)" );
            Console.WriteLine( " " );

            // Enumerate the widgets of all fields in the document
            Console.WriteLine( "Field widgets at document level" );
            for( int i = 0; i < doc.Form.Fields.Count; i++ )
            {
                // Display the field name
                Console.WriteLine( "Field name: {0}", doc.Form.Fields[i].Name );

                // Every field has at least one widget
                int widgetsCount = 1;

                if( doc.Form.Fields[i] is PDFTextBoxField )
                {
                    PDFTextBoxField textBox = ( PDFTextBoxField )doc.Form.Fields[i];
                    // Activate first widget
                    textBox.ActivateFirstWidget( );
                    // Display widget position on the page
                    Console.WriteLine( " Position for widget {0} " +
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                        widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top,
                        textBox.Appearance.Width, textBox.Appearance.Height );
                    // Loop through all field widgets
                    while( textBox.ActivateNextWidget( ) )
                    {
                        widgetsCount++;
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top,
                            textBox.Appearance.Width, textBox.Appearance.Height );
                    }
                }
                if( doc.Form.Fields[i] is PDFPushbuttonField )
                {
                    PDFPushbuttonField pushButton = ( PDFPushbuttonField )doc.Form.Fields[i];
                    // Activate first widget
                    pushButton.ActivateFirstWidget( );
                    // Display widget position on the page
                    Console.WriteLine( " Position for widget {0} " +
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                        widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top,
                        pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height );
                    // Loop through all field widgets
                    while( pushButton.ActivateNextWidget( ) )
                    {
                        widgetsCount++;
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top,
                            pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height );
                    }
                }
                if( doc.Form.Fields[i] is PDFCheckBoxField )
                {
                    PDFCheckBoxField checkBox = ( PDFCheckBoxField )doc.Form.Fields[i];
                    // Activate first widget
                    checkBox.ActivateFirstWidget( );
                    // Display widget position on the page
                    Console.WriteLine( " Position for widget {0} " +
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                        widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top,
                        checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height );
                    Console.WriteLine( " Export value for widget {0}: {1}",
                        widgetsCount, checkBox.ExportValue );
                    Console.WriteLine( " Widget {0} is checked: {1}", widgetsCount, checkBox.Checked );
                    // Loop through all field widgets
                    while( checkBox.ActivateNextWidget( ) )
                    {
                        widgetsCount++;
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top,
                            checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height );
                        Console.WriteLine( " Export value for widget {0}: {1}",
                            widgetsCount, checkBox.ExportValue );
                        Console.WriteLine( " Widget {0} is checked: {1}", widgetsCount, checkBox.Checked );
                    }
                }
                if( doc.Form.Fields[i] is PDFDropDownListField )
                {
                    PDFDropDownListField dropDownList = ( PDFDropDownListField )doc.Form.Fields[i];
                    // Activate first widget
                    dropDownList.ActivateFirstWidget( );
                    // Display widget position on the page
                    Console.WriteLine( " Position for widget {0} " +
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                        widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top,
                        dropDownList.Appearance.Width, dropDownList.Appearance.Height );
                    // Loop through all field widgets
                    while( dropDownList.ActivateNextWidget( ) )
                    {
                        widgetsCount++;
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top,
                            dropDownList.Appearance.Width, dropDownList.Appearance.Height );
                    }
                }
                if( doc.Form.Fields[i] is PDFListBoxField )
                {
                    PDFListBoxField listBox = ( PDFListBoxField )doc.Form.Fields[i];
                    // Activate first widget
                    listBox.ActivateFirstWidget( );
                    // Display widget position on the page
                    Console.WriteLine( " Position for widget {0} " +
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                        widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top,
                        listBox.Appearance.Width, listBox.Appearance.Height );
                    // Loop through all field widgets
                    while( listBox.ActivateNextWidget( ) )
                    {
                        widgetsCount++;
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top,
                            listBox.Appearance.Width, listBox.Appearance.Height );
                    }
                }
                if( doc.Form.Fields[i] is PDFRadioButtonListField )
                {
                    PDFRadioButtonListField radioButtonList =
                        ( PDFRadioButtonListField )doc.Form.Fields[i];
                    Console.WriteLine( " Field \"{0}\" has {1} item(s)",
                        radioButtonList.Name, radioButtonList.Items.Count );
                }
                Console.WriteLine( " Field \"{0}\" has {1} widget(s)", doc.Form.Fields[i].Name, widgetsCount );
            }

            Console.WriteLine( " " );

            // Enumerate the widgets of all fields at page level
            Console.WriteLine( "Field widgets at page level" );
            for( int j = 0; j < doc.Pages.Count; j++ )
            {
                Console.WriteLine( "*** Field widgets on page {0}", j + 1 );
                PDFFields pageFields = doc.Pages[j].Fields;
                for( int i = 0; i < pageFields.Count; i++ )
                {
                    // Display the field name
                    Console.WriteLine( "Field name: {0}", pageFields[i].Name );

                    // Every field has at least one widget
                    int widgetsCount = 1;

                    if( pageFields[i] is PDFTextBoxField )
                    {
                        PDFTextBoxField textBox = ( PDFTextBoxField )pageFields[i];
                        // Activate first widget
                        textBox.ActivateFirstWidget( );
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top,
                            textBox.Appearance.Width, textBox.Appearance.Height );
                        // Loop through all field widgets
                        while( textBox.ActivateNextWidget( ) )
                        {
                            widgetsCount++;
                            // Display widget position on the page
                            Console.WriteLine( " Position for widget {0} " +
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                                widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top,
                                textBox.Appearance.Width, textBox.Appearance.Height );
                        }
                    }
                    if( pageFields[i] is PDFPushbuttonField )
                    {
                        PDFPushbuttonField pushButton = ( PDFPushbuttonField )pageFields[i];
                        // Activate first widget
                        pushButton.ActivateFirstWidget( );
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top,
                            pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height );
                        // Loop through all field widgets
                        while( pushButton.ActivateNextWidget( ) )
                        {
                            widgetsCount++;
                            // Display widget position on the page
                            Console.WriteLine( " Position for widget {0} " +
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                                widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top,
                                pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height );
                        }
                    }
                    if( pageFields[i] is PDFCheckBoxField )
                    {
                        PDFCheckBoxField checkBox = ( PDFCheckBoxField )pageFields[i];
                        // Activate first widget
                        checkBox.ActivateFirstWidget( );
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top,
                            checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height );
                        Console.WriteLine( " Export value for widget {0}: {1}",
                            widgetsCount, checkBox.ExportValue );
                        Console.WriteLine( " Widget {0} is checked: {1}", widgetsCount, checkBox.Checked );
                        // Loop through all field widgets
                        while( checkBox.ActivateNextWidget( ) )
                        {
                            widgetsCount++;
                            // Display widget position on the page
                            Console.WriteLine( " Position for widget {0} " +
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                                widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top,
                                checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height );
                            Console.WriteLine( " Export value for widget {0}: {1}",
                                widgetsCount, checkBox.ExportValue );
                            Console.WriteLine( " Widget {0} is checked: {1}", widgetsCount, checkBox.Checked );
                        }
                    }
                    if( pageFields[i] is PDFDropDownListField )
                    {
                        PDFDropDownListField dropDownList = ( PDFDropDownListField )pageFields[i];
                        // Activate first widget
                        dropDownList.ActivateFirstWidget( );
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top,
                            dropDownList.Appearance.Width, dropDownList.Appearance.Height );
                        // Loop through all field widgets
                        while( dropDownList.ActivateNextWidget( ) )
                        {
                            widgetsCount++;
                            // Display widget position on the page
                            Console.WriteLine( " Position for widget {0} " +
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                                widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top,
                                dropDownList.Appearance.Width, dropDownList.Appearance.Height );
                        }
                    }
                    if( pageFields[i] is PDFListBoxField )
                    {
                        PDFListBoxField listBox = ( PDFListBoxField )pageFields[i];
                        // Activate first widget
                        listBox.ActivateFirstWidget( );
                        // Display widget position on the page
                        Console.WriteLine( " Position for widget {0} " +
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                            widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top,
                            listBox.Appearance.Width, listBox.Appearance.Height );
                        // Loop through all field widgets
                        while( listBox.ActivateNextWidget( ) )
                        {
                            widgetsCount++;
                            // Display widget position on the page
                            Console.WriteLine( " Position for widget {0} " +
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                                widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top,
                                listBox.Appearance.Width, listBox.Appearance.Height );
                        }
                    }
                    if( pageFields[i] is PDFRadioButtonListField )
                    {
                        PDFRadioButtonListField radioButtonList =
                            ( PDFRadioButtonListField )pageFields[i];
                        // Number of radiobutton items located on this page
                        int itemsCount = 0;
                        for( int k = 0; k < radioButtonList.Items.Count; k++ )
                        {
                            if( radioButtonList.Items[k].Page == doc.Pages[j] )
                            {
                                itemsCount++;
                                // Display widget position on the page
                                Console.WriteLine( " Position for item {0} " +
                                    "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}",
                                    itemsCount, radioButtonList.Items[k].CheckedNormalAppearance.Left,
                                    radioButtonList.Items[k].CheckedNormalAppearance.Top,
                                    radioButtonList.Items[k].CheckedNormalAppearance.Width,
                                    radioButtonList.Items[k].CheckedNormalAppearance.Height );
                            }
                        }
                        Console.WriteLine( " Field \"{0}\" has {1} item(s) on this page",
                            radioButtonList.Name, itemsCount );
                    }
                    Console.WriteLine( " Field \"{0}\" has {1} widget(s)", pageFields[i].Name, widgetsCount );
                }
            }
        }
    }
}


FormFieldsEnumerator.vb

'
' File name: FormFieldsEnumerator.vb
'

Imports System
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Forms
Namespace O2S.Samples.PDF4NET
    ''' <summary>
    ''' This sample shows how to enumerate the fields in a PDF document. Because PDF specification
    ''' allows the same field to appear multiple times (both on the same page, and in the document),
    ''' a difference is made between fields and their widgets (their visual representations).
    ''' For example, if the same field appears 3 times in a PDF file, the Fields collection of the
    ''' document will contain only one element, 1 field. The field tells the user how many
    ''' widgets it has.
    ''' The radiobutton list is a special case: each item can have only one widget, but the list
    ''' can spread over multiple pages (for example 3 items on a page, 3 items on another page, like
    ''' in the PDF file used in this sample).
    ''' </summary>
    Class FormFieldsEnumerator
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            ' Load the PDF document
            Dim doc As PDFDocument = New PDFDocument("formfieldsenumerator.pdf")
            ' Display total number of fields in the document
            ' 6 fields: 1 text box (3 widgets), 1 checkbox (3 widgets), 1 combobox (1 widget)
            ' 1 listbox (1 widget), 1 radiobuttonlist (6 items), 1 pushbutton (1 widget)
            Console.WriteLine("Total number of fields in the document: {0}", doc.Form.Fields.Count)
            ' Display number of fields located on page 1
            ' 6 fields: 1 text box (2 widgets), 1 checkbox (3 widgets), 1 combobox (1 widget)
            ' 1 listbox (1 widget), 1 radiobuttonlist (3 items on this page), 1 pushbutton
            Console.WriteLine("Number of fields on page 1: {0}", doc.Pages(0).Fields.Count)
            ' Display number of fields located on page 2
            ' 2 fields: 1 text box (1 widgets), 1 radiobuttonlist (3 items on this page)
            Console.WriteLine("Number of fields on page 2: {0}", doc.Pages(1).Fields.Count)
            ' Sum of fields on both pages is different from the number of fields
            ' in the document because there are fields that appear on both pages (TextBox and RadioButton)
            Console.WriteLine("Sum of fields on both pages is different from the number of fields " + _
                "in the document because there are fields that appear on both pages (TextBox and RadioButton)")
            Console.WriteLine(" ")
            ' Enumerate the widgets of all fields in the document
            Console.WriteLine("Field widgets at document level")
            For i As Integer = 0 To doc.Form.Fields.Count - 1
                ' Display the field name
                Console.WriteLine("Field name: {0}", doc.Form.Fields(i).Name)
                ' Every field has at least one widget
                Dim widgetsCount As Integer = 1
                If TypeOf doc.Form.Fields(i) Is PDFTextBoxField Then
                    Dim textBox As PDFTextBoxField = DirectCast(doc.Form.Fields(i), PDFTextBoxField)
                    ' Activate first widget
                    textBox.ActivateFirstWidget()
                    ' Display widget position on the page
                    Console.WriteLine(" Position for widget {0} " + _
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                        widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top, _
                        textBox.Appearance.Width, textBox.Appearance.Height)
                    ' Loop through all field widgets
                    While textBox.ActivateNextWidget()
                        widgetsCount += 1
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top, _
                            textBox.Appearance.Width, textBox.Appearance.Height)
                    End While
                End If
                If TypeOf doc.Form.Fields(i) Is PDFPushbuttonField Then
                    Dim pushButton As PDFPushbuttonField = DirectCast(doc.Form.Fields(i), PDFPushbuttonField)
                    ' Activate first widget
                    pushButton.ActivateFirstWidget()
                    ' Display widget position on the page
                    Console.WriteLine(" Position for widget {0} " + _
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                        widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top, _
                        pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height)
                    ' Loop through all field widgets
                    While pushButton.ActivateNextWidget()
                        widgetsCount += 1
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top, _
                            pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height)
                    End While
                End If
                If TypeOf doc.Form.Fields(i) Is PDFCheckBoxField Then
                    Dim checkBox As PDFCheckBoxField = DirectCast(doc.Form.Fields(i), PDFCheckBoxField)
                    ' Activate first widget
                    checkBox.ActivateFirstWidget()
                    ' Display widget position on the page
                    Console.WriteLine(" Position for widget {0} " + _
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                        widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top, _
                        checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height)
                    Console.WriteLine(" Export value for widget {0}: {1}", widgetsCount, checkBox.ExportValue)
                    Console.WriteLine(" Widget {0} is checked: {1}", widgetsCount, checkBox.Checked)
                    ' Loop through all field widgets
                    While checkBox.ActivateNextWidget()
                        widgetsCount += 1
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top, _
                            checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height)
                        Console.WriteLine(" Export value for widget {0}: {1}", widgetsCount, checkBox.ExportValue)
                        Console.WriteLine(" Widget {0} is checked: {1}", widgetsCount, checkBox.Checked)
                    End While
                End If
                If TypeOf doc.Form.Fields(i) Is PDFDropDownListField Then
                    Dim dropDownList As PDFDropDownListField = DirectCast(doc.Form.Fields(i), PDFDropDownListField)
                    ' Activate first widget
                    dropDownList.ActivateFirstWidget()
                    ' Display widget position on the page
                    Console.WriteLine(" Position for widget {0} " + _
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                        widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top, _
                        dropDownList.Appearance.Width, dropDownList.Appearance.Height)
                    ' Loop through all field widgets
                    While dropDownList.ActivateNextWidget()
                        widgetsCount += 1
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top, _
                            dropDownList.Appearance.Width, dropDownList.Appearance.Height)
                    End While
                End If
                If TypeOf doc.Form.Fields(i) Is PDFListBoxField Then
                    Dim listBox As PDFListBoxField = DirectCast(doc.Form.Fields(i), PDFListBoxField)
                    ' Activate first widget
                    listBox.ActivateFirstWidget()
                    ' Display widget position on the page
                    Console.WriteLine(" Position for widget {0} " + _
                        "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                        widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top, _
                        listBox.Appearance.Width, listBox.Appearance.Height)
                    ' Loop through all field widgets
                    While listBox.ActivateNextWidget()
                        widgetsCount += 1
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top, _
                            listBox.Appearance.Width, listBox.Appearance.Height)
                    End While
                End If
                If TypeOf doc.Form.Fields(i) Is PDFRadioButtonListField Then
                    Dim radioButtonList As PDFRadioButtonListField = DirectCast(doc.Form.Fields(i), PDFRadioButtonListField)
                    Console.WriteLine(" Field ""{0}"" has {1} item(s)", _
                        radioButtonList.Name, radioButtonList.Items.Count)
                End If
                Console.WriteLine(" Field ""{0}"" has {1} widget(s)", _
                    doc.Form.Fields(i).Name, widgetsCount)
            Next
            Console.WriteLine(" ")
            ' Enumerate the widgets of all fields at page level
            Console.WriteLine("Field widgets at page level")
            For j As Integer = 0 To doc.Pages.Count - 1
                Console.WriteLine("*** Field widgets on page {0}", j + 1)
                Dim pageFields As PDFFields = doc.Pages(j).Fields
                For i As Integer = 0 To pageFields.Count - 1
                    ' Display the field name
                    Console.WriteLine("Field name: {0}", pageFields(i).Name)
                    ' Every field has at least one widget
                    Dim widgetsCount As Integer = 1
                    If TypeOf pageFields(i) Is PDFTextBoxField Then
                        Dim textBox As PDFTextBoxField = DirectCast(pageFields(i), PDFTextBoxField)
                        ' Activate first widget
                        textBox.ActivateFirstWidget()
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top, _
                            textBox.Appearance.Width, textBox.Appearance.Height)
                        ' Loop through all field widgets
                        While textBox.ActivateNextWidget()
                            widgetsCount += 1
                            ' Display widget position on the page
                            Console.WriteLine(" Position for widget {0} " + _
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                                widgetsCount, textBox.Appearance.Left, textBox.Appearance.Top, _
                                textBox.Appearance.Width, textBox.Appearance.Height)
                        End While
                    End If
                    If TypeOf pageFields(i) Is PDFPushbuttonField Then
                        Dim pushButton As PDFPushbuttonField = DirectCast(pageFields(i), PDFPushbuttonField)
                        ' Activate first widget
                        pushButton.ActivateFirstWidget()
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top, _
                            pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height)
                        ' Loop through all field widgets
                        While pushButton.ActivateNextWidget()
                            widgetsCount += 1
                            ' Display widget position on the page
                            Console.WriteLine(" Position for widget {0} " + _
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                                widgetsCount, pushButton.NormalAppearance.Left, pushButton.NormalAppearance.Top, _
                                pushButton.NormalAppearance.Width, pushButton.NormalAppearance.Height)
                        End While
                    End If
                    If TypeOf pageFields(i) Is PDFCheckBoxField Then
                        Dim checkBox As PDFCheckBoxField = DirectCast(pageFields(i), PDFCheckBoxField)
                        ' Activate first widget
                        checkBox.ActivateFirstWidget()
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top, _
                            checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height)
                        Console.WriteLine(" Export value for widget {0}: {1}", widgetsCount, checkBox.ExportValue)
                        Console.WriteLine(" Widget {0} is checked: {1}", widgetsCount, checkBox.Checked)
                        ' Loop through all field widgets
                        While checkBox.ActivateNextWidget()
                            widgetsCount += 1
                            ' Display widget position on the page
                            Console.WriteLine(" Position for widget {0} " + _
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                                widgetsCount, checkBox.CheckedNormalAppearance.Left, checkBox.CheckedNormalAppearance.Top, _
                                checkBox.CheckedNormalAppearance.Width, checkBox.CheckedNormalAppearance.Height)
                            Console.WriteLine(" Export value for widget {0}: {1}", widgetsCount, checkBox.ExportValue)
                            Console.WriteLine(" Widget {0} is checked: {1}", widgetsCount, checkBox.Checked)
                        End While
                    End If
                    If TypeOf pageFields(i) Is PDFDropDownListField Then
                        Dim dropDownList As PDFDropDownListField = DirectCast(pageFields(i), PDFDropDownListField)
                        ' Activate first widget
                        dropDownList.ActivateFirstWidget()
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top, _
                            dropDownList.Appearance.Width, dropDownList.Appearance.Height)
                        ' Loop through all field widgets
                        While dropDownList.ActivateNextWidget()
                            widgetsCount += 1
                            ' Display widget position on the page
                            Console.WriteLine(" Position for widget {0} " + _
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                                widgetsCount, dropDownList.Appearance.Left, dropDownList.Appearance.Top, _
                                dropDownList.Appearance.Width, dropDownList.Appearance.Height)
                        End While
                    End If
                    If TypeOf pageFields(i) Is PDFListBoxField Then
                        Dim listBox As PDFListBoxField = DirectCast(pageFields(i), PDFListBoxField)
                        ' Activate first widget
                        listBox.ActivateFirstWidget()
                        ' Display widget position on the page
                        Console.WriteLine(" Position for widget {0} " + _
                            "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                            widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top, _
                            listBox.Appearance.Width, listBox.Appearance.Height)
                        ' Loop through all field widgets
                        While listBox.ActivateNextWidget()
                            widgetsCount += 1
                            ' Display widget position on the page
                            Console.WriteLine(" Position for widget {0} " + _
                                "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                                widgetsCount, listBox.Appearance.Left, listBox.Appearance.Top, _
                                listBox.Appearance.Width, listBox.Appearance.Height)
                        End While
                    End If
                    If TypeOf pageFields(i) Is PDFRadioButtonListField Then
                        Dim radioButtonList As PDFRadioButtonListField = DirectCast(pageFields(i), PDFRadioButtonListField)
                        ' Number of radiobutton items located on this page
                        Dim itemsCount As Integer = 0
                        For k As Integer = 0 To radioButtonList.Items.Count - 1
                            If radioButtonList.Items(k).Page Is doc.Pages(j) Then
                                itemsCount += 1
                                ' Display widget position on the page
                                Console.WriteLine(" Position for item {0} " + _
                                    "(Left|Top|Width|Height): {1:0.00}|{2:0.00}|{3:0.00}|{4:0.00}", _
                                    itemsCount, radioButtonList.Items(k).CheckedNormalAppearance.Left, _
                                    radioButtonList.Items(k).CheckedNormalAppearance.Top, _
                                    radioButtonList.Items(k).CheckedNormalAppearance.Width, _
                                    radioButtonList.Items(k).CheckedNormalAppearance.Height)
                            End If
                        Next
                        Console.WriteLine(" Field ""{0}"" has {1} item(s) on this page", _
                            radioButtonList.Name, itemsCount)
                    End If
                    Console.WriteLine(" Field ""{0}"" has {1} widget(s)", _
                        pageFields(i).Name, widgetsCount)
                Next
            Next
        End Sub
    End Class
End Namespace


Samples: Formfill

Samples

Form fill

This sample demonstrates how to fill a PDF form using PDF4NET.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


FormFill.cs

/// <fileName>
/// File name: FormFill.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Forms;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to fill a PDF form using PDF4NET library.
    /// </summary>
    class FormFill
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( "fw4.pdf" );

            // fill the fields from the first page
            ( doc.Fields["f1-1"] as PDFTextBoxField ).Text = "1";
            ( doc.Fields["f1-2"] as PDFTextBoxField ).Text = "1";
            ( doc.Fields["f1-3"] as PDFTextBoxField ).Text = "1";
            ( doc.Fields["f1-4"] as PDFTextBoxField ).Text = "3";
            ( doc.Fields["f1-5"] as PDFTextBoxField ).Text = "1";
            ( doc.Fields["f1-6"] as PDFTextBoxField ).Text = "1";
            ( doc.Fields["f1-7"] as PDFTextBoxField ).Text = "22";
            ( doc.Fields["f1-8"] as PDFTextBoxField ).Text = "30";
            ( doc.Fields["f1-9"] as PDFTextBoxField ).Text = "John";
            ( doc.Fields["f1-10"] as PDFTextBoxField ).Text = "Doe";
            ( doc.Fields["f1-11"] as PDFTextBoxField ).Text = "3233 Spring Rd.";
            ( doc.Fields["f1-12"] as PDFTextBoxField ).Text = "Atlanta, GA 30339";
            ( doc.Fields["f1-13"] as PDFTextBoxField ).Text = "332";
            ( doc.Fields["f1-14"] as PDFTextBoxField ).Text = "43";
            ( doc.Fields["f1-15"] as PDFTextBoxField ).Text = "4556";
            ( doc.Fields["f1-16"] as PDFTextBoxField ).Text = "3";
            ( doc.Fields["f1-17"] as PDFTextBoxField ).Text = "2000";
            ( doc.Fields["f1-18"] as PDFTextBoxField ).Text = "Exempt";
            ( doc.Fields["f1-19"] as PDFTextBoxField ).Text = "PDF4NET LLC, 3000 Nowhere Rd., Atlanta, GA 30339";
            ( doc.Fields["f1-20"] as PDFTextBoxField ).Text = "200";
            ( doc.Fields["f1-21"] as PDFTextBoxField ).Text = "22";
            ( doc.Fields["f1-22"] as PDFTextBoxField ).Text = "56654";
            ( doc.Fields["c1-1"] as PDFCheckBoxField ).Value = "Yes";
            ( doc.Fields["c1-2"] as PDFCheckBoxField ).Checked = true;

            // fill the fields from the second page
            ( doc.Fields["f2-1"] as PDFTextBoxField ).Text = "3200";
            ( doc.Fields["f2-2"] as PDFTextBoxField ).Text = "4850";
            ( doc.Fields["f2-3"] as PDFTextBoxField ).Text = "0";
            ( doc.Fields["f2-4"] as PDFTextBoxField ).Text = "500";
            ( doc.Fields["f2-5"] as PDFTextBoxField ).Text = "500";
            ( doc.Fields["f2-6"] as PDFTextBoxField ).Text = "800";
            ( doc.Fields["f2-7"] as PDFTextBoxField ).Text = "0";
            ( doc.Fields["f2-8"] as PDFTextBoxField ).Text = "0";
            ( doc.Fields["f2-9"] as PDFTextBoxField ).Text = "3";
            ( doc.Fields["f2-10"] as PDFTextBoxField ).Text = "3";
            ( doc.Fields["f2-11"] as PDFTextBoxField ).Text = "3";
            ( doc.Fields["f2-12"] as PDFTextBoxField ).Text = "2";
            ( doc.Fields["f2-13"] as PDFTextBoxField ).Text = "3";
            ( doc.Fields["f2-14"] as PDFTextBoxField ).Text = "3";
            ( doc.Fields["f2-15"] as PDFTextBoxField ).Text = "2";
            ( doc.Fields["f2-16"] as PDFTextBoxField ).Text = "1";
            ( doc.Fields["f2-17"] as PDFTextBoxField ).Text = "200";
            ( doc.Fields["f2-18"] as PDFTextBoxField ).Text = "600";
            ( doc.Fields["f2-19"] as PDFTextBoxField ).Text = "250";

            // the fields below do not exist in the sample pdf file
            // the code is provided to show how to work with other field types

            // select a checkbox
            //( doc.Fields["c1-1"] as PDFCheckBoxField ).Checked = true;

            // select the second radio button in the list
            //( doc.Fields["r1-1"] as PDFRadioButtonListField ).SelectedIndex = 1;

            // select the first item in the drop down list
            //( doc.Fields["ddl1-1"] as PDFDropDownListField ).SelectedIndex = 0;

            // select the 4th item in the list box
            //( doc.Fields["lb1-1"] as PDFTextBoxField ).SelectedIndex = 3;

            // Save the document to disk
            doc.SaveToFile( "fw4fill.pdf" );
        }
    }
}


FormFill.vb

'
' File name: FormFill.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Forms

Namespace O2S.Samples.PDF4NET.FormFill
    '/// <summary>
    '/// This sample shows how to fill a PDF form using PDF4NET library.
    '/// </summary>
    Class FormFill
        '/// <summary>
        '/// The main entry point for the application.
        '/// </summary>
        Shared Sub Main(ByVal args() As String)
            '// Create the pdf document
            Dim doc As New PDFDocument("fw4.pdf")

            '// fill the fields from the first page
            CType(doc.Fields("f1-1"), PDFTextBoxField).Text = "1"
            CType(doc.Fields("f1-2"), PDFTextBoxField).Text = "1"
            CType(doc.Fields("f1-3"), PDFTextBoxField).Text = "1"
            CType(doc.Fields("f1-4"), PDFTextBoxField).Text = "3"
            CType(doc.Fields("f1-5"), PDFTextBoxField).Text = "1"
            CType(doc.Fields("f1-6"), PDFTextBoxField).Text = "1"
            CType(doc.Fields("f1-7"), PDFTextBoxField).Text = "22"
            CType(doc.Fields("f1-8"), PDFTextBoxField).Text = "30"
            CType(doc.Fields("f1-9"), PDFTextBoxField).Text = "John"
            CType(doc.Fields("f1-10"), PDFTextBoxField).Text = "Doe"
            CType(doc.Fields("f1-11"), PDFTextBoxField).Text = "3233 Spring Rd."
            CType(doc.Fields("f1-12"), PDFTextBoxField).Text = "Atlanta, GA 30339"
            CType(doc.Fields("f1-13"), PDFTextBoxField).Text = "332"
            CType(doc.Fields("f1-14"), PDFTextBoxField).Text = "43"
            CType(doc.Fields("f1-15"), PDFTextBoxField).Text = "4556"
            CType(doc.Fields("f1-16"), PDFTextBoxField).Text = "3"
            CType(doc.Fields("f1-17"), PDFTextBoxField).Text = "2000"
            CType(doc.Fields("f1-18"), PDFTextBoxField).Text = "Exempt"
            CType(doc.Fields("f1-19"), PDFTextBoxField).Text = "PDF4NET LLC, 3000 Nowhere Rd., Atlanta, GA 30339"
            CType(doc.Fields("f1-20"), PDFTextBoxField).Text = "200"
            CType(doc.Fields("f1-21"), PDFTextBoxField).Text = "22"
            CType(doc.Fields("f1-22"), PDFTextBoxField).Text = "56654"
            CType(doc.Fields("c1-1"), PDFCheckBoxField).Value = "Yes"
            CType(doc.Fields("c1-2"), PDFCheckBoxField).Checked = true

            '// fill the fields from the second page
            CType(doc.Fields("f2-1"), PDFTextBoxField).Text = "3200"
            CType(doc.Fields("f2-2"), PDFTextBoxField).Text = "4850"
            CType(doc.Fields("f2-3"), PDFTextBoxField).Text = "0"
            CType(doc.Fields("f2-4"), PDFTextBoxField).Text = "500"
            CType(doc.Fields("f2-5"), PDFTextBoxField).Text = "500"
            CType(doc.Fields("f2-6"), PDFTextBoxField).Text = "800"
            CType(doc.Fields("f2-7"), PDFTextBoxField).Text = "0"
            CType(doc.Fields("f2-8"), PDFTextBoxField).Text = "0"
            CType(doc.Fields("f2-9"), PDFTextBoxField).Text = "3"
            CType(doc.Fields("f2-10"), PDFTextBoxField).Text = "3"
            CType(doc.Fields("f2-11"), PDFTextBoxField).Text = "3"
            CType(doc.Fields("f2-12"), PDFTextBoxField).Text = "2"
            CType(doc.Fields("f2-13"), PDFTextBoxField).Text = "3"
            CType(doc.Fields("f2-14"), PDFTextBoxField).Text = "3"
            CType(doc.Fields("f2-15"), PDFTextBoxField).Text = "2"
            CType(doc.Fields("f2-16"), PDFTextBoxField).Text = "1"
            CType(doc.Fields("f2-17"), PDFTextBoxField).Text = "200"
            CType(doc.Fields("f2-18"), PDFTextBoxField).Text = "600"
            CType(doc.Fields("f2-19"), PDFTextBoxField).Text = "250"

            '// the fields below do not exist in the sample pdf file
            '// mark a checkbox
            'CType(doc.Fields("c1-1"), PDFCheckBoxField).Checked = True
            '// select the second radio button in the list
            'CType(doc.Fields("r1-1"), PDFRadioButtonListField).SelectedIndex = 1
            '// select the first item in the drop down list
            'CType(doc.Fields("dl1-1"), PDFDropDownListField).SelectedIndex = 0
            '// select the 4th item in the list box
            'CType(doc.Fields("r1-1"), PDFListBoxField).SelectedIndex = 3

            '// Save the document to disk
            doc.SaveToFile("fw4.fill.pdf")
        End Sub
    End Class
End Namespace


Samples: FormFillXFA

Samples

XFA Form Fill

This sample demonstrates how to fill a XFA form using PDF4NET.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


FormFillXFA.cs

/// <fileName>
/// File name: FormFillXFA.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Forms;
using O2S.Components.PDF4NET.Forms.XFA;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to fill a XFA form using PDF4NET library.
    /// XFA forms are created with Adobe Designer 7.
    /// </summary>
    class FormFillXFA
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( "xfasampleform.pdf" );

            // Get the main subform.
            XFASubform mainSubform = doc.XFAForm.Subforms[0].Subforms[0];

            // Fill the product name.
            mainSubform.Fields["txtName"].Value = "PDF4NET";
            // Fill the product SKU.
            mainSubform.Fields["txtSKU"].Value = "PDF4NET01090";
            // Fill the product URL.
            mainSubform.Fields["txtURL"].Value = "http://www.o2sol.com/pdf4net/products.htm";
            // Select the product category.
            mainSubform.Fields["ddlCategory"].Value = "PDF";
            // Also add a new item to Category drop down list.
            XFAListItem listItem = new XFAListItem( "Compression", "CMP" );
            ( mainSubform.Fields["ddlCategory"] as XFAChoiceListField ).Items.Add( listItem );
            // Fill the product image.
            mainSubform.Fields["imgProduct"].Value = "pdf4net.jpg";
            ( mainSubform.Fields["imgProduct"] as XFAImageEditField ).ContentType = "image/jpg";
            // Fill the product short description.
            mainSubform.Fields["txtShortDescription"].Value = "PDF4NET is a .NET library for adding " +
                "PDF capabilities to .NET applications. It supports both desktop and web applications.";
            // Fill the product features.
            mainSubform.Fields["txtFeature1"].Value = "Create PDF files from scratch.";
            mainSubform.Fields["txtFeature2"].Value = "Merge, split and encrypt PDF files.";
            mainSubform.Fields["txtFeature3"].Value = "Create, fill and flatten PDF e-forms.";
            mainSubform.Fields["txtFeature4"].Value = "Fill XFA forms.";
            mainSubform.Fields["txtFeature5"].Value = "Add, edit and remove document attachments.";
            mainSubform.Fields["txtFeature6"].Value = "Add, edit and remove text annotations.";
            mainSubform.Fields["txtFeature7"].Value = "Support for WinForms and ASP.NET applications.";
            // Fill the product long description.
            mainSubform.Fields["txtLongDescription"].Value = "PDF4NET is a .NET library for adding " +
                "PDF capabilities to .NET applications. Version 2.7 brings support for PDF e-form " +
                "creation, support for reading and filling static XFA forms and document attachments. " +
                "It supports both desktop and web applications.";

            // Save the document to disk
            doc.SaveToFile( "xfasampleform.fill.pdf" );
        }
    }
}


FormFillXFA.vb

'
' File name: FormFillXFA.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Forms
Imports O2S.Components.PDF4NET.Forms.XFA
Namespace O2S.Samples.PDF4NET
    ''' <summary>
    ''' This sample shows how to fill a XFA form using PDF4NET library.
    ''' XFA forms are created with Adobe Designer 7.
    ''' </summary>
    Class FormFillXFA
        ''' <summary>
        ''' The main entry point for the application.
        ''' </summary>
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            ' Create the pdf document
            Dim doc As PDFDocument = New PDFDocument("xfasampleform.pdf")
            ' Get the main subform.
            Dim mainSubform As XFASubform = doc.XFAForm.Subforms(0).Subforms(0)
            ' Fill the product name.
            mainSubform.Fields("txtName").Value = "PDF4NET"
            ' Fill the product SKU.
            mainSubform.Fields("txtSKU").Value = "PDF4NET01090"
            ' Fill the product URL.
            mainSubform.Fields("txtURL").Value = "http://www.o2sol.com/pdf4net/products.htm"
            ' Select the product category.
            mainSubform.Fields("ddlCategory").Value = "PDF"
            ' Also add a new item to Category drop down list.
            Dim listItem As XFAListItem = New XFAListItem("Compression", "CMP")
            CType(mainSubform.Fields("ddlCategory"), XFAChoiceListField).Items.Add(listItem)
            ' Fill the product image.
            mainSubform.Fields("imgProduct").Value = "pdf4net.jpg"
            CType(mainSubform.Fields("imgProduct"), XFAImageEditField).ContentType = "image/jpg"
            ' Fill the product short description.
            mainSubform.Fields("txtShortDescription").Value = "PDF4NET is a .NET library for adding " + _
                "PDF capabilities to .NET applications. It supports both desktop and web applications."
            ' Fill the product features.
            mainSubform.Fields("txtFeature1").Value = "Create PDF files from scratch."
            mainSubform.Fields("txtFeature2").Value = "Merge, split and encrypt PDF files."
            mainSubform.Fields("txtFeature3").Value = "Create, fill and flatten PDF e-forms."
            mainSubform.Fields("txtFeature4").Value = "Fill XFA forms."
            mainSubform.Fields("txtFeature5").Value = "Add, edit and remove document attachments."
            mainSubform.Fields("txtFeature6").Value = "Add, edit and remove text annotations."
            mainSubform.Fields("txtFeature7").Value = "Support for WinForms and ASP.NET applications."
            ' Fill the product long description.
            mainSubform.Fields("txtLongDescription").Value = "PDF4NET is a .NET library for adding " + _
                "PDF capabilities to .NET applications. Version 2.7 brings support for PDF e-form " + _
                "creation, support for reading and filling static XFA forms and document attachments. " + _
                "It supports both desktop and web applications."
            ' Save the document to disk
            doc.SaveToFile("xfasampleform.fill.pdf")
        End Sub
    End Class
End Namespace


Samples: Form XObjects

Samples

Form XObjects

This sample demonstrates the support for PDF form XObjects implemented in PDF4NET library. Form XObjects are graphic blocks that can be drawn multiple times in a PDF document and their content is stored only once in the PDF file.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


FormXObject.cs

/// <fileName>
/// File name: FormXObject.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Actions;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.FormXObject
{
    /// <summary>
    /// This sample shows how to use form XObjects with PDF4NET.
    /// </summary>
    class FormXObject
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Create one page
            PDFPage page = doc.AddPage( );

            PDFPen redPen = new PDFPen( new PDFColor( 255, 0, 0 ), 1 );
            PDFBrush darkBlueBrush = new PDFBrush( new PDFColor( 0, 0, 128 ) );

            // create a form XObject for stretched text
            PDFFont font = new PDFFont( FontFace.Helvetica, 16 );
            string pdf4net = "PDF4NET";
            // the size of form xobject matches the text
            PDFFormXObject form = new PDFFormXObject( );
            form.Width = font.MeasureString( pdf4net );
            form.Height = 16;
            // draw the text on the form xobject
            form.Canvas.DrawText( pdf4net, font, null, darkBlueBrush, 0, 0 );

            // draw the form xobject on the page.
            // strectch it to cover the whole page header and on the left margin
            page.Canvas.DrawFormXObject( form, 0, 0, page.Width, 24 );
            page.Canvas.DrawFormXObject( form, 32, 0, page.Height, 32, -90 );

            // create another for xobject that is more complex
            PDFFormXObject form2 = new PDFFormXObject( );
            form2.Width = 100;
            form2.Height = 100;
            // create the form content
            // draw an image
            form2.Canvas.DrawImage( "target.gif", 0, 0, 50, 50 );
            // draw a round rectangle filled with a hatched brush
            PDFHatchBrush hb = new PDFHatchBrush( HatchType.DiagonalCross );
            hb.HatchColor = new PDFColor( Color.CornflowerBlue );
            form2.Canvas.DrawRoundRectangle( redPen, hb, 50, 0, 50, 50, 20, 20 );
            // draw a square with vertical gradient filling
            PDFVerticalGradientBrush vgb = new PDFVerticalGradientBrush( );
            vgb.StartColor = new PDFColor( Color.Crimson );
            vgb.EndColor = new PDFColor( Color.GreenYellow );
            form2.Canvas.DrawRectangle2( redPen, vgb, 0, 50, 50, 50 );
            // draw a square with horizontal gradient filling
            PDFHorizontalGradientBrush hgb = new PDFHorizontalGradientBrush( );
            hgb.StartColor = new PDFColor( Color.CornflowerBlue );
            hgb.EndColor = new PDFColor( Color.Chartreuse );
            form2.Canvas.DrawRectangle2( redPen, hgb, 50, 50, 50, 50 );
            // draw text
            PDFFont font2 = new PDFFont( FontFace.Helvetica, 20 );
            font2.Bold = true;
            form2.Canvas.DrawText( pdf4net, font2, null, darkBlueBrush, 50, 50, 0, TextAlign.MiddleCenter );

            // draw the form xobject on the page.
            // no stretch
            page.Canvas.DrawFormXObject( form2, 100, 50, form2.Width, form2.Height );
            // stretch 200%
            page.Canvas.DrawFormXObject( form2, 100, 50 + form2.Height, 2*form2.Width, 2*form2.Height );
            // stretch 400%
            page.Canvas.DrawFormXObject( form2, 100, 50 + form2.Height + 2*form2.Height, 4*form2.Width, 4*form2.Height );

            // Save the document to disk
            doc.SaveToFile( "formxobject.pdf" );
        }
    }
}


FormXObject.vb

'
' File name: FormXObject.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Actions
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to use form XObjects with PDF4NET.
'/ </summary>

Class FormXObject
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument

        ' Create one page
        Dim page As PDFPage = doc.AddPage()

        Dim redPen As New PDFPen(New PDFColor(255, 0, 0), 1)
        Dim darkBlueBrush As New PDFBrush(New PDFColor(0, 0, 128))

        ' create a form XObject for stretched text
        Dim font As New PDFFont(FontFace.Helvetica, 16)
        Dim pdf4net As String = "PDF4NET"
        ' the size of form xobject matches the text
        Dim form As New PDFFormXObject
        form.Width = font.MeasureString(pdf4net)
        form.Height = 16
        ' draw the text on the form xobject
        form.Canvas.DrawText(pdf4net, font, Nothing, darkBlueBrush, 0, 0)

        ' draw the form xobject on the page.
        ' strectch it to cover the whole page header and on the left margin
        page.Canvas.DrawFormXObject(form, 0, 0, page.Width, 24)
        page.Canvas.DrawFormXObject(form, 32, 0, page.Height, 32, -90)

        ' create another for xobject that is more complex
        Dim form2 As New PDFFormXObject
        form2.Width = 100
        form2.Height = 100
        ' create the form content
        ' draw an image
        form2.Canvas.DrawImage("target.gif", 0, 0, 50, 50)
        ' draw a round rectangle filled with a hatched brush
        Dim hb As New PDFHatchBrush(HatchType.DiagonalCross)
        hb.HatchColor = New PDFColor(Color.CornflowerBlue)
        form2.Canvas.DrawRoundRectangle(redPen, hb, 50, 0, 50, 50, 20, 20)
        ' draw a square with vertical gradient filling
        Dim vgb As New PDFVerticalGradientBrush
        vgb.StartColor = New PDFColor(Color.Crimson)
        vgb.EndColor = New PDFColor(Color.GreenYellow)
        form2.Canvas.DrawRectangle2(redPen, vgb, 0, 50, 50, 50)
        ' draw a square with horizontal gradient filling
        Dim hgb As New PDFHorizontalGradientBrush
        hgb.StartColor = New PDFColor(Color.CornflowerBlue)
        hgb.EndColor = New PDFColor(Color.Chartreuse)
        form2.Canvas.DrawRectangle2(redPen, hgb, 50, 50, 50, 50)
        ' draw text
        Dim font2 As New PDFFont(FontFace.Helvetica, 20)
        font2.Bold = True
        form2.Canvas.DrawText(pdf4net, font2, Nothing, darkBlueBrush, 50, 50, 0, TextAlign.MiddleCenter)

        ' draw the form xobject on the page.
        ' no stretch
        page.Canvas.DrawFormXObject(form2, 100, 50, form2.Width, form2.Height)
        ' stretch 200%
        page.Canvas.DrawFormXObject(form2, 100, 50 + form2.Height, 2 * form2.Width, 2 * form2.Height)
        ' stretch 400%
        page.Canvas.DrawFormXObject(form2, 100, 50 + form2.Height + 2 * form2.Height, 4 * form2.Width, 4 * form2.Height)

        ' Save the document to disk
        doc.SaveToFile("formxobject.pdf")
    End Sub 'Main
End Class 'FormXObject


Samples: GroupingGrid

Samples

GroupingGrid

This sample shows how to draw a complex report with grouping capabilites. It loads the data from an XML file, then draws the lines of the report. The lines of the report are grouped by client id. Each time a new group starts, a group header is drawn, and each time a group ends a group footer is drawn. This sample uses customerorders.xml file found in \bin folder.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


GroupingGrid.cs

/// <fileName>
/// File name: GroupingGrid.cs
/// </fileName>

using System;
using System.Drawing;
using System.Data;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.GroupingGrid
{
    /// <summary>
    /// This sample will show how to draw a complex report
    /// with groping using content from a database/xml file.
    /// </summary>
    class GroupingGrid
    {
        private static float leftMargin = 15;
        private static float rightMargin = 15;
        private static float topMargin = 20;
        private static float minBottomMargin = 20;
        private static float rowHeight = 20;
        private static float groupHeaderHeight = 20;
        private static float groupFooterHeight = 20;
        private static float headerHeight = 30;
        private static float firstPageTopOffset = 50;
        private static float[] columnsWidth = { 50, 80, 80, 170, 222, 100, 60 };
        private static string[] columnsHeader = { "Order ID", "Order date", "Shipped date", "Ship to",
                                                    "Address", "City", "Country" };

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the graphic objects
            PDFFont fontTitle = new PDFFont( FontFace.Helvetica, 20 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );
            // Set the document to be Landscape oriented
            pdfDoc.PageOrientation = PageOrientation.Landscape;

            // Create first page of the report
            PDFPage page = pdfDoc.AddPage( );

            // Draw the title of the report
            page.Canvas.DrawText( "Orders for customers", fontTitle, null, blackBrush,
                page.Width/2, 15, 0, TextAlign.TopCenter );

            // Draw report header
            DrawReportHeader( page, firstPageTopOffset );

            // Create the dataset
            DataSet ds = new DataSet( );

            // Load the dataset
            ds.ReadXml( "customersorders.xml", XmlReadMode.ReadSchema );

            // Get the table from the dataset
            DataTable co = ds.Tables[0];

            // rowOffset - specifies the vertical position where a row
            // should begin to be printed
            float rowOffset = firstPageTopOffset + headerHeight;
            // initial customer code
            string customerID = "";
            int ordersCount = 0;

            // draw the rows in the dataset
            for( int i = 0; i < co.Rows.Count; i++ )
            {
                // new customer, we need to draw the group header
                if( customerID != co.Rows[i][0].ToString( ) )
                {
                    if( customerID != "" )
                    { // draw the footer for the previous group
                        if( rowOffset + groupFooterHeight > page.Height - minBottomMargin )
                        { // not enough space to draw the footer
                            // create a new page
                            page = pdfDoc.AddPage( );

                            // draw the report header
                            DrawReportHeader( page, topMargin );

                            // adjust the position for next prints
                            rowOffset = topMargin + headerHeight;
                        }
                        // draw the group header
                        DrawGroupFooter( page, rowOffset, customerID, ordersCount );

                        // Adjust the position of the next row
                        rowOffset = rowOffset + groupFooterHeight;
                    }

                    // do we has enough space to draw the group header and at least one row?
                    if( rowOffset + groupHeaderHeight + rowHeight > page.Height - minBottomMargin )
                    { // not enough
                        // create a new page
                        page = pdfDoc.AddPage( );

                        // draw the report header
                        DrawReportHeader( page, topMargin );

                        // adjust the position of next rows
                        rowOffset = topMargin + headerHeight;
                    }

                    // draw the group header
                    DrawGroupHeader( page, rowOffset, co.Rows[i] );

                    // Adjust the position of the next row
                    rowOffset = rowOffset + groupHeaderHeight;
                    customerID = co.Rows[i][0].ToString( );
                    // reset customer's orders count
                    ordersCount = 0;
                }

                if( rowOffset + rowHeight > page.Height - minBottomMargin )
                { // not enough space to draw a new row, then create a new page,
                    // draw the header, then draw the rows.
                    page = pdfDoc.AddPage( );
                    DrawReportHeader( page, topMargin );
                    rowOffset = topMargin + headerHeight;
                }
                DrawReportRow( page, rowOffset, co.Rows[i] );
                rowOffset = rowOffset + rowHeight;
                ordersCount++;
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "groupinggrid.pdf" );
        }

        private static void DrawReportHeader( PDFPage pdfPage, float topOffset )
        {
            // Create the graphic objects
            PDFFont fontHeader = new PDFFont( FontFace.Helvetica, 12 );
            fontHeader.Bold = true;
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush headerFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw the header
            pdfPage.Canvas.DrawRectangle( borderColor, headerFill, topOffset, leftMargin,
                pdfPage.Width - leftMargin - rightMargin, headerHeight );

            int i;
            float xOffset = leftMargin;
            // Draw the columns separators
            for( i = 0; i < columnsWidth.Length - 1; i++ )
            {
                xOffset = xOffset + columnsWidth[i];
                pdfPage.Canvas.DrawLine( borderColor, xOffset, topOffset,
                    xOffset, topOffset + headerHeight );
            }

            xOffset = leftMargin;
            // Draw the columns header
            for( i = 0; i < columnsWidth.Length; i++ )
            {
                pdfPage.Canvas.DrawText( columnsHeader[i], fontHeader, null, textColor,
                    xOffset + columnsWidth[i]/2, topOffset + headerHeight/2, 0, TextAlign.MiddleCenter );
                xOffset = xOffset + columnsWidth[i];
            }
        }

        private static void DrawReportRow( PDFPage pdfPage, float topOffset, DataRow row )
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 10 );
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush headerFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw rows borders
            PointF[] points = { new PointF( leftMargin, topOffset ),
                                  new PointF( leftMargin, topOffset + rowHeight),
                                  new PointF( pdfPage.Width - rightMargin, topOffset + rowHeight ),
                                  new PointF( pdfPage.Width - rightMargin, topOffset )};
            pdfPage.Canvas.DrawLines( borderColor, points );

            int i;
            float xOffset = leftMargin;
            // Draw the columns separators
            for( i = 0; i < columnsWidth.Length - 1; i++ )
            {
                xOffset = xOffset + columnsWidth[i];
                pdfPage.Canvas.DrawLine( borderColor, xOffset, topOffset,
                    xOffset, topOffset + rowHeight );
            }

            xOffset = leftMargin;
            // Draw the columns values
            // Order id
            pdfPage.Canvas.DrawText( row[2].ToString( ), fontText, null, textColor,
                xOffset + 2, topOffset + rowHeight/2, 0, TextAlign.MiddleLeft );
            xOffset = xOffset + columnsWidth[0];
            // Order date
            DateTime date;
            if( row[3] != System.DBNull.Value )
            {
                date = ( DateTime )row[3];
                pdfPage.Canvas.DrawText( date.ToString( "MM/dd/yyyy" ), fontText, null, textColor,
                    xOffset + columnsWidth[1]/2, topOffset + rowHeight/2, 0, TextAlign.MiddleCenter );
            }
            xOffset = xOffset + columnsWidth[1];
            // Shipped date
            if( row[4] != System.DBNull.Value )
            {
                date = ( DateTime )row[4];
                pdfPage.Canvas.DrawText( date.ToString( "MM/dd/yyyy" ), fontText, null, textColor,
                    xOffset + columnsWidth[2]/2, topOffset + rowHeight/2, 0, TextAlign.MiddleCenter );
            }
            xOffset = xOffset + columnsWidth[2];
            // Ship to
//            pdfPage.Canvas.DrawTextBox( row[5].ToString( ), fontText, null, textColor,
//                xOffset + 2, topOffset, columnsWidth[3], rowHeight, 0, TextAlign.MiddleLeft );
            pdfPage.Canvas.DrawText( row[5].ToString( ), fontText, null, textColor,
                xOffset + 2, topOffset + rowHeight/2, 0, TextAlign.MiddleLeft );
            xOffset = xOffset + columnsWidth[3];
            // Address
            pdfPage.Canvas.DrawText( row[6].ToString( ), fontText, null, textColor,
                xOffset + 2, topOffset + rowHeight/2, 0, TextAlign.MiddleLeft );
            xOffset = xOffset + columnsWidth[4];
            // City
            pdfPage.Canvas.DrawText( row[7].ToString( ), fontText, null, textColor,
                xOffset + 2, topOffset + rowHeight/2, 0, TextAlign.MiddleLeft );
            xOffset = xOffset + columnsWidth[5];
            // Country
            pdfPage.Canvas.DrawText( row[8].ToString( ), fontText, null, textColor,
                xOffset + 2, topOffset + rowHeight/2, 0, TextAlign.MiddleLeft );
            xOffset = xOffset + columnsWidth[6];
        }

        private static void DrawGroupHeader( PDFPage pdfPage, float topOffset, DataRow row )
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush groupFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw group header
            pdfPage.Canvas.DrawRectangle( borderColor, groupFill, topOffset, leftMargin,
                pdfPage.Width - leftMargin - rightMargin, groupHeaderHeight );

            // Draw the content of the header
            pdfPage.Canvas.DrawText( "Customer ID: " + row[0].ToString( ) +
                " / Company name: " + row[1].ToString( ), fontText, null, textColor,
                leftMargin + 2, topOffset + groupHeaderHeight/2, 0, TextAlign.MiddleLeft );
        }

        private static void DrawGroupFooter( PDFPage pdfPage, float topOffset,
            string customerID, int totalOrders )
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush groupFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw group header
            pdfPage.Canvas.DrawRectangle( borderColor, groupFill, topOffset, leftMargin,
                pdfPage.Width - leftMargin - rightMargin, groupFooterHeight );

            // Draw the content of the header
            pdfPage.Canvas.DrawText( "Total number of orders for customer " + customerID +
                " is " + totalOrders.ToString( ), fontText, null, textColor,
                leftMargin + 2, topOffset + groupFooterHeight/2, 0, TextAlign.MiddleLeft );
        }
    }
}


GroupingGrid.vb

'
' File name: GroupingGrid.vb
'

Imports System
Imports System.Drawing
Imports System.Data
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.GroupingGrid
    '/ <summary>
    '/ This sample will show how to draw a complex report
    '/ with groping using content from a database/xml file.
    '/ </summary>
    Class GroupingGrid
        Private Shared leftMargin As Single = 15
        Private Shared rightMargin As Single = 15
        Private Shared topMargin As Single = 20
        Private Shared minBottomMargin As Single = 20
        Private Shared rowHeight As Single = 20
        Private Shared groupHeaderHeight As Single = 20
        Private Shared groupFooterHeight As Single = 20
        Private Shared headerHeight As Single = 30
        Private Shared firstPageTopOffset As Single = 50
        Private Shared columnsWidth As Single() = {50, 80, 80, 170, 222, 100, 60}
        Private Shared columnsHeader As String() = {"Order ID", "Order date", "Shipped date", "Ship to", "Address", "City", "Country"}

        Shared Sub Main()
            ' Create the graphic objects
            Dim fontTitle As New PDFFont(FontFace.Helvetica, 20)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()
            ' Set the document to be Landscape oriented
            pdfDoc.PageOrientation = PageOrientation.Landscape

            ' Create first page of the report
            Dim page As PDFPage = pdfDoc.AddPage()

            ' Draw the title of the report
            page.Canvas.DrawText("Orders for customers", fontTitle, Nothing, blackBrush, page.Width / 2, 15, 0, TextAlign.TopCenter)

            ' Draw report header
            DrawReportHeader(page, firstPageTopOffset)

            ' Create the dataset
            Dim ds As New DataSet()

            ' Load the dataset
            ds.ReadXml("customersorders.xml", XmlReadMode.ReadSchema)

            ' Get the table from the dataset
            Dim co As DataTable = ds.Tables(0)

            ' rowOffset - specifies the vertical position where a row
            ' should begin to be printed
            Dim rowOffset As Single = firstPageTopOffset + headerHeight
            ' initial customer code
            Dim customerID As String = ""
            Dim ordersCount As Integer = 0

            ' draw the rows in the dataset
            Dim i As Integer
            For i = 0 To co.Rows.Count - 1
                ' new customer, we need to draw the group header
                If customerID <> co.Rows(i)(0).ToString() Then
                    If customerID <> "" Then
                        ' draw the footer for the previous group
                        If rowOffset + groupFooterHeight > page.Height - minBottomMargin Then
                            ' not enough space to draw the footer
                            ' create a new page
                            page = pdfDoc.AddPage()

                            ' draw the report header
                            DrawReportHeader(page, topMargin)

                            ' adjust the position for next prints
                            rowOffset = topMargin + headerHeight
                        End If
                        ' draw the group header
                        DrawGroupFooter(page, rowOffset, customerID, ordersCount)

                        ' Adjust the position of the next row
                        rowOffset = rowOffset + groupFooterHeight
                    End If

                    ' do we has enough space to draw the group header and at least one row?
                    If rowOffset + groupHeaderHeight + rowHeight > page.Height - minBottomMargin Then
                        ' not enough
                        ' create a new page
                        page = pdfDoc.AddPage()

                        ' draw the report header
                        DrawReportHeader(page, topMargin)

                        ' adjust the position of next rows
                        rowOffset = topMargin + headerHeight
                    End If

                    ' draw the group header
                    DrawGroupHeader(page, rowOffset, co.Rows(i))

                    ' Adjust the position of the next row
                    rowOffset = rowOffset + groupHeaderHeight
                    customerID = co.Rows(i)(0).ToString()
                    ' reset customer's orders count
                    ordersCount = 0
                End If

                If rowOffset + rowHeight > page.Height - minBottomMargin Then
                    ' not enough space to draw a new row, then create a new page,
                    ' draw the header, then draw the rows.
                    page = pdfDoc.AddPage()
                    DrawReportHeader(page, topMargin)
                    rowOffset = topMargin + headerHeight
                End If
                DrawReportRow(page, rowOffset, co.Rows(i))
                rowOffset = rowOffset + rowHeight
                ordersCount += 1
            Next i

            ' Save the document to disk
            pdfDoc.SaveToFile("groupinggrid.pdf")
        End Sub 'Main

        Private Shared Sub DrawReportHeader(ByVal pdfPage As PDFPage, ByVal topOffset As Single)
            ' Create the graphic objects
            Dim fontHeader As New PDFFont(FontFace.Helvetica, 12)
            fontHeader.Bold = True
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim headerFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw the header
            pdfPage.Canvas.DrawRectangle(borderColor, headerFill, topOffset, leftMargin, pdfPage.Width - leftMargin - rightMargin, headerHeight)

            Dim i As Integer
            Dim xOffset As Single = leftMargin
            ' Draw the columns separators
            For i = 0 To (columnsWidth.Length - 1) - 1
                xOffset = xOffset + columnsWidth(i)
                pdfPage.Canvas.DrawLine(borderColor, xOffset, topOffset, xOffset, topOffset + headerHeight)
            Next i

            xOffset = leftMargin
            ' Draw the columns header
            For i = 0 To columnsWidth.Length - 1
                pdfPage.Canvas.DrawText(columnsHeader(i), fontHeader, Nothing, textColor, xOffset + columnsWidth(i) / 2, topOffset + headerHeight / 2, 0, TextAlign.MiddleCenter)
                xOffset = xOffset + columnsWidth(i)
            Next i
        End Sub 'DrawReportHeader

        Private Shared Sub DrawReportRow(ByVal pdfPage As PDFPage, ByVal topOffset As Single, ByVal row As DataRow)
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 10)
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim headerFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw rows borders
            Dim points As PointF() = {New PointF(leftMargin, topOffset), New PointF(leftMargin, topOffset + rowHeight), New PointF(pdfPage.Width - rightMargin, topOffset + rowHeight), New PointF(pdfPage.Width - rightMargin, topOffset)}
            pdfPage.Canvas.DrawLines(borderColor, points)

            Dim i As Integer
            Dim xOffset As Single = leftMargin
            ' Draw the columns separators
            For i = 0 To (columnsWidth.Length - 1) - 1
                xOffset = xOffset + columnsWidth(i)
                pdfPage.Canvas.DrawLine(borderColor, xOffset, topOffset, xOffset, topOffset + rowHeight)
            Next i

            xOffset = leftMargin
            ' Draw the columns values
            ' Order id
            pdfPage.Canvas.DrawText(row(2).ToString(), fontText, Nothing, textColor, xOffset + 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleLeft)
            xOffset = xOffset + columnsWidth(0)
            ' Order date
            Dim [date] As DateTime
            If Not (row(3) Is System.DBNull.Value) Then
                [date] = CType(row(3), DateTime)
                pdfPage.Canvas.DrawText([date].ToString("MM/dd/yyyy"), fontText, Nothing, textColor, xOffset + columnsWidth(1) / 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleCenter)
            End If
            xOffset = xOffset + columnsWidth(1)
            ' Shipped date
            If Not (row(4) Is System.DBNull.Value) Then
                [date] = CType(row(4), DateTime)
                pdfPage.Canvas.DrawText([date].ToString("MM/dd/yyyy"), fontText, Nothing, textColor, xOffset + columnsWidth(2) / 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleCenter)
            End If
            xOffset = xOffset + columnsWidth(2)
            ' Ship to
            '            pdfPage.Canvas.DrawTextBox( row[5].ToString( ), fontText, null, textColor,
            '                xOffset + 2, topOffset, columnsWidth[3], rowHeight, 0, TextAlign.MiddleLeft );
            pdfPage.Canvas.DrawText(row(5).ToString(), fontText, Nothing, textColor, xOffset + 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleLeft)
            xOffset = xOffset + columnsWidth(3)
            ' Address
            pdfPage.Canvas.DrawText(row(6).ToString(), fontText, Nothing, textColor, xOffset + 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleLeft)
            xOffset = xOffset + columnsWidth(4)
            ' City
            pdfPage.Canvas.DrawText(row(7).ToString(), fontText, Nothing, textColor, xOffset + 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleLeft)
            xOffset = xOffset + columnsWidth(5)
            ' Country
            pdfPage.Canvas.DrawText(row(8).ToString(), fontText, Nothing, textColor, xOffset + 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleLeft)
            xOffset = xOffset + columnsWidth(6)
        End Sub 'DrawReportRow

        Private Shared Sub DrawGroupHeader(ByVal pdfPage As PDFPage, ByVal topOffset As Single, ByVal row As DataRow)
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim groupFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw group header
            pdfPage.Canvas.DrawRectangle(borderColor, groupFill, topOffset, leftMargin, pdfPage.Width - leftMargin - rightMargin, groupHeaderHeight)

            ' Draw the content of the header
            pdfPage.Canvas.DrawText("Customer ID: " + row(0).ToString() + " / Company name: " + row(1).ToString(), fontText, Nothing, textColor, leftMargin + 2, topOffset + groupHeaderHeight / 2, 0, TextAlign.MiddleLeft)
        End Sub 'DrawGroupHeader

        Private Shared Sub DrawGroupFooter(ByVal pdfPage As PDFPage, ByVal topOffset As Single, ByVal customerID As String, ByVal totalOrders As Integer)
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim groupFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw group header
            pdfPage.Canvas.DrawRectangle(borderColor, groupFill, topOffset, leftMargin, pdfPage.Width - leftMargin - rightMargin, groupFooterHeight)

            ' Draw the content of the header
            pdfPage.Canvas.DrawText("Total number of orders for customer " + customerID + " is " + totalOrders.ToString(), fontText, Nothing, textColor, leftMargin + 2, topOffset + groupFooterHeight / 2, 0, TextAlign.MiddleLeft)
        End Sub 'DrawGroupFooter
    End Class 'GroupingGrid
End Namespace 'O2S.Samples.PDF4NET.GroupingGrid


Samples: HelloWorld

Samples

HelloWorld

This sample is the simplest pdf file. It draws the string "Hello World" in the center of the page. The text has a red border and it is filled with blue.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


HelloWorld.cs

/// <fileName>
/// File name: HelloWorld.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.HelloWorld
{
    /// <summary>
    /// The classic Hello world sample.
    /// </summary>
    class HelloWorld
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create one page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Draw "Hello world" in the center of the page
            pdfPage.Canvas.DrawText( "Hello world !",
                new PDFFont( FontFace.Helvetica, 100 ), new PDFPen( new PDFColor( 255, 0, 0 ), 1 ),
                new PDFBrush( new PDFColor( 0, 0, 255 ) ), pdfPage.Width/2, pdfPage.Height/2,
                0, TextAlign.MiddleCenter );

            // Save the document to disk
            pdfDoc.SaveToFile( "helloworld.pdf" );
        }
    }
}


HelloWorld.vb

'
' File name: HelloWorld.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.HelloWorld
    '/ <summary>
    '/ The classic Hello world sample.
    '/ </summary>
    Class HelloWorld

        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create one page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Draw "Hello world" in the center of the page
            pdfPage.Canvas.DrawText("Hello world !", New PDFFont(FontFace.Helvetica, 100), New PDFPen(New PDFColor(255, 0, 0), 1), New PDFBrush(New PDFColor(0, 0, 255)), pdfPage.Width / 2, pdfPage.Height / 2, 0, TextAlign.MiddleCenter)

            ' Save the document to disk
            pdfDoc.SaveToFile("helloworld.pdf")
        End Sub 'Main
    End Class 'HelloWorld
End Namespace 'O2S.Samples.PDF4NET.HelloWorld


Samples: Images

Samples

Images

This sample shows how to draw images on a page. It draws a normal image, then it draws another image that is rotated with 30 degrees around the top left corner.
The sample also demonstrates the image transparency capabilities in PDF4NET library. Color keys masking, image masks and alpha channel transparency are shown. This sample uses pdf4net.jpg, pdf4net.png and o2solutions.jpg images found in \bin folder.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Images.cs

/// <fileName>
/// File name: Images.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Graphics.Shapes.Transparency;

namespace O2S.Samples.PDF4NET.Images
{
    /// <summary>
    /// This sample will show how to draw jpeg images on a page.
    /// </summary>
    class Images
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create first page
            PDFPage page = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Draw a label
            page.Canvas.DrawText( "Normal image", fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Draw the image
            page.Canvas.DrawImage( "pdf4net.jpg", 20, 35, 467, 200, 0, KeepAspectRatio.KeepWidth );

            // Draw the image
            page.Canvas.DrawImage( "pdf4net.jpg", 20, 250, 467, 200, 0, KeepAspectRatio.KeepWidth );

            // Draw a label
            page.Canvas.DrawText( "30 degrees rotated image",
                fontText, null, blackBrush, 20, 300, 0, TextAlign.TopLeft );

            // Draw the image
            page.Canvas.DrawImage( "o2solutions.jpg", 20, 435, 444, 126.85F, 30, KeepAspectRatio.KeepWidth );

            // Create second page
            page = pdfDoc.AddPage( );

            // Draw a label
            page.Canvas.DrawText( "Image with a transparent color",
                fontText, null, blackBrush, 20, 30, 0, TextAlign.TopLeft );

            // create an image object
            PDFImage img = new PDFImage( "pdf4net.jpg", 0, 0, 0, 0, 0 );
            img.KeepAspectRatio = KeepAspectRatio.KeepBoth;

            // set the transparent color
            // even opaque images can be made transparent
            // the color image mask allows to set a range of colors as tranparent, not only one color
            img.Mask = new PDFColorImageMask( new PDFColor( 220, 220, 220 ), new PDFColor( 220, 220, 220 ) );

            // Draw the image
            page.Canvas.DrawImage( img, 20, 40, 467, 200 );

            // Draw a label
            page.Canvas.DrawText( "Image with a mask, black color is transparent, white is opaque",
                fontText, null, blackBrush, 20, 250, 0, TextAlign.TopLeft );

            // create another image object
            img = new PDFImage( "pdf4net.jpg", 0, 0, 0, 0, 0 );
            img.KeepAspectRatio = KeepAspectRatio.KeepBoth;

            // set an image mask for this image
            img.Mask = new PDFImageMask( "mask.bmp" );

            // Draw the image
            page.Canvas.DrawImage( img, 20, 260, 467, 200 );

            // Create third page
            page = pdfDoc.AddPage( );

            // Draw a label
            page.Canvas.DrawText( "Image with alpha channel transparency (take a look at the rounded corners)",
                fontText, null, blackBrush, 20, 30, 0, TextAlign.TopLeft );

            PDFBrush greenBrush = new PDFBrush( new PDFColor( Color.GreenYellow ) );
            // Draw a green rectangle under the image to emphasize the alpha channel transparency
            page.Canvas.DrawRectangle2( greenBrush, 45, 45, 510, 325 );

            // create an image object
            PDFImage cc = new PDFImage( "pdf4net.png", 0, 0, 0, 0, 0 );
            cc.UseEmbeddedAlphaChannel = true;
            cc.KeepAspectRatio = KeepAspectRatio.KeepWidth;

            // Draw the image on green background
            page.Canvas.DrawImage( cc, 50, 50, 500, 200 );

            PDFBrush redBrush = new PDFBrush( new PDFColor( Color.RosyBrown ) );
            // Draw a rosy rectangle under the image to emphasize the alpha channel transparency
            page.Canvas.DrawRectangle2( redBrush, 45, 395, 510, 325 );

            // Draw the image on rosy background
            page.Canvas.DrawImage( cc, 50, 400, 500, 200 );

            // Save the document to disk
            pdfDoc.SaveToFile( "images.pdf" );
        }
    }
}


Images.vb

'
' File name: Images.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Graphics.Shapes.Transparency

'/ <summary>
'/ This sample will show how to draw jpeg images on a page.
'/ </summary>

Class Images
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim pdfDoc As New PDFDocument

        ' Create first page
        Dim page As PDFPage = pdfDoc.AddPage()

        ' Create the graphic objects
        Dim fontText As New PDFFont(FontFace.Helvetica, 12)
        Dim blackBrush As New PDFBrush(New PDFColor)

        ' Draw a label
        page.Canvas.DrawText("Normal image", fontText, Nothing, blackBrush, 20, 20, 0, TextAlign.TopLeft)

        ' Draw the image
        page.Canvas.DrawImage("pdf4net.jpg", 20, 35, 467, 200, 0, KeepAspectRatio.KeepWidth)

        ' Draw the image
        page.Canvas.DrawImage("pdf4net.jpg", 20, 250, 467, 200, 0, KeepAspectRatio.KeepWidth)

        ' Draw a label
        page.Canvas.DrawText("30 degrees rotated image", fontText, Nothing, blackBrush, 20, 300, 0, TextAlign.TopLeft)

        ' Draw the image
        page.Canvas.DrawImage("o2solutions.jpg", 20, 435, 444, 126.85F, 30, KeepAspectRatio.KeepWidth)

        ' Create second page
        page = pdfDoc.AddPage()

        ' Draw a label
        page.Canvas.DrawText("Image with a transparent color", fontText, Nothing, blackBrush, 20, 30, 0, TextAlign.TopLeft)

        ' create an image object
        Dim img As New PDFImage("pdf4net.jpg", 0, 0, 0, 0, 0)
        img.KeepAspectRatio = KeepAspectRatio.KeepBoth

        ' set the transparent color
        ' even opaque images can be made transparent
        ' the color image mask allows to set a range of colors as tranparent, not only one color
        img.Mask = New PDFColorImageMask(New PDFColor(220, 220, 220), New PDFColor(220, 220, 220))

        ' Draw the image
        page.Canvas.DrawImage(img, 20, 40, 467, 200)

        ' Draw a label
        page.Canvas.DrawText("Image with a mask, black color is transparent, white is opaque", fontText, Nothing, blackBrush, 20, 250, 0, TextAlign.TopLeft)

        ' create another image object
        img = New PDFImage("pdf4net.jpg", 0, 0, 0, 0, 0)
        img.KeepAspectRatio = KeepAspectRatio.KeepBoth

        ' set an image mask for this image
        img.Mask = New PDFImageMask("mask.bmp")

        ' Draw the image
        page.Canvas.DrawImage(img, 20, 260, 467, 200)

        ' Create third page
        page = pdfDoc.AddPage()

        ' Draw a label
        page.Canvas.DrawText("Image with alpha channel transparency (take a look at the rounded corners)", fontText, Nothing, blackBrush, 20, 30, 0, TextAlign.TopLeft)

        Dim greenBrush As New PDFBrush(New PDFColor(Color.GreenYellow))
        ' Draw a green rectangle under the image to emphasize the alpha channel transparency
        page.Canvas.DrawRectangle2(greenBrush, 45, 45, 510, 325)

        ' create an image object
        Dim cc As New PDFImage("pdf4net.png", 0, 0, 0, 0, 0)
        cc.UseEmbeddedAlphaChannel = True
        cc.KeepAspectRatio = KeepAspectRatio.KeepWidth

        ' Draw the image on green background
        page.Canvas.DrawImage(cc, 50, 50, 500, 200)

        Dim redBrush As New PDFBrush(New PDFColor(Color.RosyBrown))
        ' Draw a rosy rectangle under the image to emphasize the alpha channel transparency
        page.Canvas.DrawRectangle2(redBrush, 45, 395, 510, 325)

        ' Draw the image on rosy background
        page.Canvas.DrawImage(cc, 50, 400, 500, 200)

        ' Save the document to disk
        pdfDoc.SaveToFile("images.pdf")
    End Sub 'Main
End Class 'Images


Samples: Layers

Layers

Actions

This sample demonstrates the support for layers in a PDF file implemented in PDF4NET library. Unlimited levels of layers and sublayers can be created. The layers are stacked on top of each other in the order they were created.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Layers.cs

/// <fileName>
/// File name: Layers.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Layers
{
    /// <summary>
    /// The sample shows how to use layers in a PDF file.
    /// The PDF4NET library supports unlimited levels of nested layers.
    /// Each layers can be hidden or shown independently. Hidding a parent layer
    /// will hide all its child layers. Layers' content is always drawn on top of page content
    /// and they are drawn on top of each other in the order they have been added to the Layers collection.
    /// Page main content can not be hidden, it is always visible.
    /// </summary>
    class Layers
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Create one page
            PDFPage page = doc.AddPage( );

            PDFPen redPen = new PDFPen( new PDFColor( 192, 0, 0 ), 1 );
            PDFBrush blueBrush = new PDFBrush( new PDFColor( 0, 0, 255 ) );
            PDFBrush darkBlueBrush = new PDFBrush( new PDFColor( 0, 0, 128 ) );

            // Draw "Hello world" in the center of the page
            // this text is always visible.
            page.Canvas.DrawText( "Hello world !",
                new PDFFont( FontFace.Helvetica, 100 ), redPen, blueBrush, page.Width/2, page.Height/2,
                0, TextAlign.MiddleCenter );

            // Create a parent layer
            PDFLayer squareLayer = page.Canvas.Layers.Add( "Empty square" );
            // Create a poly polygon and draw it on the layer
            PDFPoint[][] polygons = new PDFPoint[2][];
            polygons[0] = new PDFPoint[]{ new PDFPoint( 50, 100 ), new PDFPoint( 550, 100 ),
                                            new PDFPoint( 550, 600 ), new PDFPoint( 50, 600 ) };
            polygons[1] = new PDFPoint[]{ new PDFPoint( 100, 150 ), new PDFPoint( 500, 150 ),
                                            new PDFPoint( 500, 550 ), new PDFPoint( 100, 550 ) };
            PDFPolyPolygon pp = new PDFPolyPolygon( redPen, darkBlueBrush, polygons );
            pp.FillMode = FillMode.EvenOdd;
            squareLayer.Canvas.Add( pp );

            // create 4 sublayers
            // 1. Hatched layer
            PDFLayer hatchedLayer = squareLayer.Canvas.Layers.Add( "Hatched square" );
            // Create a hatch brush
            PDFHatchBrush hb = new PDFHatchBrush( HatchType.DiagonalCross );
            hb.HatchColor = new PDFColor( Color.Aquamarine );
            hb.Color = new PDFColor( Color.Azure );
            hatchedLayer.Canvas.DrawRectangle2( redPen, hb, 100, 150, 200, 200 );

            // 2. Vertical gradient layer
            PDFLayer verticalGradientLayer = squareLayer.Canvas.Layers.Add( "Vertical gradient square" );
            // Create a vertical gradien brush
            PDFVerticalGradientBrush vgb = new PDFVerticalGradientBrush( );
            vgb.StartColor = new PDFColor( Color.Aquamarine );
            vgb.EndColor = new PDFColor( Color.Purple );
            verticalGradientLayer.Canvas.DrawRectangle2( redPen, vgb, 300, 150, 200, 200 );

            // 4. Horizontal gradient layer
            PDFLayer horizontalGradientLayer = squareLayer.Canvas.Layers.Add( "Horizontal gradient square" );
            // Create a horizontal gradient brush
            PDFHorizontalGradientBrush hgb = new PDFHorizontalGradientBrush( );
            hgb.StartColor = new PDFColor( Color.YellowGreen );
            hgb.EndColor = new PDFColor( Color.Violet );
            horizontalGradientLayer.Canvas.DrawRectangle2( redPen, hgb, 100, 350, 200, 200 );

            // 4. Solid layer
            PDFLayer solidLayer = squareLayer.Canvas.Layers.Add( "Solid square" );
            // Create a solid brush
            PDFBrush solidBrush = new PDFBrush( new PDFColor( Color.CornflowerBlue ) );
            solidLayer.Canvas.DrawRectangle2( redPen, solidBrush, 300, 350, 200, 200 );

            // create another layer on top of existing ones
            PDFLayer xLayer = page.Canvas.Layers.Add( "Green X" );
            PDFPen greenPen = new PDFPen( new PDFColor( Color.GreenYellow ), 32 );
            greenPen.LineCap = LineCap.Round;
            xLayer.Canvas.DrawLine( greenPen, 50, 100, 550, 600 );
            xLayer.Canvas.DrawLine( greenPen, 550, 100, 50, 600 );

            // Save the document to disk
            doc.SaveToFile( "layers.pdf" );
        }
    }
}


Layers.vb

'
' File name: Layers.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ The sample shows how to use layers in a PDF file.
'/ The PDF4NET library supports unlimited levels of nested layers.
'/ Each layers can be hidden or shown independently. Hidding a parent layer
'/ will hide all its child layers. Layers' content is always drawn on top of page content
'/ and they are drawn on top of each other in the order they have been added to the Layers collection.
'/ Page main content can not be hidden, it is always visible.
'/ </summary>

Class Layers
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument

        ' Create one page
        Dim page As PDFPage = doc.AddPage()

        Dim redPen As New PDFPen(New PDFColor(192, 0, 0), 1)
        Dim blueBrush As New PDFBrush(New PDFColor(0, 0, 255))
        Dim darkBlueBrush As New PDFBrush(New PDFColor(0, 0, 128))

        ' Draw "Hello world" in the center of the page
        ' this text is always visible.
        page.Canvas.DrawText("Hello world !", New PDFFont(FontFace.Helvetica, 100), redPen, blueBrush, page.Width / 2, page.Height / 2, 0, TextAlign.MiddleCenter)

        ' Create a parent layer
        Dim squareLayer As PDFLayer = page.Canvas.Layers.Add("Empty square")
        ' Create a poly polygon and draw it on the layer
        Dim polygons(1)() As PDFPoint
        polygons(0) = New PDFPoint() {New PDFPoint(50, 100), New PDFPoint(550, 100), New PDFPoint(550, 600), New PDFPoint(50, 600)}
        polygons(1) = New PDFPoint() {New PDFPoint(100, 150), New PDFPoint(500, 150), New PDFPoint(500, 550), New PDFPoint(100, 550)}
        Dim pp As New PDFPolyPolygon(redPen, darkBlueBrush, polygons)
        pp.FillMode = FillMode.EvenOdd
        squareLayer.Canvas.Add(pp)

        ' create 4 sublayers
        ' 1. Hatched layer
        Dim hatchedLayer As PDFLayer = squareLayer.Canvas.Layers.Add("Hatched square")
        ' Create a hatch brush
        Dim hb As New PDFHatchBrush(HatchType.DiagonalCross)
        hb.HatchColor = New PDFColor(Color.Aquamarine)
        hb.Color = New PDFColor(Color.Azure)
        hatchedLayer.Canvas.DrawRectangle2(redPen, hb, 100, 150, 200, 200)

        ' 2. Vertical gradient layer
        Dim verticalGradientLayer As PDFLayer = squareLayer.Canvas.Layers.Add("Vertical gradient square")
        ' Create a vertical gradien brush
        Dim vgb As New PDFVerticalGradientBrush
        vgb.StartColor = New PDFColor(Color.Aquamarine)
        vgb.EndColor = New PDFColor(Color.Purple)
        verticalGradientLayer.Canvas.DrawRectangle2(redPen, vgb, 300, 150, 200, 200)

        ' 4. Horizontal gradient layer
        Dim horizontalGradientLayer As PDFLayer = squareLayer.Canvas.Layers.Add("Horizontal gradient square")
        ' Create a horizontal gradient brush
        Dim hgb As New PDFHorizontalGradientBrush
        hgb.StartColor = New PDFColor(Color.YellowGreen)
        hgb.EndColor = New PDFColor(Color.Violet)
        horizontalGradientLayer.Canvas.DrawRectangle2(redPen, hgb, 100, 350, 200, 200)

        ' 4. Solid layer
        Dim solidLayer As PDFLayer = squareLayer.Canvas.Layers.Add("Solid square")
        ' Create a solid brush
        Dim solidBrush As New PDFBrush(New PDFColor(Color.CornflowerBlue))
        solidLayer.Canvas.DrawRectangle2(redPen, solidBrush, 300, 350, 200, 200)

        ' create another layer on top of existing ones
        Dim xLayer As PDFLayer = page.Canvas.Layers.Add("Green X")
        Dim greenPen As New PDFPen(New PDFColor(Color.GreenYellow), 32)
        greenPen.LineCap = LineCap.Round
        xLayer.Canvas.DrawLine(greenPen, 50, 100, 550, 600)
        xLayer.Canvas.DrawLine(greenPen, 550, 100, 50, 600)

        ' Save the document to disk
        doc.SaveToFile("layers.pdf")
    End Sub 'Main
End Class 'Layers


Samples: Lines

Samples

Lines

This sample shows the lines drawing capabilites. On the first page it draws random positioned lines, the second page demonstrates the LineCap and LineJoin properties, and on the third page it draws a spiral using an array of consecutive line segments.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Lines.cs

/// <fileName>
/// File name: Lines.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Lines
{
    /// <summary>
    /// This sample will show various types of lines.
    /// </summary>
    class Lines
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            DrawFirstPage( pdfDoc );
            DrawSecondPage( pdfDoc );
            DrawThirdPage( pdfDoc );

            // Save the document to disk
            pdfDoc.SaveToFile( "lines.pdf" );
        }

        private static void DrawFirstPage( PDFDocument pdfDoc )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            Random rnd = new Random( );
            for( int i = 0; i < 50; i++ )
            {
                // Create random colors for drawing the spline
                PDFColor penColor = new PDFColor( ( byte )rnd.Next( 256 ),
                    ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );

                // Create the pen to draw the border
                PDFPen randomPen = new PDFPen( penColor, 1 );

                // Generate random control points
                float x1 = rnd.Next( ( int )pdfPage.Width );
                float y1 = rnd.Next( ( int )pdfPage.Height );
                float x2 = rnd.Next( ( int )pdfPage.Width );
                float y2 = rnd.Next( ( int )pdfPage.Height );

                // Draw the line
                pdfPage.Canvas.DrawLine( randomPen, x1, y1, x2, y2 );
            }

            // Draw a label
            pdfPage.Canvas.DrawText( "Random lines",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );
        }

        private static void DrawSecondPage( PDFDocument pdfDoc )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 16 );
            fontText.Bold = true;
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFPen thinPen = new PDFPen( new PDFColor( ), 1 );

            // Draw the line caps
            // Flat line cap
            PDFPen thickFlatPen = new PDFPen( new PDFColor( Color.Orange ), 15 );
            thickFlatPen.LineCap = LineCap.Flat;
            pdfPage.Canvas.DrawText( "Line cap: Flat",
                fontText, null, blackBrush, 20, 25, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( thickFlatPen, 200, 30, 400, 30 );
            pdfPage.Canvas.DrawLine( thinPen, 200, 30, 400, 30 );

            // Round line cap
            PDFPen thickRoundPen = new PDFPen( new PDFColor( Color.Orange ), 15 );
            thickRoundPen.LineCap = LineCap.Round;
            pdfPage.Canvas.DrawText( "Line cap: Round",
                fontText, null, blackBrush, 20, 55, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( thickRoundPen, 200, 60, 400, 60 );
            pdfPage.Canvas.DrawLine( thinPen, 200, 60, 400, 60 );

            // Square line cap
            PDFPen thickSquarePen = new PDFPen( new PDFColor( Color.Orange ), 15 );
            thickSquarePen.LineCap = LineCap.Square;
            pdfPage.Canvas.DrawText( "Line cap: Square",
                fontText, null, blackBrush, 20, 85, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( thickSquarePen, 200, 90, 400, 90 );
            pdfPage.Canvas.DrawLine( thinPen, 200, 90, 400, 90 );

            // Draw the line joins
            // Miter join
            PDFPoint[] pointsMiter = { new PDFPoint( 200, 250 ), new PDFPoint( 300, 150 ), new PDFPoint( 400, 250 )};
            thickRoundPen.LineJoin = LineJoin.Miter;
            pdfPage.Canvas.DrawText( "Line join: Miter", fontText, null, blackBrush, 20, 200, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLines( thickRoundPen, pointsMiter );

            // Bevel join
            PDFPoint[] pointsBevel = { new PDFPoint( 200, 350 ), new PDFPoint( 300, 250 ), new PDFPoint( 400, 350 )};
            PDFPen thickRoundBevelPen = new PDFPen( new PDFColor( Color.Orange ), 15 );
            thickRoundBevelPen.LineCap = LineCap.Round;
            thickRoundBevelPen.LineJoin = LineJoin.Bevel;
            pdfPage.Canvas.DrawText( "Line join: Bevel", fontText, null, blackBrush, 20, 300, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLines( thickRoundBevelPen, pointsBevel );

            // Round join
            PDFPoint[] pointsRound = { new PDFPoint( 200, 450 ), new PDFPoint( 300, 350 ), new PDFPoint( 400, 450 )};
            PDFPen thickFlatRoundPen = new PDFPen( new PDFColor( Color.Orange ), 15 );
            thickFlatRoundPen.LineCap = LineCap.Round;
            thickFlatRoundPen.LineJoin = LineJoin.Round;
            pdfPage.Canvas.DrawText( "Line join: Round", fontText, null, blackBrush, 20, 400, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLines( thickFlatRoundPen, pointsRound );

            // Draw dash styles
            // Dash line style
            PDFPen dashPen = new PDFPen( new PDFColor( Color.Orange ), 1 );
            dashPen.DashStyle = DashStyle.Dash;
            pdfPage.Canvas.DrawText( "Dash style: Dash",
                fontText, null, blackBrush, 20, 500, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( dashPen, 200, 505, 400, 505 );

            // Dash dot line style
            PDFPen dashDotPen = new PDFPen( new PDFColor( Color.Orange ), 1 );
            dashDotPen.DashStyle = DashStyle.DashDot;
            pdfPage.Canvas.DrawText( "Dash style: DashDot",
                fontText, null, blackBrush, 20, 530, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( dashDotPen, 200, 535, 400, 535 );

            // Dash dot dot line style
            PDFPen dashDotDotPen = new PDFPen( new PDFColor( Color.Orange ), 1 );
            dashDotDotPen.DashStyle = DashStyle.DashDotDot;
            pdfPage.Canvas.DrawText( "Dash style: DashDot",
                fontText, null, blackBrush, 20, 560, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( dashDotDotPen, 200, 565, 400, 565 );

            // Dot line style
            PDFPen dotPen = new PDFPen( new PDFColor( Color.Orange ), 1 );
            dotPen.DashStyle = DashStyle.Dot;
            pdfPage.Canvas.DrawText( "Dash style: Dot",
                fontText, null, blackBrush, 20, 590, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( dotPen, 200, 595, 400, 595 );

            // Custom line style
            float[] dashPattern = {20, 5, 10, 5, 5, 5};
            PDFPen customPen = new PDFPen( new PDFColor( Color.Orange ), 1 );
            customPen.DashStyle = DashStyle.Custom;
            customPen.DashPattern = dashPattern;
            pdfPage.Canvas.DrawText( "Dash style: Custom",
                fontText, null, blackBrush, 20, 620, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawLine( customPen, 200, 625, 400, 625 );
        }

        private static void DrawThirdPage( PDFDocument pdfDoc )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Draw a label
            pdfPage.Canvas.DrawText( "Spiral lines",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            PDFPoint[] spiral = { new PDFPoint( 30, 30 ), new PDFPoint( 600, 30 ), new PDFPoint( 600, 700 ), new PDFPoint( 30, 700 ),
                                    new PDFPoint( 30, 60 ), new PDFPoint( 570, 60 ), new PDFPoint( 570, 670 ), new PDFPoint( 60, 670 ),
                                    new PDFPoint( 60, 90 ), new PDFPoint( 540, 90 ), new PDFPoint( 540, 640 ), new PDFPoint( 90, 640 ),
                                    new PDFPoint( 90, 120 ), new PDFPoint( 510, 120 ), new PDFPoint( 510, 610 ), new PDFPoint( 120, 610 ),
                                    new PDFPoint( 120, 150 ), new PDFPoint( 480, 150 ), new PDFPoint( 480, 580 ), new PDFPoint( 150, 580 ),
                                    new PDFPoint( 150, 180 ), new PDFPoint( 450, 180 ), new PDFPoint( 450, 550 ), new PDFPoint( 180, 550 ),
                                    new PDFPoint( 180, 210 ), new PDFPoint( 420, 210 ), new PDFPoint( 420, 520 ), new PDFPoint( 210, 520 ),
                                    new PDFPoint( 210, 240 ), new PDFPoint( 390, 240 ), new PDFPoint( 390, 490 ), new PDFPoint( 240, 490 ),
                                    new PDFPoint( 240, 270 ), new PDFPoint( 360, 270 ), new PDFPoint( 360, 460 ), new PDFPoint( 270, 460 ),
                                    new PDFPoint( 270, 300 ), new PDFPoint( 330, 300 ), new PDFPoint( 330, 430 ), new PDFPoint( 300, 430 ),
                                    new PDFPoint( 300, 330 ) };
            Random rnd = new Random( );
            // Create random color for drawing the line
            PDFColor penColor2 = new PDFColor( ( byte )rnd.Next( 256 ),
                ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );
            // Create the pen to draw the line
            PDFPen randomPen2 = new PDFPen( penColor2, 1 );

            pdfPage.Canvas.DrawLines( randomPen2, spiral );
        }
    }
}


Lines.vb

'
' File name: Lines.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.Lines
    '/ <summary>
    '/ This sample will show various types of lines.
    '/ </summary>
    Class Lines

        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            DrawFirstPage(pdfDoc)
            DrawSecondPage(pdfDoc)
            DrawThirdPage(pdfDoc)

            ' Save the document to disk
            pdfDoc.SaveToFile("lines.pdf")
        End Sub 'Main

        Private Shared Sub DrawFirstPage(ByVal pdfDoc As PDFDocument)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())

            Dim rnd As New Random()
            Dim i As Integer
            For i = 0 To 49
                ' Create random colors for drawing the spline
                Dim penColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))

                ' Create the pen to draw the border
                Dim randomPen As New PDFPen(penColor, 1)

                ' Generate random control points
                Dim x1 As Single = rnd.Next(CInt(pdfPage.Width))
                Dim y1 As Single = rnd.Next(CInt(pdfPage.Height))
                Dim x2 As Single = rnd.Next(CInt(pdfPage.Width))
                Dim y2 As Single = rnd.Next(CInt(pdfPage.Height))

                ' Draw the line
                pdfPage.Canvas.DrawLine(randomPen, x1, y1, x2, y2)
            Next i

            ' Draw a label
            pdfPage.Canvas.DrawText("Random lines", fontText, Nothing, blackBrush, 20, 20)
        End Sub 'DrawFirstPage

        Private Shared Sub DrawSecondPage(ByVal pdfDoc As PDFDocument)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 16)
            fontText.Bold = True
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim thinPen As New PDFPen(New PDFColor(), 1)

            ' Draw the line caps
            ' Flat line cap
            Dim thickFlatPen As New PDFPen(New PDFColor(Color.Orange), 15)
            thickFlatPen.LineCap = LineCap.Flat
            pdfPage.Canvas.DrawText("Line cap: Flat", fontText, Nothing, blackBrush, 20, 25)
            pdfPage.Canvas.DrawLine(thickFlatPen, 200, 30, 400, 30)
            pdfPage.Canvas.DrawLine(thinPen, 200, 30, 400, 30)

            ' Round line cap
            Dim thickRoundPen As New PDFPen(New PDFColor(Color.Orange), 15)
            thickRoundPen.LineCap = LineCap.Round
            pdfPage.Canvas.DrawText("Line cap: Round", fontText, Nothing, blackBrush, 20, 55)
            pdfPage.Canvas.DrawLine(thickRoundPen, 200, 60, 400, 60)
            pdfPage.Canvas.DrawLine(thinPen, 200, 60, 400, 60)

            ' Square line cap
            Dim thickSquarePen As New PDFPen(New PDFColor(Color.Orange), 15)
            thickSquarePen.LineCap = LineCap.Square
            pdfPage.Canvas.DrawText("Line cap: Square", fontText, Nothing, blackBrush, 20, 85)
            pdfPage.Canvas.DrawLine(thickSquarePen, 200, 90, 400, 90)
            pdfPage.Canvas.DrawLine(thinPen, 200, 90, 400, 90)

            ' Draw the line joins
            ' Miter join
            Dim pointsMiter As PointF() = {New PointF(200, 250), New PointF(300, 150), New PointF(400, 250)}
            thickRoundPen.LineJoin = LineJoin.Miter
            pdfPage.Canvas.DrawText("Line join: Miter", fontText, Nothing, blackBrush, 20, 200)
            pdfPage.Canvas.DrawLines(thickRoundPen, pointsMiter)

            ' Bevel join
            Dim pointsBevel As PointF() = {New PointF(200, 350), New PointF(300, 250), New PointF(400, 350)}
            Dim thickRoundBevelPen As New PDFPen(New PDFColor(Color.Orange), 15)
            thickRoundBevelPen.LineCap = LineCap.Round
            thickRoundBevelPen.LineJoin = LineJoin.Bevel
            pdfPage.Canvas.DrawText("Line join: Bevel", fontText, Nothing, blackBrush, 20, 300)
            pdfPage.Canvas.DrawLines(thickRoundBevelPen, pointsBevel)

            ' Round join
            Dim pointsRound As PointF() = {New PointF(200, 450), New PointF(300, 350), New PointF(400, 450)}
            Dim thickFlatRoundPen As New PDFPen(New PDFColor(Color.Orange), 15)
            thickFlatRoundPen.LineCap = LineCap.Round
            thickFlatRoundPen.LineJoin = LineJoin.Round
            pdfPage.Canvas.DrawText("Line join: Round", fontText, Nothing, blackBrush, 20, 400)
            pdfPage.Canvas.DrawLines(thickFlatRoundPen, pointsRound)

            ' Draw dash styles
            ' Dash line style
            Dim dashPen As New PDFPen(New PDFColor(Color.Orange), 1)
            dashPen.DashStyle = DashStyle.Dash
            pdfPage.Canvas.DrawText("Dash style: Dash", fontText, Nothing, blackBrush, 20, 500)
            pdfPage.Canvas.DrawLine(dashPen, 200, 505, 400, 505)

            ' Dash dot line style
            Dim dashDotPen As New PDFPen(New PDFColor(Color.Orange), 1)
            dashDotPen.DashStyle = DashStyle.DashDot
            pdfPage.Canvas.DrawText("Dash style: DashDot", fontText, Nothing, blackBrush, 20, 530)
            pdfPage.Canvas.DrawLine(dashDotPen, 200, 535, 400, 535)

            ' Dash dot dot line style
            Dim dashDotDotPen As New PDFPen(New PDFColor(Color.Orange), 1)
            dashDotDotPen.DashStyle = DashStyle.DashDotDot
            pdfPage.Canvas.DrawText("Dash style: DashDot", fontText, Nothing, blackBrush, 20, 560)
            pdfPage.Canvas.DrawLine(dashDotDotPen, 200, 565, 400, 565)

            ' Dot line style
            Dim dotPen As New PDFPen(New PDFColor(Color.Orange), 1)
            dotPen.DashStyle = DashStyle.Dot
            pdfPage.Canvas.DrawText("Dash style: Dot", fontText, Nothing, blackBrush, 20, 590)
            pdfPage.Canvas.DrawLine(dotPen, 200, 595, 400, 595)

            ' Custom line style
            Dim dashPattern As Single() = {20, 5, 10, 5, 5, 5}
            Dim customPen As New PDFPen(New PDFColor(Color.Orange), 1)
            customPen.DashStyle = DashStyle.Custom
            customPen.DashPattern = dashPattern
            pdfPage.Canvas.DrawText("Dash style: Custom", fontText, Nothing, blackBrush, 20, 620)
            pdfPage.Canvas.DrawLine(customPen, 200, 625, 400, 625)
        End Sub 'DrawSecondPage

        Private Shared Sub DrawThirdPage(ByVal pdfDoc As PDFDocument)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Draw a label
            pdfPage.Canvas.DrawText("Spiral lines", fontText, Nothing, blackBrush, 20, 20)

            Dim spiral As PointF() = {New PointF(30, 30), New PointF(600, 30), New PointF(600, 700), New PointF(30, 700), New PointF(30, 60), New PointF(570, 60), New PointF(570, 670), New PointF(60, 670), New PointF(60, 90), New PointF(540, 90), New PointF(540, 640), New PointF(90, 640), New PointF(90, 120), New PointF(510, 120), New PointF(510, 610), New PointF(120, 610), New PointF(120, 150), New PointF(480, 150), New PointF(480, 580), New PointF(150, 580), New PointF(150, 180), New PointF(450, 180), New PointF(450, 550), New PointF(180, 550), New PointF(180, 210), New PointF(420, 210), New PointF(420, 520), New PointF(210, 520), New PointF(210, 240), New PointF(390, 240), New PointF(390, 490), New PointF(240, 490), New PointF(240, 270), New PointF(360, 270), New PointF(360, 460), New PointF(270, 460), New PointF(270, 300), New PointF(330, 300), New PointF(330, 430), New PointF(300, 430), New PointF(300, 330)}
            Dim rnd As New Random()
            ' Create random color for drawing the line
            Dim penColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))
            ' Create the pen to draw the line
            Dim randomPen As New PDFPen(penColor, 1)

            pdfPage.Canvas.DrawLines(randomPen, spiral)
        End Sub 'DrawThirdPage
    End Class 'Lines
End Namespace 'O2S.Samples.PDF4NET.Lines


Samples: Links

Samples

Links

This sample shows how to create links in a page that point to other content. It shows all 4 types of links: internal links, external document links, file links and web links. For each type of link, an area link and a text link are created.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Links.cs

/// <fileName>
/// File name: Links.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Links
{
    /// <summary>
    /// This sample will show how to create links to internal
    /// and external elements.
    /// </summary>
    class Links
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // The default page size is letter
            const int width = 612;
            const int height = 792;

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFFont fontTitle = new PDFFont( FontFace.Helvetica, 72 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFPen blackPen = new PDFPen( new PDFColor( ), 1 );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Add 2 pages to the document
            PDFPage pdfPage1 = pdfDoc.AddPage( );
            PDFPage pdfPage2 = pdfDoc.AddPage( );

            // Create content for page1
            pdfPage1.Canvas.DrawText( "Rectangular area links", fontText,
                null, blackBrush, width/4, 20, 0, TextAlign.TopCenter );
            pdfPage1.Canvas.DrawText( "Text links", fontText,
                null, blackBrush, 3*width/4, 20, 0, TextAlign.TopCenter );
            pdfPage1.Canvas.DrawLine( blackPen, width/2, 20, width/2, height - 20 );

            // Draw the rectangular links
            // Web link
            pdfPage1.Canvas.DrawAreaWebLink( "http://www.o2sol.com/", 10, 30,
                width/2 - 30, 150, new PDFPen( new PDFColor( 0, 0, 255 ), 1 ) );
            pdfPage1.Canvas.DrawText( "web link", fontText, null, blackBrush, 15, 35, 0, TextAlign.TopLeft );
            // File link
            pdfPage1.Canvas.DrawAreaFileLink( "links.exe", 10, 200,
                width/2 - 30, 150, new PDFPen( new PDFColor( 255, 0, 0 ), 1 ) );
            pdfPage1.Canvas.DrawText( "file link", fontText, null, blackBrush, 15, 205, 0, TextAlign.TopLeft );
            // External pdf document link
            pdfPage1.Canvas.DrawAreaRemoteDocLink( "helloworld.pdf", 10, 400,
                width/2 - 30, 150, new PDFPen( new PDFColor( 0, 255, 0 ), 1 ) );
            pdfPage1.Canvas.DrawText( "external pdf file link", fontText, null, blackBrush, 15, 405, 0, TextAlign.TopLeft );
            // In document link
            pdfPage1.Canvas.DrawAreaDocLink( pdfPage2, 0, 10, 600,
                width/2 - 30, 150, new PDFPen( new PDFColor( ), 1 ) );
            pdfPage1.Canvas.DrawText( "in document link (click to go to next page)",
                fontText, null, blackBrush, 15, 605, 0, TextAlign.TopLeft );

            // Draw the text links
            // Web link
            pdfPage1.Canvas.DrawTextWebLink( "http://www.o2sol.com/", "Text web link",
                fontText, null, blackBrush, width/2 + 30, 35,
                TextAlign.TopLeft, new PDFPen( new PDFColor( ), 0 ) );
            // File link
            pdfPage1.Canvas.DrawTextFileLink( "links.exe", "Text file link",
                fontText, null, blackBrush, width/2 + 30, 205, TextAlign.TopLeft,
                new PDFPen( new PDFColor( ), 0 ) );
            // External pdf document link
            pdfPage1.Canvas.DrawTextRemoteDocLink( "helloworld.pdf", "Text external pdf document link",
                fontText, null, blackBrush, width/2 + 30, 405, TextAlign.TopLeft,
                new PDFPen( new PDFColor( ), 0 ) );
            // In document link
            pdfPage1.Canvas.DrawTextDocLink( pdfPage2, 0, "Text in document link (click to go to next page)",
                fontText, null, blackBrush, width/2 + 30, 605, TextAlign.TopLeft,
                new PDFPen( new PDFColor( ), 0 ) );

            pdfPage2.Canvas.DrawText( "This is page 2.",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Save the document to disk
            pdfDoc.SaveToFile( "links.pdf" );
        }
    }
}


Links.vb

'
' File name: Links.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.Links
    '/ <summary>
    '/ This sample will show how to create links to internal
    '/ and external elements.
    '/ </summary>
    Class Links

        Shared Sub Main()
            ' The default page size is letter
            Const width As Integer = 612
            Const height As Integer = 792

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim fontTitle As New PDFFont(FontFace.Helvetica, 72)
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim blackPen As New PDFPen(New PDFColor(), 1)

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Add 2 pages to the document
            Dim pdfPage1 As PDFPage = pdfDoc.AddPage()
            Dim pdfPage2 As PDFPage = pdfDoc.AddPage()

            ' Create content for page1
            pdfPage1.Canvas.DrawText("Rectangular area links", fontText, Nothing, blackBrush, width / 4, 20, 0, TextAlign.TopCenter)
            pdfPage1.Canvas.DrawText("Text links", fontText, Nothing, blackBrush, 3 * width / 4, 20, 0, TextAlign.TopCenter)
            pdfPage1.Canvas.DrawLine(blackPen, width / 2, 20, width / 2, height - 20)

            ' Draw the rectangular links
            ' Web link
            pdfPage1.Canvas.DrawAreaWebLink("http://www.o2sol.com/", 10, 30, width / 2 - 30, 150, New PDFPen(New PDFColor(0, 0, 255), 1))
            pdfPage1.Canvas.DrawText("web link", fontText, Nothing, blackBrush, 15, 35)
            ' File link
            pdfPage1.Canvas.DrawAreaFileLink("links.exe", 10, 200, width / 2 - 30, 150, New PDFPen(New PDFColor(255, 0, 0), 1))
            pdfPage1.Canvas.DrawText("file link", fontText, Nothing, blackBrush, 15, 205)
            ' External pdf document link
            pdfPage1.Canvas.DrawAreaRemoteDocLink("helloworld.pdf", 10, 400, width / 2 - 30, 150, New PDFPen(New PDFColor(0, 255, 0), 1))
            pdfPage1.Canvas.DrawText("external pdf file link", fontText, Nothing, blackBrush, 15, 405)
            ' In document link
            pdfPage1.Canvas.DrawAreaDocLink(pdfPage2, 0, 10, 600, width / 2 - 30, 150, New PDFPen(New PDFColor(), 1))
            pdfPage1.Canvas.DrawText("in document link (click to go to next page)", fontText, Nothing, blackBrush, 15, 605)

            ' Draw the text links
            ' Web link
            pdfPage1.Canvas.DrawTextWebLink("http://www.o2sol.com/", "Text web link", fontText, Nothing, blackBrush, width / 2 + 30, 35, TextAlign.TopLeft, New PDFPen(New PDFColor(), 0))
            ' File link
            pdfPage1.Canvas.DrawTextFileLink("links.exe", "Text file link", fontText, Nothing, blackBrush, width / 2 + 30, 205, TextAlign.TopLeft, New PDFPen(New PDFColor(), 0))
            ' External pdf document link
            pdfPage1.Canvas.DrawTextRemoteDocLink("helloworld.pdf", "Text external pdf document link", fontText, Nothing, blackBrush, width / 2 + 30, 405, TextAlign.TopLeft, New PDFPen(New PDFColor(), 0))
            ' In document link
            pdfPage1.Canvas.DrawTextDocLink(pdfPage2, 0, "Text in document link (click to go to next page)", fontText, Nothing, blackBrush, width / 2 + 30, 605, TextAlign.TopLeft, New PDFPen(New PDFColor(), 0))

            pdfPage2.Canvas.DrawText("This is page 2.", fontText, Nothing, blackBrush, 20, 20)

            ' Save the document to disk
            pdfDoc.SaveToFile("links.pdf")
        End Sub 'Main
    End Class 'Links
End Namespace 'O2S.Samples.PDF4NET.Links


Samples: Metafiles

Samples

Metafiles

This sample demonstrates the metafiles support implemented in PDF4NET library. Enhanced Windows Metafiles are converted to native PDF vector data when using PDFMetafile class. Metafiles can be scaled or rotated without losing their graphic quality.
Metafiles are stored as form XObjects to reduce the file size, and allowing the viewer to cache their graphic representation when the metafile is displayed multiple times in the same file.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Metafiles.cs

/// <fileName>
/// File name: Metafiles.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Metafiles
{
    /// <summary>
    /// This sample shows how to use metafiles in a PDF file.
    /// When using metafiles in this way, they are converted to PDF vector data
    /// thus keeping the graphic details, no matter the drawing size. If metafiles
    /// are used with DrawImage methods, they are converted to raster data thus resulting
    /// the stairs effect when zooming the PDF file.<br>
    /// The metafile data is stored only once in the PDF file
    /// and can be drawn multiple times.
    /// </summary>
    class Metafiles
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Create first page
            PDFPage page = doc.AddPage( );

            // Create a metafile object
            PDFMetafile mf = new PDFMetafile( "sample.emf" );

            page.Orientation = PageOrientation.Landscape;
            page.Canvas.DrawMetafile( mf, 10, 10, page.Width - 20, page.Height - 20, 0, KeepAspectRatio.KeepBoth );

            // Create second page
            page = doc.AddPage( );

            page.Orientation = PageOrientation.Landscape;
            page.Canvas.DrawMetafile( mf, 10, 10, page.Width/2 - 20, page.Height/2 - 20, 0, KeepAspectRatio.KeepBoth );
            page.Canvas.DrawMetafile( mf, page.Width/2 + 10, 10, page.Width/2 - 20, page.Height/2 - 20, 0, KeepAspectRatio.KeepBoth );
            page.Canvas.DrawMetafile( mf, 10, page.Height/2 + 10, page.Width/2 - 20, page.Height/2 - 20, 0, KeepAspectRatio.KeepBoth );
            page.Canvas.DrawMetafile( mf, page.Width/2 + 10, page.Height/2 + 10, page.Width/2 - 20, page.Height/2 - 20, 0, KeepAspectRatio.KeepBoth );

            // Save the document to disk
            doc.SaveToFile( "metafiles.pdf" );
        }
    }
}


Metafiles.vb

'
' File name: Metafiles.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to use metafiles in a PDF file.
'/ When using metafiles in this way, they are converted to PDF vector data
'/ thus keeping the graphic details, no matter the drawing size. If metafiles
'/ are used with DrawImage methods, they are converted to raster data thus resulting
'/ the stairs effect when zooming the PDF file.<br>
'/ The metafile data is stored only once in the PDF file
'/ and can be drawn multiple times.
'/ </summary>

Class Metafiles
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument

        ' Create first page
        Dim page As PDFPage = doc.AddPage()

        ' Create a metafile object
        Dim mf As New PDFMetafile("test.emf")

        page.Orientation = PageOrientation.Landscape
        page.Canvas.DrawMetafile(mf, 10, 10, page.Width - 20, page.Height - 20, 0, KeepAspectRatio.KeepBoth)

        ' Create second page
        page = doc.AddPage()

        page.Orientation = PageOrientation.Landscape
        page.Canvas.DrawMetafile(mf, 10, 10, page.Width / 2 - 20, page.Height / 2 - 20, 0, KeepAspectRatio.KeepBoth)
        page.Canvas.DrawMetafile(mf, page.Width / 2 + 10, 10, page.Width / 2 - 20, page.Height / 2 - 20, 0, KeepAspectRatio.KeepBoth)
        page.Canvas.DrawMetafile(mf, 10, page.Height / 2 + 10, page.Width / 2 - 20, page.Height / 2 - 20, 0, KeepAspectRatio.KeepBoth)
        page.Canvas.DrawMetafile(mf, page.Width / 2 + 10, page.Height / 2 + 10, page.Width / 2 - 20, page.Height / 2 - 20, 0, KeepAspectRatio.KeepBoth)

        ' Save the document to disk
        doc.SaveToFile("metafiles.pdf")
    End Sub 'Main
End Class 'Metafiles


Samples: Multicolumn Text and Images

Samples

Multicolumn Text and Images

This sample shows how to draw columnar text that flows over multiple pages. It also demonstrates HTML formatting capabilities of PDF4NET library.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


MultiColumnTextAndImages.cs

/// <fileName>
/// File name: MultiColumnTextAndImages.cs
/// </fileName>

using System;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.MultiColumnTextAndImages
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class MultiColumnTextAndImages
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            float leftMargin = 30;
            float topMargin = 30;
            float rightMargin = 30;
            float bottomMargin = 30;
            float columnSpace = 30;
            float columnCount = 2;
            float columnWidth = ( 612 - leftMargin - rightMargin - columnSpace )/2;//612 - width of Letter size in points
            float columnHeight = 792 - topMargin - bottomMargin;//792 - height of Letter size in points
            PDFBrush blackBrush = new PDFBrush( new PDFColor( 0, 0, 0 ) );
            PDFFont font = new PDFFont( FontFace.Helvetica, 12 );

            string longText = "<font color='#0000F8'><b>PDF4NET</b></font> is a <u><i>.NET</i></u> " +
                "library for embedding pdf " +
                "documents creation in any <u><i>.NET</i></u> application. " +
                "The pdf files structure is " +
                "hidden behind a simple object model that allows the creation of " +
                "<u>complex pdf documents with a few lines of code</u>. The library uses " +
                "a grid-based approach for placing content on document's pages. " +
                "It allows random access to each page of the document, allowing " +
                "the developer to set the size and the orientation for each page. " +
                "The object model provides support for basic drawing primitives, " +
                "like lines, circles, rectangles, images, etc. " +
                "It also provides extensive support for drawing text, giving the " +
                "developer a large freedom in formatting and placing text on page. " +
                "<font face='TimesRoman'>The library also offers more advanced features, like: automatic page " +
                "numbering; page templates; creation of bookmarks tree; " +
                "creation of hyperlinks; transition effects between pages; support " +
                "for viewer preferences; support for document metadata, like author, " +
                "title, etc, allowing the document to be searched and indexed; custom " +
                "document properties; enhanced color support (RGB, CMYK, Grayscale); " +
                "Adobe XMP metadata storage; user defined logical units; user defined " +
                "coordinate system.</font><br/>" +
                "The resulting pdf documents can be saved to disk or HTTP streams. " +
                "The library compresses document's content, thus resulting smaller pdf files. " +
                "The <font color='#0000F8'><b>PDF4NET</b></font> library can be used both from windows and <i>ASP.NET</i> applications. " +
                "The library is 100% managed, being written in C#. " +
                "The <font color='#0000F8'><b>PDF4NET</b></font> library is <u>licensed " +
                "per developer</u> and can be " +
                "distributed <font color='#F80000'>royalty free</font>.<br/><br/>";

            longText = longText + longText + longText + longText + longText + longText +
                longText + longText + longText + longText + longText + longText;

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            PDFTextFormatOptions tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopJustified;
            tfo.ClipText = ClipText.ClipWords;

            // length of text that fits in the column
            int columnTextLength;

            bool endOfText = false;
            int startIndex = 0;
            // start drawing text
            while( !endOfText )
            {
                // where to start to print the column
                float leftOffset = leftMargin;

                // Create a new page in the document
                PDFPage page = pdfDoc.AddPage( );

                int i = 0;
                // draw each column
                // each column will contain one random positioned image
                Random rnd = new Random( );
                while( i < columnCount )
                {
                    #region Random Image Setup
                    // index of the image to be displayed
                    int imageIndex = 1 + rnd.Next( 5 );

                    // set columnHeight for height, because we'll set KeepAspectRatio to
                    // KeepWidth and the height will be automatically computed.
                    PDFImage img = new PDFImage( "auto" + imageIndex.ToString( ) +".jpg",
                        leftOffset, topMargin, columnWidth, columnHeight, 0 );
                    img.KeepAspectRatio = KeepAspectRatio.KeepWidth;
                    float imageHeight = img.RealHeight;

                    // compute a random top position for the image so it fits full
                    // in the column
                    float imageTop = 30 +
                        ( float )( ( columnHeight - topMargin - bottomMargin - imageHeight ) * rnd.NextDouble( ) );
                    img.Top = imageTop;
                    #endregion Random Image Setup

                    #region Above Image Text
                    // see how much text fits above the image
                    // imageTop - topMargin = the height available above the image
                    columnTextLength = PDFHTMLTextBox.FitText( longText, font,
                        columnWidth, imageTop - topMargin, 0, startIndex );

                    // draw text above image
                    page.Canvas.DrawHTMLTextBox( longText, font, null, blackBrush,
                        leftOffset, topMargin, columnWidth, imageTop - topMargin, tfo, startIndex );

                    // move the index to the next fragment
                    startIndex = startIndex + columnTextLength;
                    if( startIndex >= longText.Length )
                    {
                        endOfText = true;
                        break;
                    }
                    #endregion Above Image Text

                    // draw the image
                    page.Canvas.Add( img );

                    #region Below Image Text
                    // see how much text fits below the image
                    // columnHeight - ( topText - topMargin ) = available space below image
                    float topText = ( float )Math.Ceiling( ( imageTop + imageHeight )/font.Size ) * font.Size;
                    columnTextLength = PDFHTMLTextBox.FitText( longText, font,
                        columnWidth, columnHeight - ( topText - topMargin ),
                        0, startIndex );

                    // draw text below image
                    page.Canvas.DrawHTMLTextBox( longText, font, null, blackBrush,
                        leftOffset, topText, columnWidth,
                        columnHeight - ( topText - topMargin ),
                        tfo, startIndex );

                    // move the index to the next fragment
                    startIndex = startIndex + columnTextLength;
                    if( startIndex >= longText.Length )
                    {
                        endOfText = true;
                        break;
                    }
                    #endregion Below Image Text

                    // compute the offset of the next column
                    leftOffset = leftOffset + columnWidth + columnSpace;

                    i++;
                }
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "multicolumntextandimages.pdf" );
        }
    }
}


MultiColumnTextAndImages.vb

'
' File name: MultiColumnTextAndImages.vb
'

Imports System
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ Summary description for Class1.
'/ </summary>

Class MultiColumnTextAndImages

    '/ <summary>
    '/ The main entry point for the application.
    '/ </summary>
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        Dim leftMargin As Single = 30
        Dim topMargin As Single = 30
        Dim rightMargin As Single = 30
        Dim bottomMargin As Single = 30
        Dim columnSpace As Single = 30
        Dim columnCount As Single = 2
        Dim columnWidth As Single = (612 - leftMargin - rightMargin - columnSpace) / 2 '612 - width of Letter size in points
        Dim columnHeight As Single = 792 - topMargin - bottomMargin '792 - height of Letter size in points
        Dim blackBrush As New PDFBrush(New PDFColor(0, 0, 0))
        Dim font As New PDFFont(FontFace.Helvetica, 12)

        Dim longText As String = "<font color='#0000F8'><b>PDF4NET</b></font> is a <u><i>.NET</i></u> " + _
            "library for embedding pdf documents creation in any <u><i>.NET</i></u> application. " + _
            "The pdf files structure is hidden behind a simple object model that allows the creation of " + _
            "<u>complex pdf documents with a few lines of code</u>. The library uses " + _
            "a grid-based approach for placing content on document's pages. " + _
            "It allows random access to each page of the document, allowing " + _
            "the developer to set the size and the orientation for each page. " + _
            "The object model provides support for basic drawing primitives, " + _
            "like lines, circles, rectangles, images, etc. " + _
            "It also provides extensive support for drawing text, giving the " + _
            "developer a large freedom in formatting and placing text on page. " + _
            "<font face='TimesRoman'>The library also offers more advanced features, like: automatic page " + _
            "numbering; page templates; creation of bookmarks tree; " + _
            "creation of hyperlinks; transition effects between pages; support " + _
            "for viewer preferences; support for document metadata, like author, " + _
            "title, etc, allowing the document to be searched and indexed; custom " + _
            "document properties; enhanced color support (RGB, CMYK, Grayscale); " + _
            "Adobe XMP metadata storage; user defined logical units; user defined " + _
            "coordinate system.</font><br/>" + _
            "The resulting pdf documents can be saved to disk or HTTP streams. " + _
            "The library compresses document's content, thus resulting smaller pdf files. " + _
            "The <font color='#0000F8'><b>PDF4NET</b></font> library can be used both from " + _
            "windows and <i>ASP.NET</i> applications. " + _
            "The library is 100% managed, being written in C#. " + _
            "The <font color='#0000F8'><b>PDF4NET</b></font> library is <u>licensed " + _
            "per developer</u> and can be distributed <font color='#F80000'>royalty free</font>.<br/><br/>"

        longText = longText + longText + longText + longText + longText + longText + _
            longText + longText + longText + longText + longText + longText

        ' Create the pdf document
        Dim pdfDoc As New PDFDocument()

        Dim tfo As New PDFTextFormatOptions()
        tfo.Align = TextAlign.TopJustified
        tfo.ClipText = ClipText.ClipWords

        ' length of text that fits in the column
        Dim columnTextLength As Integer

        Dim endOfText As Boolean = False
        Dim startIndex As Integer = 0
        ' start drawing text
        While Not endOfText
            ' where to start to print the column
            Dim leftOffset As Single = leftMargin

            ' Create a new page in the document
            Dim page As PDFPage = pdfDoc.AddPage()

            Dim i As Integer = 0
            ' draw each column
            ' each column will contain one random positioned image
            Dim rnd As New Random()
            While i < columnCount
                ' index of the image to be displayed
                Dim imageIndex As Integer = 1 + rnd.Next(5)

                ' set columnHeight for height, because we'll set KeepAspectRatio to
                ' KeepWidth and the height will be automatically computed.
                Dim img As New PDFImage("auto" + imageIndex.ToString() + ".jpg", leftOffset, topMargin, columnWidth, columnHeight, 0)
                img.KeepAspectRatio = KeepAspectRatio.KeepWidth
                Dim imageHeight As Single = img.RealHeight

                ' compute a random top position for the image so it fits full
                ' in the column
                Dim imageTop As Single = 30 + System.Convert.ToSingle((columnHeight - topMargin - bottomMargin - imageHeight) * rnd.NextDouble())
                img.Top = imageTop

                ' see how much text fits above the image
                ' imageTop - topMargin = the height available above the image
                columnTextLength = PDFHTMLTextBox.FitText(longText, font, columnWidth, imageTop - topMargin, 0, startIndex)

                ' draw text above image
                page.Canvas.DrawHTMLTextBox(longText, font, Nothing, blackBrush, leftOffset, topMargin, columnWidth, imageTop - topMargin, tfo, startIndex)

                ' move the index to the next fragment
                startIndex = startIndex + columnTextLength
                If startIndex >= longText.Length Then
                    endOfText = True
                    Exit While
                End If

                ' draw the image
                page.Canvas.Add(img)

                ' see how much text fits below the image
                ' columnHeight - ( topText - topMargin ) = available space below image
                Dim topText As Single = System.Convert.ToSingle(Math.Ceiling((imageTop + imageHeight) / font.Size)) * font.Size
                columnTextLength = PDFHTMLTextBox.FitText(longText, font, columnWidth, columnHeight - (topText - topMargin), 0, startIndex)

                ' draw text below image
                page.Canvas.DrawHTMLTextBox(longText, font, Nothing, blackBrush, leftOffset, topText, columnWidth, columnHeight - (topText - topMargin), tfo, startIndex)

                ' move the index to the next fragment
                startIndex = startIndex + columnTextLength
                If startIndex >= longText.Length Then
                    endOfText = True
                    Exit While
                End If

                ' compute the offset of the next column
                leftOffset = leftOffset + columnWidth + columnSpace

                i += 1
            End While
        End While

        ' Save the document to disk
        pdfDoc.SaveToFile("multicolumntextandimages.pdf")

    End Sub 'Main
End Class 'MultiColumnTextAndImages


Samples: PageOrientations

Samples

PageOrientations

This sample shows how the PDF4NET library allows to create documents with different orientations of their pages. It creates a document with 2 pages. The first page has Portrait orientation, while the second one has Landscape orientation.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


PageOrientations.cs

/// <fileName>
/// File name: PageOrientations.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.PageOrientations
{
    /// <summary>
    /// This sample will show how to create a document with
    /// different pages orientations
    /// </summary>
    class PageOrientations
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 20 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create first page
            PDFPage pdfPage1 = pdfDoc.AddPage( );
            // No need to do this because Portrait is the default orientation
            pdfPage1.Orientation = PageOrientation.Portrait;

            // Draw a label on first page
            pdfPage1.Canvas.DrawText( "This page uses Portrait orientation.",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Create second page
            PDFPage pdfPage2 = pdfDoc.AddPage( );
            // Set page's orientation to Landscape
            pdfPage2.Orientation = PageOrientation.Landscape;

            // Draw a label on first page
            pdfPage2.Canvas.DrawText( "This page uses Landscape orientation.",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Save the document to disk
            pdfDoc.SaveToFile( "pageorientations.pdf" );
        }
    }
}


PageOrientations.vb

'
' File name: PageOrientations.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.PageOrientations
    '/ <summary>
    '/ This sample will show how to create a document with
    '/ different pages orientations
    '/ </summary>
    Class PageOrientations

        Shared Sub Main()
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 20)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create first page
            Dim pdfPage1 As PDFPage = pdfDoc.AddPage()
            ' No need to do this because Portrait is the default orientation
            pdfPage1.Orientation = PageOrientation.Portrait

            ' Draw a label on first page
            pdfPage1.Canvas.DrawText("This page uses Portrait orientation.", fontText, Nothing, blackBrush, 20, 20)

            ' Create second page
            Dim pdfPage2 As PDFPage = pdfDoc.AddPage()
            ' Set page's orientation to Landscape
            pdfPage2.Orientation = PageOrientation.Landscape

            ' Draw a label on first page
            pdfPage2.Canvas.DrawText("This page uses Landscape orientation.", fontText, Nothing, blackBrush, 20, 20)

            ' Save the document to disk
            pdfDoc.SaveToFile("pageorientations.pdf")
        End Sub 'Main
    End Class 'PageOrientations
End Namespace 'O2S.Samples.PDF4NET.PageOrientations


Samples: PageSizes

Samples

PageSizes

This sample shows how the PDF4NET library allows to create documents with pages of different sizes. It creates a document with 14 pages, each page has a different size.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


PageSizes.cs

/// <fileName>
/// File name: PageSizes.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.PageSizes
{
    /// <summary>
    /// This sample will show how to create a document with different page sizes
    /// </summary>
    class PageSizes
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            PageSize[] pageSizes = { PageSize.A3, PageSize.A4, PageSize.A5, PageSize.B4,
                                       PageSize.B5, PageSize.Executive, PageSize.Folio,
                                       PageSize.Ledger, PageSize.Legal, PageSize.Letter,
                                       PageSize.Quarto, PageSize.Size10x14,
                                       PageSize.Statement, PageSize.Tabloid };

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 20 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create the pages of the document, each one having a different size
            for( int i = 0; i < pageSizes.Length; i++ )
            {
                // Create the page
                PDFPage pdfPage = pdfDoc.AddPage( );
                // Set its size
                pdfPage.Size = pageSizes[i];
                // Draw a label on it
                pdfPage.Canvas.DrawText( "This page has the following size: " + pageSizes[i].ToString( ),
                    fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "pagesizes.pdf" );
        }
    }
}


PageSizes.vb

'
' File name: PageSizes.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.PageSizes
    '/ <summary>
    '/ This sample will show how to create a document with different page sizes
    '/ </summary>
    Class PageSizes

        Shared Sub Main()
            Dim pageSizes As PageSize() = {PageSize.A3, PageSize.A4, PageSize.A5, PageSize.B4, PageSize.B5, PageSize.Executive, PageSize.Folio, PageSize.Ledger, PageSize.Legal, PageSize.Letter, PageSize.Quarto, PageSize.Size10x14, PageSize.Statement, PageSize.Tabloid}

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 20)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create the pages of the document, each one having a different size
            Dim i As Integer
            For i = 0 To pageSizes.Length - 1
                ' Create the page
                Dim pdfPage As PDFPage = pdfDoc.AddPage()
                ' Set its size
                pdfPage.Size = pageSizes(i)
                ' Draw a label on it
                pdfPage.Canvas.DrawText("This page has the following size: " + pageSizes(i).ToString(), fontText, Nothing, blackBrush, 20, 20)
            Next i

            ' Save the document to disk
            pdfDoc.SaveToFile("pagesizes.pdf")
        End Sub 'Main
    End Class 'PageSizes
End Namespace 'O2S.Samples.PDF4NET.PageSizes


Samples: Pantone colors

Samples

Pantone colors

This sample shows how to work with Pantone colors. These colors are specific instances of separation colors.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


PantoneColors.cs

using System;
using System.IO;
using System.Text;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Functions;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Graphics.ColorSpaces;

namespace O2S.Samples.PDF4NET
{
    /// <summary>
    /// This sample shows how to work with various PANTONE colors when creating a PDF document.
    /// </summary>
    class PantoneColors
    {
        [STAThread]
        static void Main(string[] args)
        {
            PDFDocument doc = new PDFDocument();

            PDFPage page = doc.AddPage();
            DrawPantoneColors(page);

            doc.Save("pantonecolors.pdf");
            doc.Dispose();
        }

        /// <summary>
        /// Draws content on a page using PANTONE colors.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        private static void DrawPantoneColors(PDFPage page)
        {
            PDFRgbColor black = new PDFRgbColor(0, 0, 0);
            PDFBrush blackBrush = new PDFBrush(black);
            PDFFont font = new PDFFont(FontFace.Helvetica, 16);

            page.Canvas.DrawText("Pantone colors", font, null, blackBrush, 50, 50);

            PDFPantoneColor orange = PDFPantoneColor.Orange021;
            orange.Tint = 0.9;
            PDFPantoneColor warmRed = PDFPantoneColor.WarmRed;
            warmRed.Tint = 0.4;

            PDFBrush orangeBrush = new PDFBrush(orange);
            PDFPen warmRedPen = new PDFPen(warmRed, 5);
            page.Canvas.DrawRoundRectangle(warmRedPen, orangeBrush, 50, 100, 400, 150, 20, 20);
        }
    }
}


PantoneColors.vb

Imports System
Imports System.IO
Imports System.Text
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Functions
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Graphics.ColorSpaces

Namespace O2S.Samples.PDF4NET
    '/ <summary>
    '/ This sample shows how to work with various PANTONE colors when creating a PDF document.
    '/ </summary>
    Class PantoneColors
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            Dim doc As PDFDocument = New PDFDocument()

            Dim page As PDFPage = doc.AddPage()
            DrawPantoneColors(page)

            doc.Save("pantonecolors.pdf")
            doc.Dispose()
        End Sub

        '/ <summary>
        '/ Draws content on a page using PANTONE colors.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        Private Shared Sub DrawPantoneColors(ByVal page As PDFPage)
            Dim black As PDFRgbColor = New PDFRgbColor(0, 0, 0)
            Dim blackBrush As PDFBrush = New PDFBrush(black)
            Dim font As PDFFont = New PDFFont(FontFace.Helvetica, 16)

            page.Canvas.DrawText("Pantone colors", font, Nothing, blackBrush, 50, 50)

            Dim orange As PDFPantoneColor = PDFPantoneColor.Orange021
            orange.Tint = 0.9
            Dim warmRed As PDFPantoneColor = PDFPantoneColor.WarmRed
            warmRed.Tint = 0.4

            Dim orangeBrush As PDFBrush = New PDFBrush(orange)
            Dim warmRedPen As PDFPen = New PDFPen(warmRed, 5)
            page.Canvas.DrawRoundRectangle(warmRedPen, orangeBrush, 50, 100, 400, 150, 20, 20)
        End Sub
    End Class
End Namespace


Samples: Paths

Samples

Paths

This sample demonstrates the support for free form paths implemented in PDF4NET library. A path can be constructed from several drawing primitives and it can be stroked and/or filled.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Paths.cs

/// <fileName>
/// File name: Paths.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Paths
{
    /// <summary>
    /// This sample shows how to use free form graphics paths with PDF4NET.
    /// </summary>
    class Paths
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Create one page
            PDFPage page = doc.AddPage( );

            PDFPen redPen = new PDFPen( new PDFColor( 255, 0, 0 ), 1 );
            PDFBrush darkBlueBrush = new PDFBrush( new PDFColor( 0, 0, 128 ) );
            // a star
            PDFPoint[] points = new PDFPoint[]{ new PDFPoint( 50, 200 ), new PDFPoint( 500, 200 ),
                new PDFPoint( 200, 400 ), new PDFPoint( 275, 50 ), new PDFPoint( 350, 400 ) };

            // create a graphic path
            PDFPath path = new PDFPath( );
            path.MoveTo( 50, 200 );
            path.Polygon( points );
            path.FillMode = FillMode.EvenOdd;

            path.MoveTo( 50, 450 );
            path.LineTo( 600, 450 );
            path.BezierTo( 600, 500, 500, 500, 500, 600 );
            path.BezierTo( 400, 600, 300, 550, 600, 500 );
            path.CloseSubpath( );

            // draw the path on the page
            page.Canvas.DrawPath( redPen, darkBlueBrush, path );

            // Save the document to disk
            doc.SaveToFile( "paths.pdf" );
        }
    }
}


Paths.vb

'
' File name: Paths.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to use free form graphics paths with PDF4NET.
'/ </summary>

Class Paths
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument

        ' Create one page
        Dim page As PDFPage = doc.AddPage()

        Dim redPen As New PDFPen(New PDFColor(255, 0, 0), 1)
        Dim darkBlueBrush As New PDFBrush(New PDFColor(0, 0, 128))
        ' a star
        Dim points() As PDFPoint = {New PDFPoint(50, 200), New PDFPoint(500, 200), New PDFPoint(200, 400), New PDFPoint(275, 50), New PDFPoint(350, 400)}

        ' create a graphic path
        Dim path As New PDFPath
        path.MoveTo(50, 200)
        path.Polygon(points)
        path.FillMode = FillMode.EvenOdd

        path.MoveTo(50, 450)
        path.LineTo(600, 450)
        path.BezierTo(600, 500, 500, 500, 500, 600)
        path.BezierTo(400, 600, 300, 550, 600, 500)
        path.CloseSubpath()

        ' draw the path on the page
        page.Canvas.DrawPath(redPen, darkBlueBrush, path)

        ' Save the document to disk
        doc.SaveToFile("paths.pdf")
    End Sub 'Main
End Class 'Paths


Samples: Polygons

Samples

Polygons

This sample shows the polygons drawing capabilites. On the first page it draws a few geometric figures. Second page demonstrates polypolygon drawing capabilities. For polypolygons the filling mode can be set.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Polygons.cs

/// <fileName>
/// File name: Polygons.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Polygons
{
    /// <summary>
    /// This sample will show how to draw various polygons and polypolygons on the page.
    /// </summary>
    class Polygons
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create first page
            PDFPage pdfPage1 = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFBrush orangeBrush = new PDFBrush( new PDFColor( Color.Orange ) );
            PDFPen pen = new PDFPen( new PDFColor( Color.GreenYellow ), 1 );

            // Draw a pentagon
            PDFPoint[] pentagon = { new PDFPoint( 150, 35 ), new PDFPoint( 250, 125 ), new PDFPoint( 200, 215 ),
                                      new PDFPoint( 100, 215 ), new PDFPoint( 50, 125 ) };
            pdfPage1.Canvas.DrawText( "This is a pentagon",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawPolygon( pen, orangeBrush, pentagon );

            // Draw a hexagon
            PDFPoint[] hexagon = { new PDFPoint( 450, 35 ), new PDFPoint( 550, 135 ), new PDFPoint( 550, 235 ),
                                     new PDFPoint( 450, 335 ), new PDFPoint( 350, 235 ), new PDFPoint( 350, 135 ) };
            pdfPage1.Canvas.DrawText( "This is a hexagon",
                fontText, null, blackBrush, 300, 20, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawPolygon( pen, orangeBrush, hexagon );

            // Draw an arrow
            PDFPoint[] arrow = { new PDFPoint( 20, 350 ), new PDFPoint( 220, 350 ), new PDFPoint( 220, 300 ),
                                   new PDFPoint( 320, 400 ), new PDFPoint( 220, 500 ), new PDFPoint( 220, 450 ),
                                   new PDFPoint( 20, 450 ) };
            pdfPage1.Canvas.DrawText( "This is an arrow",
                fontText, null, blackBrush, 20, 300, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawPolygon( pen, null, arrow );

            // Draw a rectangular callout
            PDFPoint[] callout = { new PDFPoint( 350, 350 ), new PDFPoint( 550, 350 ), new PDFPoint( 550, 450 ),
                                     new PDFPoint( 480, 450 ), new PDFPoint( 350, 550 ), new PDFPoint( 420, 450 ),
                                     new PDFPoint( 350, 450 ) };
            pdfPage1.Canvas.DrawText( "This is a rectangular callout",
                fontText, null, blackBrush, 370, 400, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawPolygon( pen, null, callout );

            // Create second page
            PDFPage pdfPage2 = pdfDoc.AddPage( );

            // a star
            PDFPoint[] points = new PDFPoint[]{ new PDFPoint( 50, 200 ), new PDFPoint( 500, 200 ),
                                                  new PDFPoint( 150, 500 ), new PDFPoint( 275, 50 ), new PDFPoint( 400, 500 ) };
            PDFPolygon polygon = new PDFPolygon( pen, orangeBrush, points );
            polygon.FillMode = FillMode.EvenOdd;
            pdfPage2.Canvas.Add( polygon );

            // Create third page
            PDFPage pdfPage3 = pdfDoc.AddPage( );

            // a polypolygon
            PDFPoint[][] polygons = new PDFPoint[4][];
            polygons[0] = new PDFPoint[]{ new PDFPoint( 50, 100 ), new PDFPoint( 550, 100 ),
                                            new PDFPoint( 550, 600 ), new PDFPoint( 50, 600 ) };
            polygons[1] = new PDFPoint[]{ new PDFPoint( 100, 150 ), new PDFPoint( 500, 150 ),
                                            new PDFPoint( 500, 550 ), new PDFPoint( 100, 550 ) };
            polygons[2] = new PDFPoint[]{ new PDFPoint( 150, 200 ), new PDFPoint( 450, 200 ),
                                            new PDFPoint( 450, 500 ), new PDFPoint( 150, 500 ) };
            polygons[3] = new PDFPoint[]{ new PDFPoint( 200, 250 ), new PDFPoint( 400, 250 ),
                                            new PDFPoint( 400, 450 ), new PDFPoint( 200, 450 ) };
            PDFPolyPolygon pp = new PDFPolyPolygon( pen, orangeBrush, polygons );
            pp.FillMode = FillMode.EvenOdd;
            pdfPage3.Canvas.Add( pp );

            // Save the document to disk
            pdfDoc.SaveToFile( "polygons.pdf" );
        }
    }
}


Polygons.vb

'
' File name: Polygons.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample will show how to draw various polygons and polypolygons on the page.
'/ </summary>

Class Polygons

    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim pdfDoc As New PDFDocument

        ' Create first page
        Dim pdfPage1 As PDFPage = pdfDoc.AddPage()

        ' Create the graphic objects
        Dim fontText As New PDFFont(FontFace.Helvetica, 12)
        Dim blackBrush As New PDFBrush(New PDFColor)
        Dim orangeBrush As New PDFBrush(New PDFColor(Color.Orange))
        Dim pen As New PDFPen(New PDFColor(Color.GreenYellow), 1)

        ' Draw a pentagon
        Dim pentagon As PDFPoint() = {New PDFPoint(150, 35), New PDFPoint(250, 125), New PDFPoint(200, 215), New PDFPoint(100, 215), New PDFPoint(50, 125)}
        pdfPage1.Canvas.DrawText("This is a pentagon", fontText, Nothing, blackBrush, 20, 20, 0, TextAlign.TopLeft)
        pdfPage1.Canvas.DrawPolygon(pen, orangeBrush, pentagon)

        ' Draw a hexagon
        Dim hexagon As PDFPoint() = {New PDFPoint(450, 35), New PDFPoint(550, 135), New PDFPoint(550, 235), New PDFPoint(450, 335), New PDFPoint(350, 235), New PDFPoint(350, 135)}
        pdfPage1.Canvas.DrawText("This is a hexagon", fontText, Nothing, blackBrush, 300, 20, 0, TextAlign.TopLeft)
        pdfPage1.Canvas.DrawPolygon(pen, orangeBrush, hexagon)

        ' Draw an arrow
        Dim arrow As PDFPoint() = {New PDFPoint(20, 350), New PDFPoint(220, 350), New PDFPoint(220, 300), New PDFPoint(320, 400), New PDFPoint(220, 500), New PDFPoint(220, 450), New PDFPoint(20, 450)}
        pdfPage1.Canvas.DrawText("This is an arrow", fontText, Nothing, blackBrush, 20, 300, 0, TextAlign.TopLeft)
        pdfPage1.Canvas.DrawPolygon(pen, Nothing, arrow)

        ' Draw a rectangular callout
        Dim callout As PDFPoint() = {New PDFPoint(350, 350), New PDFPoint(550, 350), New PDFPoint(550, 450), New PDFPoint(480, 450), New PDFPoint(350, 550), New PDFPoint(420, 450), New PDFPoint(350, 450)}
        pdfPage1.Canvas.DrawText("This is a rectangular callout", fontText, Nothing, blackBrush, 370, 400, 0, TextAlign.TopLeft)
        pdfPage1.Canvas.DrawPolygon(pen, Nothing, callout)

        ' Create second page
        Dim pdfPage2 As PDFPage = pdfDoc.AddPage()

        ' a star
        Dim points() As PDFPoint = {New PDFPoint(50, 200), New PDFPoint(500, 200), New PDFPoint(150, 500), New PDFPoint(275, 50), New PDFPoint(400, 500)}
        Dim polygon As New PDFPolygon(pen, orangeBrush, points)
        polygon.FillMode = FillMode.EvenOdd
        pdfPage2.Canvas.Add(polygon)

        ' Create third page
        Dim pdfPage3 As PDFPage = pdfDoc.AddPage()

        ' a polypolygon
        Dim polygons(3)() As PDFPoint
        polygons(0) = New PDFPoint() {New PDFPoint(50, 100), New PDFPoint(550, 100), New PDFPoint(550, 600), New PDFPoint(50, 600)}
        polygons(1) = New PDFPoint() {New PDFPoint(100, 150), New PDFPoint(500, 150), New PDFPoint(500, 550), New PDFPoint(100, 550)}
        polygons(2) = New PDFPoint() {New PDFPoint(150, 200), New PDFPoint(450, 200), New PDFPoint(450, 500), New PDFPoint(150, 500)}
        polygons(3) = New PDFPoint() {New PDFPoint(200, 250), New PDFPoint(400, 250), New PDFPoint(400, 450), New PDFPoint(200, 450)}
        Dim pp As New PDFPolyPolygon(pen, orangeBrush, polygons)
        pp.FillMode = FillMode.EvenOdd
        pdfPage3.Canvas.Add(pp)

        ' Save the document to disk
        pdfDoc.SaveToFile("polygons.pdf")
    End Sub 'Main
End Class 'Polygons


Samples: RandomAccess

Samples

RandomAccess

This sample shows the possibilities of random accessing each page of the document. It creates a document with 10 pages, then the pages are access in a random order. On each page it is written the time of access. To better observe the random access, between page writes, there is a few seconds delay.

C# Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


RandomAccess.cs

/// <fileName>
/// File name: RandomAccess.cs
/// </fileName>

using System;
using System.Drawing;
using System.Threading;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.RandomAccess
{
    /// <summary>
    /// This sample will show the possibility to
    /// access in a random way any page of the document.
    /// On each page the access time will be written.
    /// </summary>
    class RandomAccess
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the array that will hold the page access indexes
            int[] pageIndexes = {4, 7, 9, 2, 6, 1, 0, 3, 8, 5};
            int i;

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create all the pages of the document
            for( i = 0; i < pageIndexes.Length; i++ )
            {
                pdfDoc.AddPage( );
            }

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush brush = new PDFBrush( new PDFColor( ) );

            // Access each page of the document. The access order
            // is given by the content of pageIndexes array
            for( i = 0; i < pageIndexes.Length; i++ )
            {
                pdfDoc.Pages[pageIndexes[i]].Canvas.DrawText( "Write time: " +
                    DateTime.Now.ToString( "yyyy/MM/dd HH:mm:ss" ),
                    fontText, null, brush, 20, 50 );

                // Sleep for 2 seconds
                Thread.Sleep( 2000 );
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "randomaccess.pdf" );
        }
    }
}


Samples: Rectangles

Samples

Rectangles

This samples shows the rectanges drawing capabilities of the PDF4NET library. On the first page, it draws a rectange by painting its border, a rectange by filling its interior, and a rectange by painting its border and filling its interior. It also show how to draw a rotated rectangle. On the second page it draws 50 rectangles at random locations on the page. The color of the rectangles is generated randomly.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Rectangles.cs

/// <fileName>
/// File name: Rectangles.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Rectangles
{
    /// <summary>
    /// This sample will show how to draw various rectangles
    /// on the page.
    /// </summary>
    class Rectangles
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create first page
            PDFPage pdfPage1 = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFBrush redBrush = new PDFBrush( new PDFColor( 255, 0, 0 ) );
            PDFPen pen = new PDFPen( new PDFColor( 0, 0, 255 ), 1 );

            // Draw a rectangle that has a border
            pdfPage1.Canvas.DrawText( "This rectangle is drawn by drawing its border",
                fontText, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawRectangle2( pen, null, 20, 35, 200, 100, 0 );

            // Draw a rectangle that has no border and its interior is filled
            pdfPage1.Canvas.DrawText( "This rectangle is drawn by filling its interior",
                fontText, null, blackBrush, 300, 20, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawRectangle2( null, redBrush, 300, 35, 300, 150, 0 );

            // Draw a rectangle that has a border and its interior is filled
            pdfPage1.Canvas.DrawText( "This rectangle has a border and a filled interior",
                fontText, null, blackBrush, 20, 200, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawRectangle2( pen, redBrush, 20, 215, 200, 150, 0 );

            // Draw a rotated rectangle
            pdfPage1.Canvas.DrawText( "This rectangle is rotated with 30 degrees around the top left corner",
                fontText, null, blackBrush, 20, 400, 0, TextAlign.TopLeft );
            pdfPage1.Canvas.DrawRectangle2( pen, redBrush, 20, 550, 200, 150, 30 );
            pdfPage1.Canvas.DrawRectangle2( pen, redBrush, 20, 550, 200, 150, 0 );

            // Create the second page
            PDFPage pdfPage2 = pdfDoc.AddPage( );

            Random rnd = new Random( );
            for( int i = 0; i < 50; i++ )
            {
                // Create random colors for the border and the interior
                PDFColor brushColor = new PDFColor( ( byte )rnd.Next( 256 ),
                    ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );
                PDFColor penColor = new PDFColor( ( byte )rnd.Next( 256 ),
                    ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );

                // Create the brush to fill the interior
                PDFBrush randomBrush = new PDFBrush( brushColor );
                // Create the pen to draw the border
                PDFPen randomPen = new PDFPen( penColor, 1 );

                // Generate random positions
                float left = rnd.Next( ( int )pdfPage2.Width );
                float top = rnd.Next( ( int )pdfPage2.Height );

                // Generate random sizes
                float width = rnd.Next( ( int )( pdfPage2.Width - left ) ); // try to keep the rectangle
                float height = rnd.Next( ( int )( pdfPage2.Height - top ) );   // within the page

                // Generate random orientation
                float orientation = rnd.Next( 360 );

                // Draw the rectangle
                pdfPage2.Canvas.DrawRectangle2( randomPen, randomBrush,
                    left, top, width, height, orientation );
            }

            // Draw a label
            pdfPage2.Canvas.DrawText( "Random rectangles",
                fontText, null, blackBrush, 20, 350, 0, TextAlign.TopLeft );

            // Save the document to disk
            pdfDoc.SaveToFile( "rectangles.pdf" );
        }
    }
}


Rectangles.vb

'
' File name: Rectangles.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.Rectangles
    '/ <summary>
    '/ This sample will show how to draw various rectangles
    '/ on the page.
    '/ </summary>
    Class Rectangles

        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create first page
            Dim pdfPage1 As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim redBrush As New PDFBrush(New PDFColor(255, 0, 0))
            Dim pen As New PDFPen(New PDFColor(0, 0, 255), 1)

            ' Draw a rectangle that has a border
            pdfPage1.Canvas.DrawText("This rectangle is drawn by drawing its border", fontText, Nothing, blackBrush, 20, 20)
            pdfPage1.Canvas.DrawRectangle(pen, 35, 20, 200, 100)

            ' Draw a rectangle that has no border and its interior is filled
            pdfPage1.Canvas.DrawText("This rectangle is drawn by filling its interior", fontText, Nothing, blackBrush, 300, 20)
            pdfPage1.Canvas.DrawRectangle(redBrush, 35, 300, 300, 150)

            ' Draw a rectangle that has a border and its interior is filled
            pdfPage1.Canvas.DrawText("This rectangle has a border and a filled interior", fontText, Nothing, blackBrush, 20, 200)
            pdfPage1.Canvas.DrawRectangle(pen, redBrush, 215, 20, 200, 150)

            ' Draw a rotated rectangle
            pdfPage1.Canvas.DrawText("This rectangle is rotated with 30 degrees around the top left corner", fontText, Nothing, blackBrush, 20, 400)
            pdfPage1.Canvas.DrawRectangle(pen, redBrush, 550, 20, 200, 150, 30)

            ' Create the second page
            Dim pdfPage2 As PDFPage = pdfDoc.AddPage()

            Dim rnd As New Random()
            Dim i As Integer
            For i = 0 To 49
                ' Create random colors for the border and the interior
                Dim brushColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))
                Dim penColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))

                ' Create the brush to fill the interior
                Dim randomBrush As New PDFBrush(brushColor)
                ' Create the pen to draw the border
                Dim randomPen As New PDFPen(penColor, 1)

                ' Generate random positions
                Dim left As Single = rnd.Next(CInt(pdfPage2.Width))
                Dim top As Single = rnd.Next(CInt(pdfPage2.Height))

                ' Generate random sizes
                Dim width As Single = rnd.Next(CInt(pdfPage2.Width - left)) ' try to keep the rectangle
                Dim height As Single = rnd.Next(CInt(pdfPage2.Height - top)) ' within the page
                ' Generate random orientation
                Dim orientation As Single = rnd.Next(360)

                ' Draw the rectangle
                pdfPage2.Canvas.DrawRectangle(randomPen, randomBrush, top, left, width, height, orientation)
            Next i

            ' Draw a label
            pdfPage2.Canvas.DrawText("Random rectangles", fontText, Nothing, blackBrush, 20, 350)

            ' Save the document to disk
            pdfDoc.SaveToFile("rectangles.pdf")
        End Sub 'Main
    End Class 'Rectangles
End Namespace 'O2S.Samples.PDF4NET.Rectangles


Samples: SaveProgress

Samples

Save progress

This sample shows how use the document's SaveProgress event in order to display a progress bar in a WinForms application to inform the user how much of the PDF file has been saved.

C# Source code | VB.NET Source code

© 2003 - 2007 O2 Solutions. All rights reserved.


SaveProgress.cs

/// <fileName>
/// File name: SaveProgress.cs.
/// </fileName>

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Graphics.Fonts;

namespace SaveProgress
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class SaveProgressForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtSourcePDFFile;
        private System.Windows.Forms.OpenFileDialog ofd;
        private System.Windows.Forms.Button btnBrowseSourcePDF;
        private System.Windows.Forms.Button btnBrowseDestinationPDF;
        private System.Windows.Forms.TextBox txtDestPDFFile;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button btnSave;
        private System.Windows.Forms.ProgressBar saveProgressBar;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public SaveProgressForm()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.txtSourcePDFFile = new System.Windows.Forms.TextBox();
            this.btnBrowseSourcePDF = new System.Windows.Forms.Button();
            this.ofd = new System.Windows.Forms.OpenFileDialog();
            this.btnBrowseDestinationPDF = new System.Windows.Forms.Button();
            this.txtDestPDFFile = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.btnSave = new System.Windows.Forms.Button();
            this.saveProgressBar = new System.Windows.Forms.ProgressBar();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(6, 6);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(84, 18);
            this.label1.TabIndex = 0;
            this.label1.Text = "Source PDF file:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // txtSourcePDFFile
            //
            this.txtSourcePDFFile.Location = new System.Drawing.Point(114, 6);
            this.txtSourcePDFFile.Name = "txtSourcePDFFile";
            this.txtSourcePDFFile.Size = new System.Drawing.Size(240, 21);
            this.txtSourcePDFFile.TabIndex = 1;
            this.txtSourcePDFFile.Text = "";
            //
            // btnBrowseSourcePDF
            //
            this.btnBrowseSourcePDF.Location = new System.Drawing.Point(354, 6);
            this.btnBrowseSourcePDF.Name = "btnBrowseSourcePDF";
            this.btnBrowseSourcePDF.Size = new System.Drawing.Size(24, 21);
            this.btnBrowseSourcePDF.TabIndex = 2;
            this.btnBrowseSourcePDF.Text = "...";
            this.btnBrowseSourcePDF.Click += new System.EventHandler(this.btnBrowseSourcePDF_Click);
            //
            // ofd
            //
            this.ofd.Filter = "PDF Files|*.pdf";
            this.ofd.Title = "Select a PDF file";
            //
            // btnBrowseDestinationPDF
            //
            this.btnBrowseDestinationPDF.Location = new System.Drawing.Point(354, 36);
            this.btnBrowseDestinationPDF.Name = "btnBrowseDestinationPDF";
            this.btnBrowseDestinationPDF.Size = new System.Drawing.Size(24, 21);
            this.btnBrowseDestinationPDF.TabIndex = 5;
            this.btnBrowseDestinationPDF.Text = "...";
            this.btnBrowseDestinationPDF.Click += new System.EventHandler(this.btnBrowseDestinationPDF_Click);
            //
            // txtDestPDFFile
            //
            this.txtDestPDFFile.Location = new System.Drawing.Point(114, 36);
            this.txtDestPDFFile.Name = "txtDestPDFFile";
            this.txtDestPDFFile.Size = new System.Drawing.Size(240, 21);
            this.txtDestPDFFile.TabIndex = 4;
            this.txtDestPDFFile.Text = "";
            //
            // label2
            //
            this.label2.Location = new System.Drawing.Point(6, 36);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(108, 18);
            this.label2.TabIndex = 3;
            this.label2.Text = "Destination PDF file:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // btnSave
            //
            this.btnSave.Location = new System.Drawing.Point(6, 66);
            this.btnSave.Name = "btnSave";
            this.btnSave.Size = new System.Drawing.Size(372, 23);
            this.btnSave.TabIndex = 6;
            this.btnSave.Text = "Save source as destination";
            this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
            //
            // saveProgressBar
            //
            this.saveProgressBar.Location = new System.Drawing.Point(6, 96);
            this.saveProgressBar.Name = "saveProgressBar";
            this.saveProgressBar.Size = new System.Drawing.Size(372, 23);
            this.saveProgressBar.Step = 1;
            this.saveProgressBar.TabIndex = 7;
            //
            // SaveProgressForm
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(384, 125);
            this.Controls.Add(this.saveProgressBar);
            this.Controls.Add(this.btnSave);
            this.Controls.Add(this.btnBrowseDestinationPDF);
            this.Controls.Add(this.txtDestPDFFile);
            this.Controls.Add(this.txtSourcePDFFile);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.btnBrowseSourcePDF);
            this.Controls.Add(this.label1);
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.Name = "SaveProgressForm";
            this.Text = "PDF4NET - Save progress sample";
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new SaveProgressForm());
        }

        private void btnBrowseSourcePDF_Click(object sender, System.EventArgs e)
        {
            ofd.CheckFileExists = true;
            if( ofd.ShowDialog( ) == DialogResult.OK )
            {
                txtSourcePDFFile.Text = ofd.FileName;
            }
        }

        private void btnBrowseDestinationPDF_Click(object sender, System.EventArgs e)
        {
            ofd.CheckFileExists = false;
            if( ofd.ShowDialog( ) == DialogResult.OK )
            {
                txtDestPDFFile.Text = ofd.FileName;
            }
        }

        private void btnSave_Click(object sender, System.EventArgs e)
        {
            saveProgressBar.Value = 0;

            // Import the PDF file.
            PDFDocument doc = new PDFDocument( txtSourcePDFFile.Text );
            // Create the event handler.
            PDFDocument.SaveProgressEventHandler saveProgressEventHandler =
                new PDFDocument.SaveProgressEventHandler( DocumentSaveProgress );
            // Attach the event to the document.
            doc.SaveProgress += saveProgressEventHandler;
            // Save the PDF file.
            doc.SaveToFile( txtDestPDFFile.Text );
            // Remove the event handler.
            doc.SaveProgress -= saveProgressEventHandler;
            // Dispose the document.
            doc.Dispose( );
            doc = null;
        }

        private void DocumentSaveProgress( object sender, SaveProgressEventArgs args )
        {
            saveProgressBar.Value = ( int )args.Progress;
        }
    }
}


SaveProgress.vb

'
' File name: SaveProgress.vb
'

Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Graphics.Fonts

Public Class SaveProgressForm
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    Friend WithEvents saveProgressBar As System.Windows.Forms.ProgressBar
    Friend WithEvents btnSave As System.Windows.Forms.Button
    Friend WithEvents btnBrowseDestinationPDF As System.Windows.Forms.Button
    Friend WithEvents txtDestPDFFile As System.Windows.Forms.TextBox
    Friend WithEvents txtSourcePDFFile As System.Windows.Forms.TextBox
    Friend WithEvents label2 As System.Windows.Forms.Label
    Friend WithEvents btnBrowseSourcePDF As System.Windows.Forms.Button
    Friend WithEvents label1 As System.Windows.Forms.Label
    Friend WithEvents ofd As System.Windows.Forms.OpenFileDialog
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.saveProgressBar = New System.Windows.Forms.ProgressBar
        Me.btnSave = New System.Windows.Forms.Button
        Me.btnBrowseDestinationPDF = New System.Windows.Forms.Button
        Me.txtDestPDFFile = New System.Windows.Forms.TextBox
        Me.txtSourcePDFFile = New System.Windows.Forms.TextBox
        Me.label2 = New System.Windows.Forms.Label
        Me.btnBrowseSourcePDF = New System.Windows.Forms.Button
        Me.label1 = New System.Windows.Forms.Label
        Me.ofd = New System.Windows.Forms.OpenFileDialog
        Me.SuspendLayout()
        '
        'saveProgressBar
        '
        Me.saveProgressBar.Location = New System.Drawing.Point(6, 96)
        Me.saveProgressBar.Name = "saveProgressBar"
        Me.saveProgressBar.Size = New System.Drawing.Size(372, 23)
        Me.saveProgressBar.Step = 1
        Me.saveProgressBar.TabIndex = 15
        '
        'btnSave
        '
        Me.btnSave.Location = New System.Drawing.Point(6, 66)
        Me.btnSave.Name = "btnSave"
        Me.btnSave.Size = New System.Drawing.Size(372, 23)
        Me.btnSave.TabIndex = 14
        Me.btnSave.Text = "Save source as destination"
        '
        'btnBrowseDestinationPDF
        '
        Me.btnBrowseDestinationPDF.Location = New System.Drawing.Point(354, 36)
        Me.btnBrowseDestinationPDF.Name = "btnBrowseDestinationPDF"
        Me.btnBrowseDestinationPDF.Size = New System.Drawing.Size(24, 21)
        Me.btnBrowseDestinationPDF.TabIndex = 13
        Me.btnBrowseDestinationPDF.Text = "..."
        '
        'txtDestPDFFile
        '
        Me.txtDestPDFFile.Location = New System.Drawing.Point(114, 36)
        Me.txtDestPDFFile.Name = "txtDestPDFFile"
        Me.txtDestPDFFile.Size = New System.Drawing.Size(240, 21)
        Me.txtDestPDFFile.TabIndex = 12
        Me.txtDestPDFFile.Text = ""
        '
        'txtSourcePDFFile
        '
        Me.txtSourcePDFFile.Location = New System.Drawing.Point(114, 6)
        Me.txtSourcePDFFile.Name = "txtSourcePDFFile"
        Me.txtSourcePDFFile.Size = New System.Drawing.Size(240, 21)
        Me.txtSourcePDFFile.TabIndex = 9
        Me.txtSourcePDFFile.Text = ""
        '
        'label2
        '
        Me.label2.Location = New System.Drawing.Point(6, 36)
        Me.label2.Name = "label2"
        Me.label2.Size = New System.Drawing.Size(108, 18)
        Me.label2.TabIndex = 11
        Me.label2.Text = "Destination PDF file:"
        Me.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'btnBrowseSourcePDF
        '
        Me.btnBrowseSourcePDF.Location = New System.Drawing.Point(354, 6)
        Me.btnBrowseSourcePDF.Name = "btnBrowseSourcePDF"
        Me.btnBrowseSourcePDF.Size = New System.Drawing.Size(24, 21)
        Me.btnBrowseSourcePDF.TabIndex = 10
        Me.btnBrowseSourcePDF.Text = "..."
        '
        'label1
        '
        Me.label1.Location = New System.Drawing.Point(6, 6)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(84, 18)
        Me.label1.TabIndex = 8
        Me.label1.Text = "Source PDF file:"
        Me.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'ofd
        '
        Me.ofd.Filter = "PDF Files|*.pdf"
        Me.ofd.Title = "Select a PDF file"
        '
        'SaveProgressForm
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 14)
        Me.ClientSize = New System.Drawing.Size(384, 125)
        Me.Controls.Add(Me.saveProgressBar)
        Me.Controls.Add(Me.btnSave)
        Me.Controls.Add(Me.btnBrowseDestinationPDF)
        Me.Controls.Add(Me.txtDestPDFFile)
        Me.Controls.Add(Me.txtSourcePDFFile)
        Me.Controls.Add(Me.label2)
        Me.Controls.Add(Me.btnBrowseSourcePDF)
        Me.Controls.Add(Me.label1)
        Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.MaximizeBox = False
        Me.Name = "SaveProgressForm"
        Me.Text = "PDF4NET - Save progress sample"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub btnBrowseSourcePDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowseSourcePDF.Click
        ofd.CheckFileExists = True
        If ofd.ShowDialog() = DialogResult.OK Then
            txtSourcePDFFile.Text = ofd.FileName
        End If
    End Sub

    Private Sub btnBrowseDestinationPDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowseDestinationPDF.Click
        ofd.CheckFileExists = False
        If ofd.ShowDialog() = DialogResult.OK Then
            txtDestPDFFile.Text = ofd.FileName
        End If
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        saveProgressBar.Value = 0

        ' Import the PDF file.
        Dim doc As New PDFDocument(txtSourcePDFFile.Text)
        ' Attach the event to the document.
        AddHandler doc.SaveProgress, AddressOf Me.DocumentSaveProgress
        ' Save the PDF file.
        doc.SaveToFile(txtDestPDFFile.Text)
        ' Remove the event handler.
        RemoveHandler doc.SaveProgress, AddressOf Me.DocumentSaveProgress
        ' Dispose the document.
        doc.Dispose()
        doc = Nothing
    End Sub

    Private Sub DocumentSaveProgress(ByVal sender As System.Object, ByVal e As SaveProgressEventArgs)
        saveProgressBar.Value = CType(e.Progress, Integer)
    End Sub

End Class


Samples: SimpleGrid

Samples

SimpleGrid

This samples shows how to draw a simple report. The content of the report is loaded from an XML file.
This sample uses authors.xml file found in \bin folder.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


SimpleGrid.cs

/// <fileName>
/// File name: SimpleGrid.cs
/// </fileName>

using System;
using System.Drawing;
using System.Data;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.SimpleGrid
{
    /// <summary>
    /// This sample will show how to draw a simple report
    /// using content from a database/xml file.
    /// </summary>
    class SimpleGrid
    {
        private static float leftMargin = 15;
        private static float rightMargin = 15;
        private static float topMargin = 20;
        private static float minBottomMargin = 20;
        private static float rowHeight = 30;
        private static float headerHeight = 30;
        private static float firstPageTopOffset = 50;
        private static float[] columnsWidth = { 80, 100, 100, 90, 212, 90, 40, 50 };
        private static string[] columnsHeader = { "Author ID", "First name", "Last name", "Phone",
                                                    "Address", "City", "State", "ZIP" };

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the graphic objects
            PDFFont fontTitle = new PDFFont( FontFace.Helvetica, 20 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );
            // Set the document to be Landscape oriented
            pdfDoc.PageOrientation = PageOrientation.Landscape;

            // Create first page of the report
            PDFPage page = pdfDoc.AddPage( );

            // Draw the title of the report
            page.Canvas.DrawText( "Authors", fontTitle, null, blackBrush,
                page.Width/2, 15, 0, TextAlign.TopCenter );

            // Draw report header
            DrawReportHeader( page, firstPageTopOffset );

            // Create the dataset
            DataSet ds = new DataSet( );

            // Load the dataset
            ds.ReadXml( "authors.xml", XmlReadMode.ReadSchema );

            // Get the table from the dataset
            DataTable authors = ds.Tables[0];

            // rowOffset - specifies the vertical position where a row
            // should begin to be printed
            float rowOffset = firstPageTopOffset + headerHeight;
            for( int i = 0; i < authors.Rows.Count; i++ )
            {
                if( rowOffset + rowHeight > page.Height - minBottomMargin )
                { // not enough space to draw a new row, then create a new page,
                  // draw the header, then draw the rows.
                    page = pdfDoc.AddPage( );
                    DrawReportHeader( page, topMargin );
                    rowOffset = topMargin + headerHeight;
                }
                DrawReportRow( page, rowOffset, authors.Rows[i] );
                rowOffset = rowOffset + rowHeight;
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "simplegrid.pdf" );
        }

        private static void DrawReportHeader( PDFPage pdfPage, float topOffset )
        {
            // Create the graphic objects
            PDFFont fontHeader = new PDFFont( FontFace.Helvetica, 12 );
            fontHeader.Bold = true;
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush headerFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw the header
            pdfPage.Canvas.DrawRectangle( borderColor, headerFill, topOffset, leftMargin,
                pdfPage.Width - leftMargin - rightMargin, headerHeight );

            int i;
            float xOffset = leftMargin;
            // Draw the columns separators
            for( i = 0; i < columnsWidth.Length - 1; i++ )
            {
                xOffset = xOffset + columnsWidth[i];
                pdfPage.Canvas.DrawLine( borderColor, xOffset, topOffset,
                    xOffset, topOffset + headerHeight );
            }

            xOffset = leftMargin;
            // Draw the columns header
            for( i = 0; i < columnsWidth.Length; i++ )
            {
                pdfPage.Canvas.DrawText( columnsHeader[i], fontHeader, null, textColor,
                    xOffset + columnsWidth[i]/2, topOffset + headerHeight/2, 0, TextAlign.MiddleCenter );
                xOffset = xOffset + columnsWidth[i];
            }
        }

        private static void DrawReportRow( PDFPage pdfPage, float topOffset, DataRow row )
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush headerFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw rows borders
            PointF[] points = { new PointF( leftMargin, topOffset ),
                                  new PointF( leftMargin, topOffset + rowHeight),
                                  new PointF( pdfPage.Width - rightMargin, topOffset + rowHeight ),
                                  new PointF( pdfPage.Width - rightMargin, topOffset )};
            pdfPage.Canvas.DrawLines( borderColor, points );

            int i;
            float xOffset = leftMargin;
            // Draw the columns separators
            for( i = 0; i < columnsWidth.Length - 1; i++ )
            {
                xOffset = xOffset + columnsWidth[i];
                pdfPage.Canvas.DrawLine( borderColor, xOffset, topOffset,
                    xOffset, topOffset + rowHeight );
            }

            xOffset = leftMargin;
            // Draw the columns header
            for( i = 0; i < columnsWidth.Length; i++ )
            {
                pdfPage.Canvas.DrawText( ( string )row[i], fontText, null, textColor,
                    xOffset + 2, topOffset + rowHeight/2, 0, TextAlign.MiddleLeft );
                xOffset = xOffset + columnsWidth[i];
            }

        }
    }
}


SimpleGrid.vb

'
' File name: SimpleGrid.vb
'

Imports System
Imports System.Drawing
Imports System.Data
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.SimpleGrid
    '/ <summary>
    '/ This sample will show how to draw a simple report
    '/ using content from a database/xml file.
    '/ </summary>
    Class SimpleGrid
        Private Shared leftMargin As Single = 15
        Private Shared rightMargin As Single = 15
        Private Shared topMargin As Single = 20
        Private Shared minBottomMargin As Single = 20
        Private Shared rowHeight As Single = 30
        Private Shared headerHeight As Single = 30
        Private Shared firstPageTopOffset As Single = 50
        Private Shared columnsWidth As Single() = {80, 100, 100, 90, 212, 90, 40, 50}
        Private Shared columnsHeader As String() = {"Author ID", "First name", "Last name", "Phone", "Address", "City", "State", "ZIP"}

        Shared Sub Main()
            ' Create the graphic objects
            Dim fontTitle As New PDFFont(FontFace.Helvetica, 20)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()
            ' Set the document to be Landscape oriented
            pdfDoc.PageOrientation = PageOrientation.Landscape

            ' Create first page of the report
            Dim page As PDFPage = pdfDoc.AddPage()

            ' Draw the title of the report
            page.Canvas.DrawText("Authors", fontTitle, Nothing, blackBrush, page.Width / 2, 15, 0, TextAlign.TopCenter)

            ' Draw report header
            DrawReportHeader(page, firstPageTopOffset)

            ' Create the dataset
            Dim ds As New DataSet()

            ' Load the dataset
            ds.ReadXml("authors.xml", XmlReadMode.ReadSchema)

            ' Get the table from the dataset
            Dim authors As DataTable = ds.Tables(0)

            ' rowOffset - specifies the vertical position where a row
            ' should begin to be printed
            Dim rowOffset As Single = firstPageTopOffset + headerHeight
            Dim i As Integer
            For i = 0 To authors.Rows.Count - 1
                If rowOffset + rowHeight > page.Height - minBottomMargin Then
                    ' not enough space to draw a new row, then create a new page,
                    ' draw the header, then draw the rows.
                    page = pdfDoc.AddPage()
                    DrawReportHeader(page, topMargin)
                    rowOffset = topMargin + headerHeight
                End If
                DrawReportRow(page, rowOffset, authors.Rows(i))
                rowOffset = rowOffset + rowHeight
            Next i

            ' Save the document to disk
            pdfDoc.SaveToFile("simplegrid.pdf")
        End Sub 'Main

        Private Shared Sub DrawReportHeader(ByVal pdfPage As PDFPage, ByVal topOffset As Single)
            ' Create the graphic objects
            Dim fontHeader As New PDFFont(FontFace.Helvetica, 12)
            fontHeader.Bold = True
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim headerFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw the header
            pdfPage.Canvas.DrawRectangle(borderColor, headerFill, topOffset, leftMargin, pdfPage.Width - leftMargin - rightMargin, headerHeight)

            Dim i As Integer
            Dim xOffset As Single = leftMargin
            ' Draw the columns separators
            For i = 0 To (columnsWidth.Length - 1) - 1
                xOffset = xOffset + columnsWidth(i)
                pdfPage.Canvas.DrawLine(borderColor, xOffset, topOffset, xOffset, topOffset + headerHeight)
            Next i

            xOffset = leftMargin
            ' Draw the columns header
            For i = 0 To columnsWidth.Length - 1
                pdfPage.Canvas.DrawText(columnsHeader(i), fontHeader, Nothing, textColor, xOffset + columnsWidth(i) / 2, topOffset + headerHeight / 2, 0, TextAlign.MiddleCenter)
                xOffset = xOffset + columnsWidth(i)
            Next i
        End Sub 'DrawReportHeader

        Private Shared Sub DrawReportRow(ByVal pdfPage As PDFPage, ByVal topOffset As Single, ByVal row As DataRow)
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim headerFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw rows borders
            Dim points As PointF() = {New PointF(leftMargin, topOffset), New PointF(leftMargin, topOffset + rowHeight), New PointF(pdfPage.Width - rightMargin, topOffset + rowHeight), New PointF(pdfPage.Width - rightMargin, topOffset)}
            pdfPage.Canvas.DrawLines(borderColor, points)

            Dim i As Integer
            Dim xOffset As Single = leftMargin
            ' Draw the columns separators
            For i = 0 To (columnsWidth.Length - 1) - 1
                xOffset = xOffset + columnsWidth(i)
                pdfPage.Canvas.DrawLine(borderColor, xOffset, topOffset, xOffset, topOffset + rowHeight)
            Next i

            xOffset = leftMargin
            ' Draw the columns header
            For i = 0 To columnsWidth.Length - 1
                pdfPage.Canvas.DrawText(CStr(row(i)), fontText, Nothing, textColor, xOffset + 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleLeft)
                xOffset = xOffset + columnsWidth(i)
            Next i
        End Sub 'DrawReportRow
    End Class 'SimpleGrid
End Namespace 'O2S.Samples.PDF4NET.SimpleGrid


Samples: Sin(x) Graph

Samples

Sin(x) Graph

This sample shows how to use user defined logical units, define them and change the current logical unit during the drawing process. It will also show how to move the coordinate system in order to better fit the drawing needs. The sample will draw the graph of Sin(x) function, using 3 different user defined logical units. These 3 units will be equal on X axis, but they will be different on Y axis.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Sinus.cs

/// <fileName>
/// File name: Sinus.cs
/// </fileName>

using System;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Sinus
{
    /// <summary>
    /// This sample shows how to use user defined logical units,
    /// define them and change the current logical unit
    /// during the drawing process. It will also show how to move
    /// the coordinate system in order to better fit the drawing needs.
    /// The sample will draw the graph of Sin(x) function, using 3
    /// different user defined logical units. These 3 units will be
    /// equal on X axis, but they will be different on Y axis.
    /// </summary>
    class Sinus
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            PDFPen redPen = new PDFPen( new PDFColor( 255, 0, 0 ), 1 );
            PDFPen bluePen = new PDFPen( new PDFColor( 0, 0, 192 ), 1 );
            PDFPen greenPen = new PDFPen( new PDFColor( 0, 192, 0 ), 1 );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            // Create first page of the document
            PDFPage page = pdfDoc.AddPage( );

            // Setup Graph (draw axes, draw labels)
            SetupGraph( page );

            // Create a new logical unit
            CustomUnit1 un1 = new CustomUnit1( );

            DrawGraph( page, un1, redPen );

            // Create a new logical unit
            CustomUnit2 un2 = new CustomUnit2( );

            DrawGraph( page, un2, bluePen );

            // Create an inch logical unit
            PDFInchLogicalUnit inch = new PDFInchLogicalUnit( );

            DrawGraph( page, inch, greenPen );

            // Save the document to disk
            pdfDoc.SaveToFile( "sinus.pdf" );
        }

        public static void SetupGraph( PDFPage page )
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 10 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFPen blackPen = new PDFPen( new PDFColor( ), 1 );

            page.Canvas.DrawText( "Sin(x) graph", fontText, null, blackBrush, 50, 50 );
            page.Canvas.DrawTextBox( "All 3 graphs are drawn at the same logical " +
                "position on the page. The difference between them is the logical " +
                "unit that has been used for drawing each graph. Each logical unit " +
                "performed a different mapping between the logical position and the " +
                "physical position on the page.", fontText, null, blackBrush, 50, 70, 250, 0,
                0, TextAlign.TopLeft, false, 2 );

            // Move the origin of the coordinate system to the
            // center of the page
            page.Canvas.SetOrigin( page.Width/2, page.Height/2 );

            // Set the direction of Y axis to BottomToTop
            // and leave the X axis unchanged
            page.Canvas.SetAxesDirection( XAxisDirection.LeftToRight,
                YAxisDirection.BottomToTop );

            // Draw the axes of the coordinate system
            // Draw the Y axis. Adjust 50 pixels to have
            // some space between the end of the axis and
            // the page margin.
            page.Canvas.DrawLine( blackPen, 0, - ( page.Height/2 - 50 ), 0, page.Height/2 - 50 );
            // Draw the X axis.
            page.Canvas.DrawLine( blackPen, - ( page.Width/2 - 50 ), 0, page.Width/2 - 50, 0 );

            page.Canvas.DrawText( "0", fontText, null, blackBrush, 1, -1 );
            page.Canvas.DrawText( "x", fontText, null, blackBrush, page.Width/2 - 55, -1 );
            page.Canvas.DrawText( "y", fontText, null, blackBrush, 1, page.Height/2 - 50 );
        }

        /// <summary>
        /// Draws the Sin(x) graph on the given page using the specified logical unit.
        /// </summary>
        /// <param name="page">The page to draw to.</param>
        /// <param name="lu">The logical unit used to position the graph.</param>
        /// <param name="pen">The pen used to draw the graph.</param>
        public static void DrawGraph( PDFPage page, PDFLogicalUnitBase lu, PDFPen pen )
        {
            float y1, y2, x1, x2;

            // Set the unit for the page
            page.Canvas.SetLogicalUnit( lu );

            // i goes from -180 degrees to 180 degrees (=Math.PI)
            for( int i = -180; i < 180; i++ )
            {
                x1 = ( float )( i * Math.PI/180 );
                y1 = ( float )Math.Sin( x1 );
                x2 = ( float )( ( i + 1 ) * Math.PI/180 );
                y2 = ( float )Math.Sin( x2 );

                page.Canvas.DrawLine( pen, x1, y1, x2, y2 );
            }
        }
    }

    /// <summary>
    /// Defines a custom unit that specifies different mappings for X
    /// and Y axis. The unit on Y axis equals to 3 inch (3*72 points),
    /// and the unit on X axis equals 1 inch.
    /// </summary>
    class CustomUnit1 : PDFLogicalUnitBase
    {
        public CustomUnit1( )
        {
        }

        public override float ToPDFUnitX(float unit)
        {
            return unit * 72;
        }

        public override float ToPDFUnitY(float unit)
        {
            return unit * 72 * 3;
        }
    }

    /// <summary>
    /// Defines a custom unit that specifies different mappings for X
    /// and Y axis. The unit on Y axis equals to 2 inch (2*72 points),
    /// and the unit on X axis equals 1 inch.
    /// </summary>
    class CustomUnit2 : PDFLogicalUnitBase
    {
        public CustomUnit2( )
        {
        }

        public override float ToPDFUnitX(float unit)
        {
            return unit * 72;
        }

        public override float ToPDFUnitY(float unit)
        {
            return unit * 72 * 2;
        }
    }
}


Sinus.vb

'
' File name: Sinus.vb
'

Imports System
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.Sinus
    '/ <summary>
    '/ This sample shows how to use user defined logical units,
    '/ define them and change the current logical unit
    '/ during the drawing process. It will also show how to move
    '/ the coordinate system in order to better fit the drawing needs.
    '/ The sample will draw the graph of Sin(x) function, using 3
    '/ different user defined logical units. These 3 units will be
    '/ equal on X axis, but they will be different on Y axis.
    '/ </summary>
    Class Sinus

        Shared Sub Main()
            Dim redPen As New PDFPen(New PDFColor(255, 0, 0), 1)
            Dim bluePen As New PDFPen(New PDFColor(0, 0, 192), 1)
            Dim greenPen As New PDFPen(New PDFColor(0, 192, 0), 1)

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            ' Create first page of the document
            Dim page As PDFPage = pdfDoc.AddPage()

            ' Setup Graph (draw axes, draw labels)
            SetupGraph(page)

            ' Create a new logical unit
            Dim un1 As New CustomUnit1()

            DrawGraph(page, un1, redPen)

            ' Create a new logical unit
            Dim un2 As New CustomUnit2()

            DrawGraph(page, un2, bluePen)

            ' Create an inch logical unit
            Dim inch As New PDFInchLogicalUnit()

            DrawGraph(page, inch, greenPen)

            ' Save the document to disk
            pdfDoc.SaveToFile("sinus.pdf")
        End Sub 'Main

        Public Shared Sub SetupGraph(ByVal page As PDFPage)
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 10)
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim blackPen As New PDFPen(New PDFColor(), 1)

            page.Canvas.DrawText("Sin(x) graph", fontText, Nothing, blackBrush, 50, 50)
            page.Canvas.DrawTextBox("All 3 graphs are drawn at the same logical " + "position on the page. The difference between them is the logical " + "unit that has been used for drawing each graph. Each logical unit " + "performed a different mapping between the logical position and the " + "physical position on the page.", fontText, Nothing, blackBrush, 50, 70, 250, 0, 0, TextAlign.TopLeft, False, 2)

            ' Move the origin of the coordinate system to the
            ' center of the page
            page.Canvas.SetOrigin(page.Width / 2, page.Height / 2)

            ' Set the direction of Y axis to BottomToTop
            ' and leave the X axis unchanged
            page.Canvas.SetAxesDirection(XAxisDirection.LeftToRight, YAxisDirection.BottomToTop)

            ' Draw the axes of the coordinate system
            ' Draw the Y axis. Adjust 50 pixels to have
            ' some space between the end of the axis and
            ' the page margin.
            page.Canvas.DrawLine(blackPen, 0, -(page.Height / 2 - 50), 0, page.Height / 2 - 50)
            ' Draw the X axis.
            page.Canvas.DrawLine(blackPen, -(page.Width / 2 - 50), 0, page.Width / 2 - 50, 0)

            page.Canvas.DrawText("0", fontText, Nothing, blackBrush, 1, -1)
            page.Canvas.DrawText("x", fontText, Nothing, blackBrush, page.Width / 2 - 55, -1)
            page.Canvas.DrawText("y", fontText, Nothing, blackBrush, 1, page.Height / 2 - 50)
        End Sub 'SetupGraph

        '/ <summary>
        '/ Draws the Sin(x) graph on the given page using the specified logical unit.
        '/ </summary>
        '/ <param name="page">The page to draw to.</param>
        '/ <param name="lu">The logical unit used to position the graph.</param>
        '/ <param name="pen">The pen used to draw the graph.</param>
        Public Shared Sub DrawGraph(ByVal page As PDFPage, ByVal lu As PDFLogicalUnitBase, ByVal pen As PDFPen)
            Dim y1, y2, x1, x2 As Single

            ' Set the unit for the page
            page.Canvas.SetLogicalUnit(lu)

            ' i goes from -180 degrees to 180 degrees (=Math.PI)
            Dim i As Integer
            For i = -180 To 179
                x1 = CSng(i * Math.PI / 180)
                y1 = CSng(Math.Sin(x1))
                x2 = CSng((i + 1) * Math.PI / 180)
                y2 = CSng(Math.Sin(x2))

                page.Canvas.DrawLine(pen, x1, y1, x2, y2)
            Next i
        End Sub 'DrawGraph
    End Class 'Sinus
    _

    '/ <summary>
    '/ Defines a custom unit that specifies different mappings for X
    '/ and Y axis. The unit on Y axis equals to 3 inch (3*72 points),
    '/ and the unit on X axis equals 1 inch.
    '/ </summary>
    Class CustomUnit1
        Inherits PDFLogicalUnitBase

        Public Sub New()
        End Sub 'New

        Public Overrides Function ToPDFUnitX(ByVal unit As Single) As Single
            Return unit * 72
        End Function 'ToPDFUnitX

        Public Overrides Function ToPDFUnitY(ByVal unit As Single) As Single
            Return unit * 72 * 3
        End Function 'ToPDFUnitY
    End Class 'CustomUnit1
    _

    '/ <summary>
    '/ Defines a custom unit that specifies different mappings for X
    '/ and Y axis. The unit on Y axis equals to 2 inch (2*72 points),
    '/ and the unit on X axis equals 1 inch.
    '/ </summary>
    Class CustomUnit2
        Inherits PDFLogicalUnitBase

        Public Sub New()
        End Sub 'New

        Public Overrides Function ToPDFUnitX(ByVal unit As Single) As Single
            Return unit * 72
        End Function 'ToPDFUnitX

        Public Overrides Function ToPDFUnitY(ByVal unit As Single) As Single
            Return unit * 72 * 2
        End Function 'ToPDFUnitY
    End Class 'CustomUnit2
End Namespace 'O2S.Samples.PDF4NET.Sinus


Samples: SlideShow

Samples

SlideShow

This samples shows the transition effects available in pdf files. This sample is identical with SimpleGrid sample, but it uses transition effects when passing from one page to another.
This sample uses authors.xml file found in \bin folder.

C# Source code | VB.NET Source code | PDF file

� 2003 - 2007 O2 Solutions. All rights reserved.


SlideShow.cs

/// <fileName>
/// File name: SlideShow.cs
/// </fileName>

using System;
using System.Data;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.SlideShow
{
    /// <summary>
    /// This sample will show the presentation capabilities
    /// of the pdf document. The report in SimpleGrid sample
    /// uses now transitions to automatically advance from
    /// one page to the next.
    /// </summary>
    class SlideShow
    {
        private static float leftMargin = 15;
        private static float rightMargin = 15;
        private static float topMargin = 20;
        private static float minBottomMargin = 20;
        private static float rowHeight = 30;
        private static float headerHeight = 30;
        private static float firstPageTopOffset = 50;
        private static float[] columnsWidth = { 80, 100, 100, 90, 212, 90, 40, 50 };
        private static string[] columnsHeader = { "Author ID", "First name", "Last name", "Phone",
                                                    "Address", "City", "State", "ZIP" };

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the graphic objects
            PDFFont fontTitle = new PDFFont( FontFace.Helvetica, 20 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );
            // Set the document to be Landscape oriented
            pdfDoc.PageOrientation = PageOrientation.Landscape;

            // Create the transition object
            PDFPageTransition trans = new PDFPageTransition( );
            trans.Effect = PageTransitionEffect.Box;
            trans.PageDuration = 2;
            trans.TransitionDuration = 2;
            trans.TransitionMotionDirection = TransitionMotionDirection.Outward;

            // Create first page of the report
            PDFPage page = pdfDoc.AddPage( );

            // Add the transition to the page
            page.Transition = trans;

            // Draw the title of the report
            page.Canvas.DrawText( "Authors - with transition effects", fontTitle,
                null, blackBrush, page.Width/2, 15, 0, TextAlign.TopCenter );

            // Draw report header
            DrawReportHeader( page, firstPageTopOffset );

            // Create the dataset
            DataSet ds = new DataSet( );

            // Load the dataset
            ds.ReadXml( "authors.xml", XmlReadMode.ReadSchema );

            // Get the table from the dataset
            DataTable authors = ds.Tables[0];

            // rowOffset - specifies the vertical position where a row
            // should begin to be printed
            float rowOffset = firstPageTopOffset + headerHeight;

            for( int i = 0; i < authors.Rows.Count; i++ )
            {
                if( rowOffset + rowHeight > page.Height - minBottomMargin )
                { // not enough space to draw a new row, then create a new page,
                    // draw the header, then draw the rows.
                    page = pdfDoc.AddPage( );

                    // set the transition effect for the page
                    page.Transition = trans;

                    DrawReportHeader( page, topMargin );
                    rowOffset = topMargin + headerHeight;
                }
                DrawReportRow( page, rowOffset, authors.Rows[i] );
                rowOffset = rowOffset + rowHeight;
            }

            // Save the document to disk
            pdfDoc.SaveToFile( "slideshow.pdf" );
        }

        private static void DrawReportHeader( PDFPage pdfPage, float topOffset )
        {
            // Create the graphic objects
            PDFFont fontHeader = new PDFFont( FontFace.Helvetica, 12 );
            fontHeader.Bold = true;
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush headerFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw the header
            pdfPage.Canvas.DrawRectangle( borderColor, headerFill, topOffset, leftMargin,
                pdfPage.Width - leftMargin - rightMargin, headerHeight );

            int i;
            float xOffset = leftMargin;
            // Draw the columns separators
            for( i = 0; i < columnsWidth.Length - 1; i++ )
            {
                xOffset = xOffset + columnsWidth[i];
                pdfPage.Canvas.DrawLine( borderColor, xOffset, topOffset,
                    xOffset, topOffset + headerHeight );
            }

            xOffset = leftMargin;
            // Draw the columns header
            for( i = 0; i < columnsWidth.Length; i++ )
            {
                pdfPage.Canvas.DrawText( columnsHeader[i], fontHeader, null, textColor,
                    xOffset + columnsWidth[i]/2, topOffset + headerHeight/2, 0, TextAlign.MiddleCenter );
                xOffset = xOffset + columnsWidth[i];
            }
        }

        private static void DrawReportRow( PDFPage pdfPage, float topOffset, DataRow row )
        {
            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFPen borderColor = new PDFPen( new PDFColor( ), 1 );
            PDFBrush textColor = new PDFBrush( new PDFColor( ) );
            PDFBrush headerFill = new PDFBrush( new PDFColor( 192, 192, 192 ) );

            // Draw rows borders
            PointF[] points = { new PointF( leftMargin, topOffset ),
                                  new PointF( leftMargin, topOffset + rowHeight),
                                  new PointF( pdfPage.Width - rightMargin, topOffset + rowHeight ),
                                  new PointF( pdfPage.Width - rightMargin, topOffset )};
            pdfPage.Canvas.DrawLines( borderColor, points );

            int i;
            float xOffset = leftMargin;
            // Draw the columns separators
            for( i = 0; i < columnsWidth.Length - 1; i++ )
            {
                xOffset = xOffset + columnsWidth[i];
                pdfPage.Canvas.DrawLine( borderColor, xOffset, topOffset,
                    xOffset, topOffset + rowHeight );
            }

            xOffset = leftMargin;
            // Draw the columns header
            for( i = 0; i < columnsWidth.Length; i++ )
            {
                pdfPage.Canvas.DrawText( ( string )row[i], fontText, null, textColor,
                    xOffset + 2, topOffset + rowHeight/2, 0, TextAlign.MiddleLeft );
                xOffset = xOffset + columnsWidth[i];
            }

        }
    }
}


SlideShow.vb

'
' File name: SlideShow.vb
'

Imports System
Imports System.Data
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.SlideShow
    '/ <summary>
    '/ This sample will show the presentation capabilities
    '/ of the pdf document. The report in SimpleGrid sample
    '/ uses now transitions to automatically advance from
    '/ one page to the next.
    '/ </summary>
    Class SlideShow
        Private Shared leftMargin As Single = 15
        Private Shared rightMargin As Single = 15
        Private Shared topMargin As Single = 20
        Private Shared minBottomMargin As Single = 20
        Private Shared rowHeight As Single = 30
        Private Shared headerHeight As Single = 30
        Private Shared firstPageTopOffset As Single = 50
        Private Shared columnsWidth As Single() = {80, 100, 100, 90, 212, 90, 40, 50}
        Private Shared columnsHeader As String() = {"Author ID", "First name", "Last name", "Phone", "Address", "City", "State", "ZIP"}

        Shared Sub Main()
            ' Create the graphic objects
            Dim fontTitle As New PDFFont(FontFace.Helvetica, 20)
            Dim blackBrush As New PDFBrush(New PDFColor())

            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()
            ' Set the document to be Landscape oriented
            pdfDoc.PageOrientation = PageOrientation.Landscape

            ' Create the transition object
            Dim trans As New PDFPageTransition()
            trans.Effect = PageTransitionEffect.Box
            trans.PageDuration = 2
            trans.TransitionDuration = 2
            trans.TransitionMotionDirection = TransitionMotionDirection.Outward

            ' Create first page of the report
            Dim page As PDFPage = pdfDoc.AddPage()

            ' Add the transition to the page
            page.Transition = trans

            ' Draw the title of the report
            page.Canvas.DrawText("Authors - with transition effects", fontTitle, Nothing, blackBrush, page.Width / 2, 15, 0, TextAlign.TopCenter)

            ' Draw report header
            DrawReportHeader(page, firstPageTopOffset)

            ' Create the dataset
            Dim ds As New DataSet()

            ' Load the dataset
            ds.ReadXml("authors.xml", XmlReadMode.ReadSchema)

            ' Get the table from the dataset
            Dim authors As DataTable = ds.Tables(0)

            ' rowOffset - specifies the vertical position where a row
            ' should begin to be printed
            Dim rowOffset As Single = firstPageTopOffset + headerHeight

            Dim i As Integer
            For i = 0 To authors.Rows.Count - 1
                If rowOffset + rowHeight > page.Height - minBottomMargin Then
                    ' not enough space to draw a new row, then create a new page,
                    ' draw the header, then draw the rows.
                    page = pdfDoc.AddPage()

                    ' set the transition effect for the page
                    page.Transition = trans

                    DrawReportHeader(page, topMargin)
                    rowOffset = topMargin + headerHeight
                End If
                DrawReportRow(page, rowOffset, authors.Rows(i))
                rowOffset = rowOffset + rowHeight
            Next i

            ' Save the document to disk
            pdfDoc.SaveToFile("slideshow.pdf")
        End Sub 'Main

        Private Shared Sub DrawReportHeader(ByVal pdfPage As PDFPage, ByVal topOffset As Single)
            ' Create the graphic objects
            Dim fontHeader As New PDFFont(FontFace.Helvetica, 12)
            fontHeader.Bold = True
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim headerFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw the header
            pdfPage.Canvas.DrawRectangle(borderColor, headerFill, topOffset, leftMargin, pdfPage.Width - leftMargin - rightMargin, headerHeight)

            Dim i As Integer
            Dim xOffset As Single = leftMargin
            ' Draw the columns separators
            For i = 0 To (columnsWidth.Length - 1) - 1
                xOffset = xOffset + columnsWidth(i)
                pdfPage.Canvas.DrawLine(borderColor, xOffset, topOffset, xOffset, topOffset + headerHeight)
            Next i

            xOffset = leftMargin
            ' Draw the columns header
            For i = 0 To columnsWidth.Length - 1
                pdfPage.Canvas.DrawText(columnsHeader(i), fontHeader, Nothing, textColor, xOffset + columnsWidth(i) / 2, topOffset + headerHeight / 2, 0, TextAlign.MiddleCenter)
                xOffset = xOffset + columnsWidth(i)
            Next i
        End Sub 'DrawReportHeader

        Private Shared Sub DrawReportRow(ByVal pdfPage As PDFPage, ByVal topOffset As Single, ByVal row As DataRow)
            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim borderColor As New PDFPen(New PDFColor(), 1)
            Dim textColor As New PDFBrush(New PDFColor())
            Dim headerFill As New PDFBrush(New PDFColor(192, 192, 192))

            ' Draw rows borders
            Dim points As PointF() = {New PointF(leftMargin, topOffset), New PointF(leftMargin, topOffset + rowHeight), New PointF(pdfPage.Width - rightMargin, topOffset + rowHeight), New PointF(pdfPage.Width - rightMargin, topOffset)}
            pdfPage.Canvas.DrawLines(borderColor, points)

            Dim i As Integer
            Dim xOffset As Single = leftMargin
            ' Draw the columns separators
            For i = 0 To (columnsWidth.Length - 1) - 1
                xOffset = xOffset + columnsWidth(i)
                pdfPage.Canvas.DrawLine(borderColor, xOffset, topOffset, xOffset, topOffset + rowHeight)
            Next i

            xOffset = leftMargin
            ' Draw the columns header
            For i = 0 To columnsWidth.Length - 1
                pdfPage.Canvas.DrawText(CStr(row(i)), fontText, Nothing, textColor, xOffset + 2, topOffset + rowHeight / 2, 0, TextAlign.MiddleLeft)
                xOffset = xOffset + columnsWidth(i)
            Next i
        End Sub 'DrawReportRow
    End Class 'SlideShow
End Namespace 'O2S.Samples.PDF4NET.SlideShow


Samples: Stamp PDF

Samples

Stamp PDF

This sample shows how to stamp a PDF file. A PDF file can be stamped with any combination of text, graphics, images and annotations. The stamps can be opaque or transparent. First page in the sample is stamped with a rubber stamp annotation, second page is stamped with regular text and third page is stamped with a transparent image.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


StampPDF.cs

/// <fileName>
/// File name: StampPDF.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Annotations;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.StampPDF
{
    /// <summary>
    /// This sample shows how to stamp existing PDF files with stamp annotations, text or images.
    /// </summary>
    class StampPDF
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Import the pdf document
            PDFDocument doc = new PDFDocument( "sample.pdf" );

            // stamp first page with a rubber stamp annotation.
            PDFRubberStampAnnotation rsa = new PDFRubberStampAnnotation( "Approved", "This document has been approved." );
            rsa.Icon = RubberStampAnnotationIcon.Approved;
            rsa.Rectangle = new RectangleF( 50, 50, 500, 100 );
            // make the stamp transparent, so the text behind it is visible
            rsa.Opacity = 50;
            doc.Pages[0].Annotations.Add( rsa );

            // stamp second page with regular text.
            PDFFont font = new PDFFont( FontFace.Helvetica, 96 );
            font.Bold = true;
            PDFBrush greenBrush = new PDFBrush( new PDFColor( Color.Green ) );
            // make the stamp transparent
            doc.Pages[1].Canvas.SetTransparency( 50 );
            doc.Pages[1].Canvas.DrawText( "Approved", font, null, greenBrush,
                doc.Pages[1].Width/2, 120, 20, TextAlign.MiddleCenter );
            doc.Pages[1].Canvas.SetTransparency( 0 );

            // stamp third page with an image.
            // make the stamp transparent
            doc.Pages[2].Canvas.SetTransparency( 50 );
            doc.Pages[2].Canvas.DrawImage( "auto1.jpg", 200, 500, 300, 1, 20, KeepAspectRatio.KeepWidth );
            doc.Pages[2].Canvas.SetTransparency( 0 );

            // Save the document to disk
            doc.SaveToFile( "stamppdf.pdf" );
        }
    }
}


StampPDF.vb

'
' File name: StampPDF.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Annotations
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to stamp existing PDF files with stamp annotations, text or images.
'/ </summary>

Class StampPDF
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Import the pdf document
        Dim doc As New PDFDocument("sample.pdf")

        ' stamp first page with a rubber stamp annotation.
        Dim rsa As New PDFRubberStampAnnotation("Approved", "This document has been approved.")
        rsa.Icon = RubberStampAnnotationIcon.Approved
        rsa.Rectangle = New RectangleF(50, 50, 500, 100)
        ' make the stamp transparent, so the text behind it is visible
        rsa.Opacity = 50
        doc.Pages(0).Annotations.Add(rsa)

        ' stamp second page with regular text.
        Dim font As New PDFFont(FontFace.Helvetica, 96)
        font.Bold = True
        Dim greenBrush As New PDFBrush(New PDFColor(Color.Green))
        ' make the stamp transparent
        doc.Pages(1).Canvas.SetTransparency(50)
        doc.Pages(1).Canvas.DrawText("Approved", font, Nothing, greenBrush, doc.Pages(1).Width / 2, 120, 20, TextAlign.MiddleCenter)
        doc.Pages(1).Canvas.SetTransparency(0)

        ' stamp third page with an image.
        ' make the stamp transparent
        doc.Pages(2).Canvas.SetTransparency(50)
        doc.Pages(2).Canvas.DrawImage("auto1.jpg", 200, 500, 300, 1, 20, KeepAspectRatio.KeepWidth)
        doc.Pages(2).Canvas.SetTransparency(0)

        ' Save the document to disk
        doc.SaveToFile("stamppdf.pdf")
    End Sub 'Main
End Class 'StampPDF


Samples: Templates

Samples

Templates

This samples shows template capabilites of the PDF4NET library. A template is created from an existing PDF page. Then it imports a PDF document, adds 10 additional pages and attached the template to the document. The template is drawn under existing page content.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Templates.cs

/// <fileName>
/// File name: Templates.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Templates
{
    /// <summary>
    /// This sample will show how to use common content
    /// on multiple pages using templates.
    /// </summary>
    class Templates
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // The default page size is letter
            const int width = 612;
            const int height = 792;

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFFont fontTitle = new PDFFont( FontFace.Helvetica, 72 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFPen blackPen = new PDFPen( new PDFColor( ), 1 );

            // Import a sample pdf document
            PDFDocument pdfDoc = new PDFDocument( "sample.pdf" );

            // Create the template from a PDF file and attach it to the document
            PDFPageTemplate tmpl = new PDFPageTemplate( "one-page-template.pdf", 0, 0, 0, width, height );
            pdfDoc.PageTemplate = tmpl;

            // Create 10 additional pages
            for( int i = 0; i < 10; i++ )
            {
                PDFPage pdfPage = pdfDoc.AddPage( );
                if( i > 0 )
                {
                    pdfPage.Canvas.DrawText( "Page " + i.ToString( ),
                        fontTitle, null, blackBrush, pdfPage.Width/2,
                        pdfPage.Height/2, 0, TextAlign.MiddleCenter );
                }
            }

            // Do not apply the template on 6th page
            pdfDoc.Pages[5].ApplyTemplate = false;

            // Draw the title on the 6th page (the first of the newly 10 added pages)
            pdfDoc.Pages[5].Canvas.DrawText( "Templates",
                fontTitle, null, blackBrush, pdfDoc.Pages[0].Width/2,
                pdfDoc.Pages[0].Height/2, 0, TextAlign.MiddleCenter );

            // Save the document to disk
            pdfDoc.SaveToFile( "templates.pdf" );
        }
    }
}


Templates.vb

'
' File name: Templates.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample will show how to use common content
'/ on multiple pages using templates.
'/ </summary>

Class Templates
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' The default page size is letter
        Const width As Integer = 612
        Const height As Integer = 792

        ' Create the graphic objects
        Dim fontText As New PDFFont(FontFace.Helvetica, 12)
        Dim fontTitle As New PDFFont(FontFace.Helvetica, 72)
        Dim blackBrush As New PDFBrush(New PDFColor)
        Dim blackPen As New PDFPen(New PDFColor, 1)

        ' Import a sample pdf document
        Dim pdfDoc As New PDFDocument("sample.pdf")

        ' Create the template from a PDF file and attach it to the document
        Dim tmpl As New PDFPageTemplate("one-page-template.pdf", 0, 0, 0, width, height)
        pdfDoc.PageTemplate = tmpl

        ' Create 10 additional pages
        Dim i As Integer
        For i = 0 To 9
            Dim pdfPage As PDFPage = pdfDoc.AddPage()
            If i > 0 Then
                pdfPage.Canvas.DrawText("Page " + i.ToString(), fontTitle, Nothing, blackBrush, pdfPage.Width / 2, pdfPage.Height / 2, 0, TextAlign.MiddleCenter)
            End If
        Next i

        ' Do not apply the template on 6th page
        pdfDoc.Pages(5).ApplyTemplate = False

        ' Draw the title on the 6th page (the first of the newly 10 added pages)
        pdfDoc.Pages(5).Canvas.DrawText("Templates", fontTitle, Nothing, blackBrush, pdfDoc.Pages(0).Width / 2, pdfDoc.Pages(0).Height / 2, 0, TextAlign.MiddleCenter)

        ' Save the document to disk
        pdfDoc.SaveToFile("templates.pdf")
    End Sub 'Main
End Class 'Templates


Samples: TextBoxes

Samples

TextBoxes - with TrueType font support

This samples shows the columnar text drawing capabilities of the PDF4NET library. On the first page, it shows all the possible alignments of the text inside a box. On the second page is shows how to draw rotated text boxes or how the constrain the text to stay inside the box. It also shows how the text can be let to flow out of the box if it does not fit inside it. The text uses Verdana font for display.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


TextBoxes.cs

/// <fileName>
/// File name: TextBoxes.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Graphics.Fonts;

namespace O2S.Samples.PDF4NET.TextBoxes
{
    /// <summary>
    /// This sample will show the available possibilities
    /// for columnar text formatting.
    /// </summary>
    class TextBoxes
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );
                        TrueTypeFont ttf = new TrueTypeFont( "verdana.ttf", 12, true );

            DrawFirstPage( pdfDoc, ttf );
            DrawSecondPage( pdfDoc, ttf );

            // Save the document to disk
            pdfDoc.SaveToFile( "textboxes.pdf" );
        }

        //private static void DrawFirstPage( PDFDocument pdfDoc, TrueTypeFont fnt )
        private static void DrawFirstPage( PDFDocument pdfDoc, PDFFont fnt )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFPen redPen = new PDFPen( new PDFColor( 255, 0, 0 ), 1 );

            // Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle2( redPen, null, 20, 20, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 190, 20, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 360, 20, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 20, 190, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 190, 190, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 360, 190, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 20, 360, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 190, 360, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 360, 360, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 20, 530, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 190, 530, 150, 150, 0 );
            pdfPage.Canvas.DrawRectangle2( redPen, null, 360, 530, 150, 150, 0 );

            // Draw the text
            // Top align
            PDFTextFormatOptions tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopLeft;
            tfo.ClipText = ClipText.ClipNone;
            pdfPage.Canvas.DrawTextBox( "These lines of text are top left aligned. These lines of text are top left aligned.",
                fnt, null, blackBrush, 20, 20, 150, 150, tfo );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopCenter;
            pdfPage.Canvas.DrawTextBox( "These lines of text are top center aligned. These lines of text are top center aligned.",
                fnt, null, blackBrush, 190, 20, 150, 150, tfo );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopRight;
            pdfPage.Canvas.DrawTextBox( "These lines of text are top right aligned. These lines of text are top right aligned.",
                fnt, null, blackBrush, 360, 20, 150, 150, tfo );
            // Middle align
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.MiddleLeft;
            pdfPage.Canvas.DrawTextBox( "These lines of text are middle left aligned. These lines of text are middle left aligned.",
                fnt, null, blackBrush, 20, 190, 150, 150, tfo  );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.MiddleCenter;
            pdfPage.Canvas.DrawTextBox( "These lines of text are middle center aligned. These lines of text are middle center aligned.",
                fnt, null, blackBrush, 190, 190, 150, 150, tfo );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.MiddleRight;
            pdfPage.Canvas.DrawTextBox( "These lines of text are middle right aligned. These lines of text are middle right aligned.",
                fnt, null, blackBrush, 360, 190, 150, 150, tfo );
            // Bottom align
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.BottomLeft;
            pdfPage.Canvas.DrawTextBox( "These lines of text are bottom left aligned. These lines of text are bottom left aligned.",
                fnt, null, blackBrush, 20, 360, 150, 150, tfo );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.BottomCenter;
            pdfPage.Canvas.DrawTextBox( "These lines of text are bottom center aligned. These lines of text are bottom center aligned.",
                fnt, null, blackBrush, 190, 360, 150, 150, tfo );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.BottomRight;
            pdfPage.Canvas.DrawTextBox( "These lines of text are bottom right aligned. These lines of text are bottom right aligned.",
                fnt, null, blackBrush, 360, 360, 150, 150, tfo );
            // Justification
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopJustified;
            pdfPage.Canvas.DrawTextBox( "These lines of text are top justify aligned. These lines of text are top justify aligned.",
                fnt, null, blackBrush, 20, 530, 150, 150, tfo );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.MiddleJustified;
            pdfPage.Canvas.DrawTextBox( "These lines of text are middle justify aligned. These lines of text are middle justify aligned.",
                fnt, null, blackBrush, 190, 530, 150, 150, tfo );
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.BottomJustified;
            pdfPage.Canvas.DrawTextBox( "These lines of text are bottom justify aligned. These lines of text are bottom justify justify aligned.",
                fnt, null, blackBrush, 360, 530, 150, 150, tfo );
        }

        //private static void DrawSecondPage( PDFDocument pdfDoc, TrueTypeFont fnt )
        private static void DrawSecondPage( PDFDocument pdfDoc, PDFFont fnt )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFPen redPen = new PDFPen( new PDFColor( 255, 0, 0 ), 1 );

            // Draw a label
            pdfPage.Canvas.DrawText( "Rotated text box",
                fnt, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle2( redPen, null, 190, 100, 150, 150, 30 );

            // Draw the text
            PDFTextFormatOptions tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopLeft;
            tfo.Orientation = 30;
            pdfPage.Canvas.DrawTextBox( "This text box is rotated with 30 degrees around " +
                "the top left corner. The red border does not belong to the text box. It has " +
                "been drawn using DrawRectangle( ) method.",
                fnt, null, blackBrush, 190, 100, 150, 150, tfo );

            // Draw a label
            pdfPage.Canvas.DrawText( "Clipped text",
                fnt, null, blackBrush, 20, 300, 0, TextAlign.TopLeft );

            // Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle2( redPen, null, 20, 315, 150, 53, 0 );

            // Draw the text
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopLeft;
            pdfPage.Canvas.DrawTextBox( "This text is not allowed to get out of the box. " +
                "This is the default behavior of the text box. The last line will be clipped.",
                fnt, null, blackBrush, 20, 315, 150, 53, tfo );

            // Draw a label
            pdfPage.Canvas.DrawText( "Flow out text",
                fnt, null, blackBrush, 300, 300, 0, TextAlign.TopLeft );

            // Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle2( redPen, null, 300, 315, 150, 53, 0 );

            // Draw the text
            tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopLeft;
            tfo.ClipText = ClipText.ClipNone;
            tfo.LineSpacing = 5;
            pdfPage.Canvas.DrawTextBox( "This text is allowed to get out of the box. " +
                "This behavior can be enforced by setting the clipText parameter to true." +
                "As it can be seen, the text can flow out of the box. " +
                "Also, for this sample, the line spacing has been increased with 5 points.",
                fnt, null, blackBrush, 300, 315, 150, 53, tfo );
        }
    }
}


TextBoxes.vb

'
' File name: TextBoxes.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Graphics.Fonts

Namespace O2S.Samples.PDF4NET.TextBoxes
    _
    '/ <summary>
    '/ This sample will show the available possibilities
    '/ for columnar text formatting.
    '/ </summary>
    Class TextBoxes

        'Entry point which delegates to C-style main Private Function
        'Public Overloads Shared Sub Main()
        'Main(System.Environment.GetCommandLineArgs())
        'End Sub

        '/ <summary>
        '/ The main entry point for the application.
        '/ </summary>
        'Overloads Shared<STAThread()>  _
        'Sub Main(ByVal args() As String)
        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()
            Dim fontText As New TrueTypeFont("verdana.ttf", 12, True)

            DrawFirstPage(pdfDoc, fontText)
            DrawSecondPage(pdfDoc, fontText)

            ' Save the document to disk
            pdfDoc.SaveToFile("textboxes.pdf")
        End Sub 'Main

        Private Shared Sub DrawFirstPage(ByVal pdfDoc As PDFDocument, _
            ByVal fontText As TrueTypeFont)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim redPen As New PDFPen(New PDFColor(255, 0, 0), 1)

            ' Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle(redPen, 20, 20, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 20, 190, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 20, 360, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 190, 20, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 190, 190, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 190, 360, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 360, 20, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 360, 190, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 360, 360, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 530, 20, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 530, 190, 150, 150)
            pdfPage.Canvas.DrawRectangle(redPen, 530, 360, 150, 150)

            ' Draw the text
            ' Top align
            pdfPage.Canvas.DrawTextBox("These lines of text are top left aligned. These lines of text are top left aligned.", fontText, Nothing, blackBrush, 20, 20, 150, 150, 0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawTextBox("These lines of text are top center aligned. These lines of text are top center aligned.", fontText, Nothing, blackBrush, 190, 20, 150, 150, 0, TextAlign.TopCenter)
            pdfPage.Canvas.DrawTextBox("These lines of text are top right aligned. These lines of text are top right aligned.", fontText, Nothing, blackBrush, 360, 20, 150, 150, 0, TextAlign.TopRight)
            ' Middle align
            pdfPage.Canvas.DrawTextBox("These lines of text are middle left aligned. These lines of text are middle left aligned.", fontText, Nothing, blackBrush, 20, 190, 150, 150, 0, TextAlign.MiddleLeft)
            pdfPage.Canvas.DrawTextBox("These lines of text are middle center aligned. These lines of text are middle center aligned.", fontText, Nothing, blackBrush, 190, 190, 150, 150, 0, TextAlign.MiddleCenter)
            pdfPage.Canvas.DrawTextBox("These lines of text are middle right aligned. These lines of text are middle right aligned.", fontText, Nothing, blackBrush, 360, 190, 150, 150, 0, TextAlign.MiddleRight)
            ' Bottom align
            pdfPage.Canvas.DrawTextBox("These lines of text are bottom left aligned. These lines of text are bottom left aligned.", fontText, Nothing, blackBrush, 20, 360, 150, 150, 0, TextAlign.BottomLeft)
            pdfPage.Canvas.DrawTextBox("These lines of text are bottom center aligned. These lines of text are bottom center aligned.", fontText, Nothing, blackBrush, 190, 360, 150, 150, 0, TextAlign.BottomCenter)
            pdfPage.Canvas.DrawTextBox("These lines of text are bottom right aligned. These lines of text are bottom right aligned.", fontText, Nothing, blackBrush, 360, 360, 150, 150, 0, TextAlign.BottomRight)
            ' Justification
            pdfPage.Canvas.DrawTextBox("These lines of text are top justify aligned. These lines of text are top justify aligned.", fontText, Nothing, blackBrush, 20, 530, 150, 150, 0, TextAlign.TopJustified)
            pdfPage.Canvas.DrawTextBox("These lines of text are middle justify aligned. These lines of text are middle justify aligned.", fontText, Nothing, blackBrush, 190, 530, 150, 150, 0, TextAlign.MiddleJustified)
            pdfPage.Canvas.DrawTextBox("These lines of text are bottom justify aligned. These lines of text are bottom justify justify aligned.", fontText, Nothing, blackBrush, 360, 530, 150, 150, 0, TextAlign.BottomJustified)
        End Sub 'DrawFirstPage

        Private Shared Sub DrawSecondPage(ByVal pdfDoc As PDFDocument, _
            ByVal fontText As TrueTypeFont)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim blackBrush As New PDFBrush(New PDFColor())
            Dim redPen As New PDFPen(New PDFColor(255, 0, 0), 1)

            ' Draw a label
            pdfPage.Canvas.DrawText("Rotated text box", fontText, Nothing, blackBrush, 20, 20)

            ' Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle(redPen, 100, 190, 150, 150, 30)

            ' Draw the text
            pdfPage.Canvas.DrawTextBox("This text box is rotated with 30 degrees around " + "the top left corner. The red border does not belong to the text box. It has " + "been drawn using DrawRectangle( ) method.", fontText, Nothing, blackBrush, 190, 100, 150, 150, 30)

            ' Draw a label
            pdfPage.Canvas.DrawText("Clipped text", fontText, Nothing, blackBrush, 20, 300)

            ' Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle(redPen, 315, 20, 150, 53)

            ' Draw the text
            pdfPage.Canvas.DrawTextBox("This text is not allowed to get out of the box. " + "This is the default behavior of the text box. The last line will be clipped.", fontText, Nothing, blackBrush, 20, 315, 150, 53)

            ' Draw a label
            pdfPage.Canvas.DrawText("Flow out text", fontText, Nothing, blackBrush, 300, 300)

            ' Draw the bounding boxes
            pdfPage.Canvas.DrawRectangle(redPen, 315, 300, 150, 53)

            ' Draw the text
            pdfPage.Canvas.DrawTextBox("This text is allowed to get out of the box. " + "This behavior can be enforced by setting the clipText parameter to true." + "As it can be seen, the text can flow out of the box. " + "Also, for this sample, the line spacing has been increased with 5 points.", fontText, Nothing, blackBrush, 300, 315, 150, 53, 0, TextAlign.TopLeft, False, 5)
        End Sub 'DrawSecondPage
    End Class 'TextBoxes
End Namespace 'O2S.Samples.PDF4NET.TextBoxes


Samples: TextLines

Samples

TextLines

This samples shows the single line text drawing capabilities of the PDF4NET library. On the first page, it shows all the supported fonts. On the second page, it shows how to draw rotated text at random positions and of random size. On the third page it shows all the possible alignments for text lines.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


TextLines.cs

/// <fileName>
/// File name: TextLines.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.TextLines
{
    struct PrintFont
    {
        public PrintFont( FontFace fontFace, bool bold, bool italic )
        {
            FontFace = fontFace;
            Bold = bold;
            Italic = italic;
        }

        public override string ToString( )
        {
            string s = FontFace.ToString( );
            if( Bold )
            {
                s = s + "Bold";
            }
            if( Italic )
            {
                s = s + "Italic";
            }
            return s;
        }

        public FontFace FontFace;
        public bool Bold;
        public bool Italic;
    }

    /// <summary>
    /// This sample will show various possibilities to draw text on page
    /// </summary>
    class TextLines
    {
        static PrintFont[] fonts =
            { new PrintFont( FontFace.Helvetica, false, false ),
                new PrintFont( FontFace.Helvetica, true, false ),
                new PrintFont( FontFace.Helvetica, false, true ),
                new PrintFont( FontFace.Helvetica, true, true ),
                new PrintFont( FontFace.Courier, false, false ),
                new PrintFont( FontFace.Courier, true, false ),
                new PrintFont( FontFace.Courier, false, true ),
                new PrintFont( FontFace.Courier, true, true ),
                new PrintFont( FontFace.TimesRoman, false, false ),
                new PrintFont( FontFace.TimesRoman, true, false ),
                new PrintFont( FontFace.TimesRoman, false, true ),
                new PrintFont( FontFace.TimesRoman, true, true ) };
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( );

            DrawFirstPage( pdfDoc );
            DrawSecondPage( pdfDoc );
            DrawThirdPage( pdfDoc );

            // Save the document to disk
            pdfDoc.SaveToFile( "textlines.pdf" );
        }

        private static void DrawFirstPage( PDFDocument pdfDoc )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFFont fontText = new PDFFont( FontFace.Helvetica, 12 );
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            for( int i = 0; i < fonts.Length; i++ )
            {
                PDFFont font = new PDFFont( fonts[i].FontFace, 12 );
                font.Bold = fonts[i].Bold;
                font.Italic = fonts[i].Italic;

                pdfPage.Canvas.DrawText( "This font is " + fonts[i].ToString( ) + " size 12",
                    font, null, blackBrush, 20, ( i + 1 ) * 20, 0, TextAlign.TopLeft );
            }

            for( int i = 0; i < fonts.Length; i++ )
            {
                PDFFont font = new PDFFont( fonts[i].FontFace, 16 );
                font.Bold = fonts[i].Bold;
                font.Italic = fonts[i].Italic;

                pdfPage.Canvas.DrawText( "This font is " + fonts[i].ToString( ) + " size 16",
                    font, null, blackBrush, 20, 300 + ( i + 1 ) * 20, 0, TextAlign.TopLeft );
            }
        }

        private static void DrawSecondPage( PDFDocument pdfDoc )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            Random rnd = new Random( );
            for( int i = 0; i < 50; i++ )
            {
                // Random position
                int x = rnd.Next( ( int )pdfPage.Width );
                int y = rnd.Next( ( int )pdfPage.Height );

                // Random text size
                int fontSize = rnd.Next( 16 );

                // Random orientation
                int orientation = rnd.Next( 360 );

                // Random font face
                int fontFaceIndex = rnd.Next( fonts.Length );

                // Create random colors for drawing the text
                PDFColor brushColor = new PDFColor( ( byte )rnd.Next( 256 ),
                    ( byte )rnd.Next( 256 ), ( byte )rnd.Next( 256 ) );

                // Create the brush to draw the text
                PDFBrush brush = new PDFBrush( brushColor );

                PDFFont font = new PDFFont( fonts[fontFaceIndex].FontFace, fontSize );
                font.Italic = fonts[fontFaceIndex].Italic;
                font.Bold = fonts[fontFaceIndex].Bold;

                pdfPage.Canvas.DrawText( "Font: " + fonts[fontFaceIndex].ToString( ) +
                    ", size: " + fontSize.ToString( ) + ", orientation: " + orientation.ToString( ) + " degrees.",
                    font, null, brush, x, y, orientation, TextAlign.TopLeft );
            }
        }

        private static void DrawThirdPage( PDFDocument pdfDoc )
        {
            // Create first page
            PDFPage pdfPage = pdfDoc.AddPage( );

            // Create the graphic objects
            PDFBrush orangeBrush = new PDFBrush( new PDFColor( Color.Orange ) );
            PDFPen pen = new PDFPen( new PDFColor( ), 1 );
            PDFFont font2 = new PDFFont( FontFace.Helvetica, 18 );

            // Draw the drid
            pdfPage.Canvas.DrawLine( pen, 10, 100, 600, 100 );
            pdfPage.Canvas.DrawLine( pen, 10, 300, 600, 300 );
            pdfPage.Canvas.DrawLine( pen, 10, 500, 600, 500 );
            pdfPage.Canvas.DrawLine( pen, 10, 100, 10, 500 );
            pdfPage.Canvas.DrawLine( pen, 300, 100, 300, 500 );
            pdfPage.Canvas.DrawLine( pen, 600, 100, 600, 500 );

            // Draw the labels
            // Top Align
            pdfPage.Canvas.DrawText( "Top left align",
                font2, null, orangeBrush, 10, 100, 0, TextAlign.TopLeft );
            pdfPage.Canvas.DrawText( "Top center align",
                font2, null, orangeBrush, 300, 100, 0, TextAlign.TopCenter );
            pdfPage.Canvas.DrawText( "Top right align",
                font2, null, orangeBrush, 600, 100, 0, TextAlign.TopRight );
            // Middle align
            pdfPage.Canvas.DrawText( "Middle left align",
                font2, null, orangeBrush, 10, 300, 0, TextAlign.MiddleLeft );
            pdfPage.Canvas.DrawText( "Middle center align",
                font2, null, orangeBrush, 300, 300, 0, TextAlign.MiddleCenter );
            pdfPage.Canvas.DrawText( "Middle right align",
                font2, null, orangeBrush, 600, 300, 0, TextAlign.MiddleRight );
            // Right align
            pdfPage.Canvas.DrawText( "Bottom left align",
                font2, null, orangeBrush, 10, 500, 0, TextAlign.BottomLeft );
            pdfPage.Canvas.DrawText( "Bottom center align",
                font2, null, orangeBrush, 300, 500, 0, TextAlign.BottomCenter );
            pdfPage.Canvas.DrawText( "Bottom right align",
                font2, null, orangeBrush, 600, 500, 0, TextAlign.BottomRight );
        }
    }
}


TextLines.vb

'
' File name: TextLines.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

Namespace O2S.Samples.PDF4NET.TextLines
    Structure PrintFont

        Public Sub New(ByVal fontFace As FontFace, ByVal bold As Boolean, ByVal italic As Boolean)
            FontFace = fontFace
            Bold = bold
            Italic = italic
        End Sub 'New

        Public Overrides Function ToString() As String
            Dim s As String = FontFace.ToString()
            If Bold Then
                s = s + "Bold"
            End If
            If Italic Then
                s = s + "Italic"
            End If
            Return s
        End Function 'ToString

        Public FontFace As FontFace
        Public Bold As Boolean
        Public Italic As Boolean
    End Structure 'PrintFont

    '/ <summary>
    '/ This sample will show various possibilities to draw text on page
    '/ </summary>
    Class TextLines
        Private Shared fonts As PrintFont() = {New PrintFont(FontFace.Helvetica, False, False), New PrintFont(FontFace.Helvetica, True, False), New PrintFont(FontFace.Helvetica, False, True), New PrintFont(FontFace.Helvetica, True, True), New PrintFont(FontFace.Courier, False, False), New PrintFont(FontFace.Courier, True, False), New PrintFont(FontFace.Courier, False, True), New PrintFont(FontFace.Courier, True, True), New PrintFont(FontFace.TimesRoman, False, False), New PrintFont(FontFace.TimesRoman, True, False), New PrintFont(FontFace.TimesRoman, False, True), New PrintFont(FontFace.TimesRoman, True, True)}

        Shared Sub Main()
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument()

            DrawFirstPage(pdfDoc)
            DrawSecondPage(pdfDoc)
            DrawThirdPage(pdfDoc)

            ' Save the document to disk
            pdfDoc.SaveToFile("textlines.pdf")
        End Sub 'Main

        Private Shared Sub DrawFirstPage(ByVal pdfDoc As PDFDocument)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim fontText As New PDFFont(FontFace.Helvetica, 12)
            Dim blackBrush As New PDFBrush(New PDFColor())

            Dim i As Integer
            For i = 0 To fonts.Length - 1
                Dim font As New PDFFont(fonts(i).FontFace, 12)
                font.Bold = fonts(i).Bold
                font.Italic = fonts(i).Italic

                pdfPage.Canvas.DrawText("This font is " + fonts(i).ToString() + " size 12", font, Nothing, blackBrush, 20, (i + 1) * 20)
            Next i

            'Dim i As Integer
            For i = 0 To fonts.Length - 1
                Dim font As New PDFFont(fonts(i).FontFace, 16)
                font.Bold = fonts(i).Bold
                font.Italic = fonts(i).Italic

                pdfPage.Canvas.DrawText("This font is " + fonts(i).ToString() + " size 16", font, Nothing, blackBrush, 20, 300 + (i + 1) * 20)
            Next i
        End Sub 'DrawFirstPage

        Private Shared Sub DrawSecondPage(ByVal pdfDoc As PDFDocument)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim blackBrush As New PDFBrush(New PDFColor())

            Dim rnd As New Random()
            Dim i As Integer
            For i = 0 To 49
                ' Random position
                Dim x As Integer = rnd.Next(CInt(pdfPage.Width))
                Dim y As Integer = rnd.Next(CInt(pdfPage.Height))

                ' Random text size
                Dim fontSize As Integer = rnd.Next(16)

                ' Random orientation
                Dim orientation As Integer = rnd.Next(360)

                ' Random font face
                Dim fontFaceIndex As Integer = rnd.Next(fonts.Length)

                ' Create random colors for drawing the text
                Dim brushColor As New PDFColor(CByte(rnd.Next(256)), CByte(rnd.Next(256)), CByte(rnd.Next(256)))

                ' Create the brush to draw the text
                Dim brush As New PDFBrush(brushColor)

                Dim font As New PDFFont(fonts(fontFaceIndex).FontFace, fontSize)
                font.Italic = fonts(fontFaceIndex).Italic
                font.Bold = fonts(fontFaceIndex).Bold

                pdfPage.Canvas.DrawText("Font: " + fonts(fontFaceIndex).ToString() + ", size: " + fontSize.ToString() + ", orientation: " + orientation.ToString() + " degrees.", font, Nothing, brush, x, y, orientation)
            Next i
        End Sub 'DrawSecondPage

        Private Shared Sub DrawThirdPage(ByVal pdfDoc As PDFDocument)
            ' Create first page
            Dim pdfPage As PDFPage = pdfDoc.AddPage()

            ' Create the graphic objects
            Dim orangeBrush As New PDFBrush(New PDFColor(Color.Orange))
            Dim pen As New PDFPen(New PDFColor(), 1)
            Dim font As New PDFFont(FontFace.Helvetica, 18)

            ' Draw the drid
            pdfPage.Canvas.DrawLine(pen, 10, 100, 600, 100)
            pdfPage.Canvas.DrawLine(pen, 10, 300, 600, 300)
            pdfPage.Canvas.DrawLine(pen, 10, 500, 600, 500)
            pdfPage.Canvas.DrawLine(pen, 10, 100, 10, 500)
            pdfPage.Canvas.DrawLine(pen, 300, 100, 300, 500)
            pdfPage.Canvas.DrawLine(pen, 600, 100, 600, 500)

            ' Draw the labels
            ' Top Align
            pdfPage.Canvas.DrawText("Top left align", font, Nothing, orangeBrush, 10, 100, 0, TextAlign.TopLeft)
            pdfPage.Canvas.DrawText("Top center align", font, Nothing, orangeBrush, 300, 100, 0, TextAlign.TopCenter)
            pdfPage.Canvas.DrawText("Top right align", font, Nothing, orangeBrush, 600, 100, 0, TextAlign.TopRight)
            ' Middle align
            pdfPage.Canvas.DrawText("Middle left align", font, Nothing, orangeBrush, 10, 300, 0, TextAlign.MiddleLeft)
            pdfPage.Canvas.DrawText("Middle center align", font, Nothing, orangeBrush, 300, 300, 0, TextAlign.MiddleCenter)
            pdfPage.Canvas.DrawText("Middle right align", font, Nothing, orangeBrush, 600, 300, 0, TextAlign.MiddleRight)
            ' Right align
            pdfPage.Canvas.DrawText("Bottom left align", font, Nothing, orangeBrush, 10, 500, 0, TextAlign.BottomLeft)
            pdfPage.Canvas.DrawText("Bottom center align", font, Nothing, orangeBrush, 300, 500, 0, TextAlign.BottomCenter)
            pdfPage.Canvas.DrawText("Bottom right align", font, Nothing, orangeBrush, 600, 500, 0, TextAlign.BottomRight)
        End Sub 'DrawThirdPage
    End Class 'TextLines
End Namespace 'O2S.Samples.PDF4NET.TextLines


Samples: Tiff2PDF

Samples

Tiff2PDF

This sample demonstrates how to convert a multipage tiff file to PDF.

C# Source code | VB.NET Source code

© 2003 - 2007 O2 Solutions. All rights reserved.


Tiff2PDF.cs

/// <fileName>
/// File name: Tiff2PDF.cs
/// </fileName>

using System;
using System.Drawing;
using System.Drawing.Imaging;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Tiff2PDF
{
    /// <summary>
    /// This sample shows how to convert a multi page tiff file to pdf
    /// </summary>
    class Tiff2PDF
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument doc = new PDFDocument( );

            // Load TIFF file
            Bitmap bitmap = new Bitmap( "sample.tif" );

            // Calculate number of pages/images used in TIFF file
            FrameDimension frameDimension = new FrameDimension( bitmap.FrameDimensionsList[0] );
            int framesCount = bitmap.GetFrameCount( frameDimension );

            for( int i = 0; i < framesCount; i++ )
            {
                // Create a new page
                PDFPage page = doc.AddPage( );

                // draw the current tiff frame on the page
                page.Canvas.DrawImage( "sample.tif", 0, 0, page.Width, page.Height, 0,
                    KeepAspectRatio.KeepNone, 1, i );
            }

            doc.SaveToFile( "tiff2pdf.pdf" );
        }
    }
}


Tiff2PDF.vb

'
' File name: Tiff2PDF.vb
'

Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to convert a multi page tiff file to pdf
'/ </summary>

Class Tiff2PDF

    '/ <summary>
    '/ The main entry point for the application.
    '/ </summary>
    Shared Sub Main(ByVal args() As String)
        ' Create the pdf document
        Dim doc As New PDFDocument()

        ' Load TIFF file
        Dim bitmap As New Bitmap("sample.tif")

        ' Calculate number of pages/images used in TIFF file
        Dim frameDimension As New FrameDimension(bitmap.FrameDimensionsList(0))
        Dim framesCount As Integer = bitmap.GetFrameCount(frameDimension)

        Dim i As Integer
        For i = 0 To framesCount - 1
            ' Create a new page
            Dim page As PDFPage = doc.AddPage()

            ' draw the current tiff frame on the page
            page.Canvas.DrawImage("sample.tif", 0, 0, page.Width, page.Height, 0, KeepAspectRatio.KeepNone, 1, i)
        Next i

        doc.SaveToFile("tiff2pdf.pdf")

    End Sub 'Main
End Class 'Tiff2PDF


Samples: Unicode

Samples

Unicode

This samples shows the Unicode capabilities of PDF4NET library. The same text is printed on several pages but translated in various languages. Some of the translations were done automatically, we apologize for any mistakes.

C# Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Unicode.cs

/// <fileName>
/// File name: Unicode.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Graphics.Fonts;

namespace O2S.Samples.PDF4NET.Unicode
{
    public class PageData
    {
        public PageData( PDFFont font, string language, string text )
        {
            Font = font;
            Language = language;
            Text = text;
        }

        public PDFFont Font;
        public string Language;
        public string Text;
    }

    /// <summary>
    /// This sample will show the Unicode display capabilities of PDF4NET library.
    /// </summary>
    class Unicode
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the fonts to write the text
            TrueTypeFont ttf = new TrueTypeFont( "tahoma.ttf", 12, true, true );
            TrueTypeFont titleFont = new TrueTypeFont( ttf, 16 );
            CJKFont csFont = new CJKFont( CJKFontFace.SinoTypeSongLight, 12 );
            CJKFont ctFont = new CJKFont( CJKFontFace.MonotypeHeiMedium, 12 );
            CJKFont krFont = new CJKFont( CJKFontFace.HanyangSystemsGothicMedium, 12 );
            CJKFont jpFont = new CJKFont( CJKFontFace.HeiseiKakuGothicW5, 12 );

            PageData[] pagesInfo =
            {
                new PageData( ttf, "English", "PDF4NET is a .NET library for generating pdf documents " +
                    "on the fly from any .NET application. The library does not rely on any Adobe " +
                    "products for creating pdf files. It hides the complex structure of pdf files " +
                    "behind a simple object model that allows creation of complex pdf files with a few " +
                    "lines of code. The PDF4NET library follows the GDI+ model, thus reducing the " +
                    "learning time and increasing productivity.\n" +
                    "It uses a grid based layout approach allowing precise positioning of content on " +
                    "document's pages. The final pdf file is compressed, making the library apropriate " +
                    "for web applications. The library can be used both from WinForms and WebForms " +
                    "(ASP.NET) applications without any restrictions. The library is written entirely " +
                    "in C#, being 100% managed. The PDF4NET library is licensed per developer and can " +
                    "be distributed ROYALTY FREE, reducing project costs.\n" ),
                new PageData( csFont, "Chinese Simplified", "PDF4NET 是一个NET 图书馆为正在进行中生成" +
                    "pdf 文件从任一个NET 申请。 图书馆不依靠任何Adobe 产品为创建pdf 文件。 它隐藏pdf " +
                    "文件复杂结构在允许复杂pdf 文件创建以几个代码行的一个简单对象模型之后。 PDF4NET " +
                    "图书馆跟随GDI+ 设计, 如此减少学习时间和增加生产力。它使用网格基于的格式途径允许精" +
                    "确安置目录在文件的页。 最终pdf 文件是压缩的, 使图书馆适当为万维网申请。 图书馆可能" +
                    "被使用从WinForms 和WebForms (ASP.NET) 申请没有任何限制。 图书馆整个地被写在C#, " +
                    "是100% 管理。 PDF4NET 图书馆被准许每开发员, 可能任意是被分配的皇族, 减少项目费用。" ),
                new PageData( ctFont, "Chinese Traditional", "PDF4NET 是一個NET 圖書館為正在進行中生成" +
                    "pdf 文件從任一個NET 申請。 圖書館不依靠任何Adobe 產品為創建pdf 文件。 它隱藏pdf 文" +
                    "件複雜結構在承認複雜pdf 文件創建以幾個代碼行的一個簡單對象模型之後。 PDF4NET 圖書館" +
                    "跟隨GDI+ 設計, 如此減少學習時間和增加生產力。它使用網格基於的格式途徑允許精確安置目" +
                    "錄在文件的頁。 最終pdf 文件是壓縮的, 使圖書館適當為萬維網申請。 圖書館可能被使用從" +
                    "WinForms 和WebForms (ASP.NET) 申請沒有任何限制。 圖書館整個地被寫在C#, 是100% " +
                    "管理。 PDF4NET 圖書館被准許每開發員, 可能任意是被分配的皇族, 減少項目費用。" ),
                new PageData( ttf, "Dutch", "PDF4NET is a. NETTO bibliotheek voor het produceren van " +
                    "pdf documenten op de vlieg van om het even welke. NETTO toepassing. De bibliotheek " +
                    "zich baseert niet op enige producten van de Adobe voor het creëren van pdf dossiers. " +
                    "Het verbergt de complexe structuur van pdfdossiers achter een eenvoudig objecten " +
                    "model dat verwezenlijking van complexe pdfdossiers met een paar lijnen van code " +
                    "toestaat. De bibliotheek PDF4NET volgt GDI + model, waarbij de het leren tijd wordt " +
                    "verminderd en het verhogen van productiviteit. Het gebruikt een net gebaseerde " +
                    "lay-outbenadering die het nauwkeurige plaatsen van inhoud op de pagina's van het " +
                    "document toestaat. Het definitieve pdfdossier wordt samengeperst, makend de " +
                    "bibliotheek voor Webtoepassingen aangewezen. De bibliotheek kan zowel van " +
                    "(NETTO ASP.) toepassingen WinForms als WebForms zonder enige beperkingen worden " +
                    "gebruikt. De bibliotheek wordt geschreven volledig in C#, zijnd geleide 100%. " +
                    "De bibliotheek PDF4NET is vergunning gegeven per ontwikkelaar en kan verdeelde " +
                    "VRIJ ROYALTY zijn die, projectkosten drukt.\n" ),
                new PageData( ttf, "French", "PDF4NET est une bibliothèque de NET pour produire des " +
                    "documents de pdf en marche de n'importe quelle application de NET. La bibliothèque " +
                    "ne se fonde sur aucun produit d'adobe pour créer des fichiers de pdf. Elle cache " +
                    "la structure complexe des fichiers de pdf derrière un modèle simple d'objet qui " +
                    "permet la création des fichiers complexes de pdf avec quelques lignes de code. " +
                    "La bibliothèque de PDF4NET suit le modèle de GDI+, de ce fait réduisant le temps " +
                    "d'étude et augmentant la productivité. Elle utilise une approche de disposition " +
                    "basée par grille permettant le positionnement précis du contenu sur les pages du " +
                    "document. Le fichier final de pdf est comprimé, rendant la bibliothèque appropriée " +
                    "pour des applications de Web. La bibliothèque peut être utilisée des applications " +
                    "de WinForms et de WebForms (ASP.NET) sans aucune restriction. La bibliothèque est " +
                    "écrite entièrement dans C#, étant 100% contrôlé. La bibliothèque de PDF4NET est " +
                    "autorisée par réalisateur et peut être REDEVANCE distribuée LIBREMENT, réduisant " +
                    "des coûts de projet.\n" ),
                new PageData( ttf, "German", "PDF4NET ist eine NET Bibliothek für pdf Dokumente schnell " +
                    "festlegen von jeder möglicher NET Anwendung. Die Bibliothek beruht nicht auf " +
                    "irgendwelchen Ziegelsteinprodukten für das Herstellen der pdf Dateien. Sie versteckt " +
                    "die komplizierte Struktur der pdf Dateien hinter einem einfachen Nachricht Modell, " +
                    "das Kreation der komplizierten pdf Dateien mit einigen Zeilen des Codes erlaubt. " +
                    "Die PDF4NET Bibliothek folgt dem GDI+ Modell, so verringert die erlernenzeit und " +
                    "erhöht Produktivität. Sie verwendet eine Rasterfeld gegründete Planannäherung, " +
                    "die exakte Positionierung des Inhalts auf Seiten des Dokumentes erlaubend. Die " +
                    "abschließende pdf Datei wird komprimiert und bildet die Bibliothek passend für " +
                    "Web-Anwendungen. Die Bibliothek kann WinForms und WebForms (ASP.NET) von den " +
                    "Anwendungen ohne irgendwelche Beschränkungen benutzt werden. Die Bibliothek wird " +
                    "völlig in C# geschrieben und ist gehandhabtes 100%. Die PDF4NET Bibliothek wird pro " +
                    "Entwickler genehmigt und kann verteilte ABGABE FREI sein und verringert Projektkosten.\n" ),
                new PageData( ttf, "Greek", "PDF4NET είναι βιβλιοθήκη δικτύου α. για την παραγωγή pdf των " +
                    "εγγράφων σχετικά με τη μύγα από οποιαδήποτε. εφαρμογή δικτύου. Η βιβλιοθήκη δεν " +
                    "στηρίζεται σε οποιαδήποτε προϊόντα πλίθας για τη δημιουργία pdf των αρχείων. Κρύβει " +
                    "τη σύνθετη δομή των αρχείων pdf πίσω από ένα απλό μοντέλο αντικειμένου που επιτρέπει " +
                    "τη δημιουργία των σύνθετων αρχείων pdf με μερικές γραμμές κώδικα. Η βιβλιοθήκη " +
                    "PDF4NET ακολουθεί GDI + το μοντέλο, μειώνοντας κατά συνέπεια το χρόνο εκμάθησης και " +
                    "αύξηση της παραγωγικότητας. Χρησιμοποιεί μια βασισμένη στο πλέγμα προσέγγιση " +
                    "σχεδιαγράμματος που επιτρέπει τον ακριβή προσδιορισμό θέσης του περιεχομένου στις " +
                    "σελίδες του εγγράφου. Το τελικό αρχείο pdf συμπιέζεται, καθιστώντας τη βιβλιοθήκη " +
                    "αρμόδια για τις εφαρμογές Ιστού. Η βιβλιοθήκη μπορεί να χρησιμοποιηθεί και από " +
                    "(ASP. δίκτυο) τις εφαρμογές WinForms και WebForms χωρίς οποιουσδήποτε περιορισμούς. " +
                    "Η βιβλιοθήκη γράφεται εξ ολοκλήρου C#, όντας 100% διοικούμενο. Η βιβλιοθήκη " +
                    "PDF4NET είναι χορηγημένη άδεια ανά υπεύθυνο για την ανάπτυξη και μπορεί να είναι " +
                    "διανεμημένο ΔΙΚΑΊΩΜΑ ΕΛΕΎΘΕΡΟ, που μειώνει τις δαπάνες προγράμματος.\n" ),
                new PageData( ttf, "Italian", "PDF4NET proviene una libreria del NET per la generazione " +
                    "dei documenti del pdf in moto da tutta l'applicazione del NET. La libreria non " +
                    "conta su alcuni prodotti dell'adobe per la creazione degli archivi del pdf. " +
                    "Nasconde la struttura complessa degli archivi del pdf dietro un modello semplice " +
                    "dell'oggetto che permette la creazione degli archivi complessi del pdf con alcune " +
                    "righe del codice. La libreria di PDF4NET segue il modello di GDI+, così riducendo " +
                    "il tempo imparante ed aumentando il rendimento. Usa un metodo della disposizione " +
                    "basato griglia permettendo posizionare preciso del soddisfare alle pagine del " +
                    "documento. L'archivio finale del pdf è compresso, rendente la libreria adatta per " +
                    "le applicazioni di Web. La libreria può essere usata sia dalle applicazioni di " +
                    "WebForms che di WinForms (ASP.NET) senza alcune limitazioni. La libreria è " +
                    "scritta interamente in C#, essendo 100% gestito. La libreria di PDF4NET è " +
                    "autorizzata per sviluppatore e può essere la SOVRANITÀ distribuita LIBERAMENTE, " +
                    "riducendo i costi di progetto.\n" ),
                new PageData( jpFont, "Japanese", "PDF4NET はあらゆるNET のアプリケーションからPDF " +
                    "文書をオンザフライ式で生成する為のNET ライブラリである。 ライブラリはPDF ファイ" +
                    "ルを作成する為のAdobe あらゆるプロダクトに頼らない。 それは少数のコード行が付い" +
                    "ている複雑なPDF ファイルの作成を可能にする簡単なオブジェクトモデルの後ろのPDF フ" +
                    "ァイルの複雑な構造を隠す。 従ってPDF4NET ライブラリはGDI+ モデルに続き、学習時間" +
                    "を減らし、生産性を高める。それは格子によって基づかせているレイアウトのアプローチ" +
                    "を使用し文書のページの内容の精密な位置を許可する。 最終的なPDF ファイルは圧縮され" +
                    "て、ライブラリを網アプリケーションのために適切にさせる。 ライブラリは制限のない" +
                    "WinForms 及びWebForms (ASP.NET) アプリケーションから両方使用することができる。 " +
                    "ライブラリはでC# 完全に書かれ、管理される100% である。 PDF4NET ライブラリは1 開" +
                    "発者につき認可され、分散特許権使用料自由にである場合もありプロジェクトのコストを" +
                    "削減する。" ),
                new PageData( krFont, "Korean", "PDF4NET은 어떤NET응용에서pdf문서를 몰래 생성하기를 " +
                    "위해NET도서관 이다. 도서관은pdf파일을 만들기를 위해Adobe어떤 제품에 의지하지 않는" +
                    "다. 그것은 약간 코드 행에 복잡한pdf파일의 창조를 허용하는 간단한 객체 모형뒤에pdf" +
                    "파일의 복잡한 구조를 숨긴다. PDF4NET도서관은 GDI+모형을 따라, 따라서 학습 시간을 " +
                    "감소하고 생산력을 증가한. 그것은 격자에 의하여 기초를 두는 배치 접근을 사용해 문" +
                    "서 페이지에 내용의 정확한 두기 허용한. 마지막pdf파일은 압축 이어, 도서관을 웹 응" +
                    "용을 위해 적당한 시킨. 도서관은 어떤 금지없이 WinForms과 WebForms(22#ASP.NET) 응" +
                    "용에서 모두 이용할 수 있는다. 도서관은 전체로안에C#써, 처리되는 100% 이. PDF4NET" +
                    "도서관은 개발자당 허용하 배부된 특허권 사용료 자유롭게 이을 수 있어, 계획사업 비" +
                    "용을 감소한." ),
                new PageData( ttf, "Portuguese", "PDF4NET é uma biblioteca do NET para gerar originais " +
                    "do pdf na mosca de toda a aplicação do NET. A biblioteca não confia em nenhuns " +
                    "produtos do adôbe para criar limas do pdf. Esconde a estrutura complexa de limas " +
                    "do pdf atrás de um modelo simples do objeto que permita a criação de limas " +
                    "complexas do pdf com algumas linhas do código. A biblioteca de PDF4NET segue o " +
                    "modelo de GDI+, assim reduzindo o tempo de aprendizagem e aumentando a produtividade. " +
                    "Usa uma aproximação baseada grade da disposição permitindo posicionar preciso do " +
                    "índice em páginas do original. A lima final do pdf é comprimida, fazendo a " +
                    "biblioteca apropriada para aplicações do Web. A biblioteca pode ser usada das " +
                    "aplicações de WinForms e de WebForms (ASP.NET) sem nenhumas limitações. A " +
                    "biblioteca é escrita inteiramente em C#, sendo 100% controlado. A biblioteca de " +
                    "PDF4NET é licenciada por o colaborador e pode ser ROYALTY distribuído LIVRE, " +
                    "reduzindo custos do projeto.\n" ),
                new PageData( ttf, "Romanian", "PDF4NET este o librărie .NET destinată generării de " +
                    "documente pdf din orice aplicaţie .NET. Librăria nu se bazează pe nici un product " +
                    "Adobe pentru generarea fişierelor pdf. Ea ascunde structura complexă a fişierelor " +
                    "pdf în spatele unui model obiect simplu ce permite crearea de fişiere pdf complexe " +
                    "cu doar câteva linii de cod. Librăria PDF4NET urmează modelul GDI+, reducând astfel " +
                    "timpul de învăţare şi crescând productivitatea.\n" +
                    "Librăria utilizeaza o abordare de poziţionare a conţinutului bazată pe grid, " +
                    "permiţând poziţionarea precisă a continuţului în paginile documentului. Fisierul " +
                    "pdf final este comprimat, făcând librăria potrivită pentru aplicaţiile web. " +
                    "Librăria poate fi utilizată atât din aplicaţii desktop WinForms cât şi din " +
                    "aplicaţii web WebForms (ASP.NET) fără nici o restricţie. Librăria a fost dezvoltată " +
                    "în întregime în C#, fiind 100% managed. Librăria PDF4NET este licenţiată per " +
                    "programator şi poate fi distribuită fără taxe suplimentare, reducând astfel " +
                    "costurile proiectului în care este folosită.\n" ),
                new PageData( ttf, "Russian", "PDF4NET будет архивом NET для производить документы pdf " +
                    "на мухе от любого применения NET. Архив не полагается на всех продуктах самана для " +
                    "создавать архивы pdf. Он прячет сложную структуру архивов pdf за просто моделью " +
                    "предмета позволяет творение сложных архивов pdf с немного линий Кодего. Архив " +
                    "PDF4NET следует за моделью GDI+, таким образом уменьшающ учя время и увеличивающ " +
                    "урожайность. Он использует основанный решеткой подход к плана позволяющ точный " +
                    "располагать содержания на страницы документа. Обжат окончательный архив pdf, делая " +
                    "архив соотвествующим для применений стержня. Архив можно использовать и от " +
                    "применений WinForms и WebForms (ASP.NET) без всех ограничений. Архив написан вс в C#, " +
                    "был управляемым 100%. Архив PDF4NET лицензирован в проявитель и может быть " +
                    "распределенной КОРОЛЕВСКОЙ ВЛАСТЬЮ СВОБОДНО, уменьшающ цены проекта.\n" ),
                new PageData( ttf, "Spanish", "PDF4NET es una biblioteca del NET para generar documentos " +
                    "del pdf en marcha de cualquier aplicación del NET. La biblioteca no confía en " +
                    "ninguna productos del adobe para crear ficheros del pdf. Oculta la estructura " +
                    "compleja de los ficheros del pdf detrás de un modelo simple del objeto que permita " +
                    "la creación de los ficheros complejos del pdf con algunas líneas del código. " +
                    "La biblioteca de PDF4NET sigue el modelo de GDI+, así reduciendo el tiempo que " +
                    "aprende y aumentando productividad. Utiliza un acercamiento basado rejilla de la " +
                    "disposición permitiendo la colocación exacta del contenido en las paginaciones del " +
                    "documento. El fichero final del pdf se comprime, haciendo la biblioteca apropiada " +
                    "para las aplicaciones del Web. La biblioteca se puede utilizar de las aplicaciones " +
                    "de WinForms y de WebForms (ASP.NET) sin ningunas restricciones. La biblioteca se " +
                    "escribe enteramente en C#, siendo el 100% manejado. La biblioteca de PDF4NET se " +
                    "licencia por el revelador y puede ser DERECHOS distribuidos LIBREMENTE, reduciendo " +
                    "costes del proyecto.\n" ),
                new PageData( ttf, "Swedish", "PDF4NET är ett .NET-bibliotek för att generera " +
                    "pdf-dokument i farten i en .NET-applikation. Biblioteket är inte beroende av någon " +
                    "produkt från Adobe för att skapa pdf-filer. Det döljer pdf-filernas komplexa " +
                    "struktur bakom en enkel objektsmodell, som tillåter skapandet av komplexa " +
                    "pdf-filer med några få rader kod. PDF4NET-biblioteket följer modellen GDI+, och " +
                    "förkortar därigenom inlärningstiden och ökar produktiviteten.\n" +
                    "Det använder en layoutmetod, baserad på rutnät, vilket möjliggör absolut " +
                    "positionering av innehållet i dokumentet. Den slutgiltiga pdf-filen är komprimerad, " +
                    "vilket gör biblioteket lämpligt för webapplikationer. Biblioteket kan användas både " +
                    "från WinForms- och WebForms- (ASP.NET) applikationer utan några begränsningar. " +
                    "Biblioteket är helt och hållet skrivet i C#, och är till 100% s.k. \"Managed Code\". " +
                    "PDF4NET-biblioteket licensieras per utvecklare och kan distribueras royaltyfritt, " +
                    "vilket minskar projektkostnader.\n" )
            };

            // Create the pdf document
            PDFDocument doc = new PDFDocument( );
            doc.ViewerPreferences.DisplayMode = DisplayMode.DisplayOutlines;

            // Create the graphic objects
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );

            // Create the root bookmark
            PDFOutline root = new PDFOutline( );
            root.Display = OutlineDisplay.Bold;
            root.TopDestination = 0;
            root.Title = "Unicode";
            doc.Outlines.Add( root );

            PDFTextFormatOptions tfo = new PDFTextFormatOptions( );
            tfo.Align = TextAlign.TopJustified;

            for( int i = 0; i < pagesInfo.Length; i++ )
            {
                PDFPage page = doc.AddPage( );

                // draw the page title
                page.Canvas.DrawText( pagesInfo[i].Language, titleFont, null, blackBrush, 20, 40 );

                // draw the page content
                page.Canvas.DrawTextBox( pagesInfo[i].Text, pagesInfo[i].Font, null, blackBrush,
                    20, 60, page.Width - 40, page.Height - 80, tfo );

                // add a bookmark to point to this page
                root.Outlines.Add( pagesInfo[i].Language, new PDFColor( ), true, OutlineDisplay.Regular, page, 0 );
            }
            root.DestinationPage = doc.Pages[0];

            // Save the document to disk
            doc.SaveToFile( "unicode.pdf" );
        }
    }
}


Samples: Update PDF

Samples

Update PDF

This samples shows the import and update capabilities of PDF4NET library. It loads an external pdf file, draws content on the first page of the document, then it creates a new page at the beginning of the document.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


UpdatePDF.cs

/// <fileName>
/// File name: UpdatePDF.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;
using O2S.Components.PDF4NET.Graphics.Fonts;

namespace O2S.Samples.PDF4NET.UpdatePDF
{
    /// <summary>
    /// This sample shows how to add content to an existing
    /// pdf file.
    /// </summary>
    class UpdatePDF
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Create the pdf document
            PDFDocument pdfDoc = new PDFDocument( "helloworld.pdf" );
            // Create the graphic objects
            PDFBrush blackBrush = new PDFBrush( new PDFColor( ) );
            PDFBrush greenBrush = new PDFBrush( new PDFColor( 0, 128, 0 ) );
            PDFPen redPen = new PDFPen( new PDFColor( 255, 0, 0 ), 2 );
            PDFFont fnt = new PDFFont( FontFace.Helvetica, 12 );

            // Draw on the first page of the imported document
            pdfDoc.Pages[0].Canvas.DrawRectangle2( redPen, greenBrush, 15, 15, 500, 200, 0 );
            pdfDoc.Pages[0].Canvas.DrawText( "This is new content added to an imported page.",
                fnt, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Create a page and insert it at the beginning
            // of the document
            PDFPage firstPage = pdfDoc.InsertPage( 0 );
            firstPage.Canvas.DrawText( "This is a new page added to the old document",
                fnt, null, blackBrush, 20, 20, 0, TextAlign.TopLeft );

            // Save the document to disk
            pdfDoc.SaveToFile( "updatepdf.pdf" );
        }
    }
}


UpdatePDF.vb

'
' File name: UpdatePDF.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes
Imports O2S.Components.PDF4NET.Graphics.Fonts

Namespace O2S.Samples.PDF4NET.UpdatePDF
   '/ <summary>
   '/ This sample shows how to add content to an existing
   '/ pdf file.
   '/ </summary>

   Class UpdatePDF
        <STAThread()> _
        Shared Sub Main(ByVal args() As String)
            ' Create the pdf document
            Dim pdfDoc As New PDFDocument("helloworld.pdf")
            ' Create the graphic objects
            Dim blackBrush As New PDFBrush(New PDFColor)
            Dim greenBrush As New PDFBrush(New PDFColor(0, 128, 0))
            Dim redPen As New PDFPen(New PDFColor(255, 0, 0), 2)
            Dim ttf As New TrueTypeFont("verdana.ttf", 12, True)

            ' Draw on the first page of the imported document
            pdfDoc.Pages(0).Canvas.DrawRectangle2(redPen, greenBrush, 15, 15, 500, 200)
            pdfDoc.Pages(0).Canvas.DrawText("This is new content added to an imported page.", ttf, Nothing, blackBrush, 20, 20)

            ' Create a page and insert it at the beginning
            ' of the document
            Dim firstPage As PDFPage = pdfDoc.InsertPage(0)
            firstPage.Canvas.DrawText("This is a new page added to the old document", ttf, Nothing, blackBrush, 20, 20)

            ' Save the document to disk
            pdfDoc.SaveToFile("updatepdf.pdf")
        End Sub 'Main
    End Class 'UpdatePDF
End Namespace 'O2S.Samples.PDF4NET.UpdatePDF


Samples: Watermarks

Samples

Watermarks

This sample demonstrates how to a watermark to a PDF file. The sample draws a simple text watermark on each page of a PDF document. Any type of text, graphics and image can be used as watermarks.

C# Source code | VB.NET Source code | PDF file

© 2003 - 2007 O2 Solutions. All rights reserved.


Watermarks.cs

/// <fileName>
/// File name: Watermarks.cs
/// </fileName>

using System;
using System.Drawing;
using O2S.Components.PDF4NET;
using O2S.Components.PDF4NET.PDFFile;
using O2S.Components.PDF4NET.Annotations;
using O2S.Components.PDF4NET.Graphics;
using O2S.Components.PDF4NET.Graphics.Shapes;

namespace O2S.Samples.PDF4NET.Watermarks
{
    /// <summary>
    /// This sample shows how to draw a text watermark on existing PDF files behind actual page content.
    /// </summary>
    class Watermarks
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Import the pdf document
            PDFDocument doc = new PDFDocument( "sample.pdf" );

            // stamp second page with regular text.
            PDFFont font = new PDFFont( FontFace.Helvetica, 96 );
            font.Bold = true;
            PDFBrush greenBrush = new PDFBrush( new PDFColor( Color.Green ) );

            for( int i = 0; i < doc.Pages.Count; i++ )
            {
                PDFImportedPage ip = ( PDFImportedPage )doc.Pages[i];

                // Use the UnderCanvas property to draw under existing page content
                ip.UnderCanvas.DrawText( "Approved", font, null, greenBrush,
                    ip.Width/2, ip.Height/2, 20, TextAlign.MiddleCenter );
            }

            // Save the document to disk
            doc.SaveToFile( "watermarks.pdf" );
        }
    }
}


Watermarks.vb

'
' File name: Watermarks.vb
'

Imports System
Imports System.Drawing
Imports O2S.Components.PDF4NET
Imports O2S.Components.PDF4NET.PDFFile
Imports O2S.Components.PDF4NET.Annotations
Imports O2S.Components.PDF4NET.Graphics
Imports O2S.Components.PDF4NET.Graphics.Shapes

'/ <summary>
'/ This sample shows how to draw a text watermark on existing PDF files behind actual page content.
'/ </summary>

Class Watermarks
    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Import the pdf document
        Dim doc As New PDFDocument("sample.pdf")

        ' stamp second page with regular text.
        Dim font As New PDFFont(FontFace.Helvetica, 96)
        font.Bold = True
        Dim greenBrush As New PDFBrush(New PDFColor(Color.Green))

        Dim i As Integer
        For i = 0 To doc.Pages.Count - 1
            Dim ip As PDFImportedPage = CType(doc.Pages(i), PDFImportedPage)

            ' Use the UnderCanvas property to draw under existing page content
            ip.UnderCanvas.DrawText("Approved", font, Nothing, greenBrush, ip.Width / 2, ip.Height / 2, 20, TextAlign.MiddleCenter)
        Next i

        ' Save the document to disk
        doc.SaveToFile("watermarks.pdf")
    End Sub 'Main
End Class 'Watermarks