ElegantJ PDF Library

 

 

Programmers’ Guide

 


 

Document Information

Document ID

EJPDFL-PG-0407-V1.0

Version

1.0

Date

16-Apr-07

Recipient

NA

Author

EMTPL

 

 

Statement of Confidentiality, Disclaimer and Copyright

This document contains information that is proprietary and confidential to EMTPL, which shall not be disclosed, transmitted, or duplicated, used in whole or in part for any purpose other than its intended purpose. Any use or disclosure in whole or in part of this information without express written permission of EMTPL is prohibited.

 

Any other company and product names mentioned are used for identification purpose only, and may be trademarks of their respective owners and duly acknowledged.


 

Table of Content

 

1    Preface  5

1.1          Purpose of this document  5

1.2          Assumptions  5

1.3          Document Organization   5

1.4          Conventions Used   6

2    About ElegantJ PDF Library   7

2.1    What’s new    7

2.2          Toolkit  7

3      Features  8

3.1    Major Functionalities  8

3.2    Text and fonts  8

3.3    Image and Graphics  9

4    Product Demo   11

4.1          Installing Demo   11

4.2    View Demo   11

5      Installation and Registration   13

5.1          Prerequisite  13

5.2          Installation Procedure  13

5.3    Using with Different IDEs  14

5.3.1             Borland JBuilder  14

5.3.2    Sun Java Studio Creator  15

5.3.3             NetBeans  15

5.3.4             Eclipse Editor  16

5.4          Getting and Using the License Key   17

5.4.1    How to Purchase  17

5.4.2             Configuring Directly within Source Code  17

6      Programmer’s Guide  18

6.1          ElegantJ PDF Library   18

6.1.1             Creating an instance of ElegantJ PDF  18

6.1.2             Creating and adding a Page to PDF  18

6.1.3             Creating True Type font  19

6.1.4             Creating Type1 font  20

6.1.5             Creating TrueTypeCJK font  20

6.1.6             Creating CJK font  21

6.1.7             Creating and Adding PDFText to page  22

6.1.8             Adding PDFText to the Page  24

6.1.9             Getting last Y coordinate on the page  24

6.1.10               Creating and adding PDFLine to Page  25

6.1.11               Creating and adding PDFRectangle to Page  26

6.1.12               Creating and adding PDFCircle to Page  27

6.1.13               Creating and adding PDFOval to Page  28

6.1.14               Creating and Adding PDFArc to Page  29

6.1.15               Creating and adding PDFPolygon to Page  31

6.1.16               Creating and adding PDFImage to page  32

6.1.17               Creating and applying PDFPattern  32

6.1.18               Applying PDFPattern to any Graphic Object  33

6.1.19               Creating and adding PDFRubberStampAnnotation to the page  34

6.1.20               Creating and adding PDFTextAnnotation to the page  35

6.1.21               Creating and adding PDFLinkAnnotation to the page  35

6.1.22               Creating and adding PDFTable to the page  36

6.1.23               Creating Outline Tree  39

6.1.24               Example Using Outlines  41

6.1.25               Working with Document Meta Information  43

6.1.26               Writing PDF to output Stream  43

6.1.27     The difference between CJKFont and TrueTypeCJKFont and when to use them  43

6.1.28               Generating PDF dynamically from servlet  44

6.1.29               Making PDFRectangle with rounded joins  45

6.1.30               Generating PDF directly from any java component  46


 

1       Preface

This preface describes the document. The preface contains the following sections:

 

 

Section

Page

Purpose of this document

5

Assumptions

5

Document Organization

5

Conventions Used

6

 

 

1.1  Purpose of this document

The purpose of this document is to provide the fundamental skills necessary to productively install, program, integrate, and use the ElegantJ PDF Library. This document provides both programmer and user perspective to the audience.

 

 

1.2  Assumptions

This manual assumes that readers are having reasonable level of exposure to fundamentals of Java programming and various architectures.

 

 

1.3  Document Organization

This document is organized as described in following tables.

Table 1 – Organization of the document

Chapter

Contents

About ElegantJ PDF Library

Ø       What’s new

Ø       Toolkit

Features

Ø       Major Functionalities

Ø       Text and fonts

Ø       Image and Graphics

Product Demo

Ø       Installing Demo

Ø       View Demo

Installation and Registration

Ø       Prerequisite

Ø       Installation Procedure

Ø       Using with Different IDEs

Ø       Getting and Using the License Key

Programmer’s Guide

Ø       Programmer's guide to frequently asked questions

 

 

 

 

 

 

1.4  Conventions Used

 

 

File

Italic (slanted) type indicates variable values, instruction operands.

[ | ]
{
 | }

In syntax definitions, brackets indicate items that are optional and braces indicate items that are required. Vertical bars separating items inside brackets or braces indicate that you choose one item from among those listed.

. . .

In syntax definitions, a horizontal ellipsis indicates that the preceding item can be repeated one or more times.

Get(1)

A cross-reference to a reference page includes the appropriate section number in parentheses. For example, get(1) indicates that you can find information on the get command in Section 1 of the reference pages.

//

An explanation of a particular function performed by preceding code.

 

 


 

2       About ElegantJ PDF Library

ElegantJ PDF Library offers dynamic documents and Enterprise Reporting in PDF. Let your customers get Invoice and Sales orders in PDF over the web or dynamically generate enterprise reports for your corporate Internet users.

 

ElegantJ PDF Library is a powerful Java class library that enables you to deliver dynamic and live business reports in printer friendly and professional looking PDF documents. ElegantJ PDF Library supports internationalization with multiple languages including Chinese, Japanese and Korean (CJK) as well as bi-directional (BiDi) fonts like Arabic. ElegantJ PDF Library also provides option to support encryption for your PDF document.

 

ElegantJ PDF library does a lot of work for a developer. It generates PDF document directly from any Java component. Using PDFTable, it generates table directly from data source. Use its methods to generate PDF from text as well as graphic objects. It gives facility of bookmarks and annotation to give a touch of class to your documentation. In nutshell, you provide raw data and formatting, and ElegantJ PDF Library will generate PDF saving time and efforts.

 

ElegantJ PDF Library also gives your Java solution ability of web printing. Use in server-side technologies like servlet/JSP, J2EE or J2SE applications and applets to generate dynamic PDF documents.

 

2.1  What’s new

In case you are using evaluation, an Evaluation Dialog used to popup every 10 minutes. This dialog will now appear only once, making evaluation without interruption.

 

Now you can generate PDF directly from any Java component. No special coding is required.

 

2.2  Toolkit

ElegantJ PDF Library has one Java Bean.

 

Ø       ElegantJ PDF Library (ejpdf.jar)

 

 


 

3       Features

ElegantJ PDF Library is a Java class library to generate PDF documents directly from a Java Component. Some of main features of ElegantJ PDF Library are:

 

Ø       Ability of dynamic reporting with PDF documents

Ø       Internationalization with multiple languages including Chinese, Japanese and Korean (CJK) fonts as well as Bi-Directional (BiDi) fonts like Arabic.

Ø       Superb graphic support

Ø       Encryption and compression features

Ø       Report writing made simpler using PDF Table.

 

3.1  Major Functionalities

Ø       Generate PDF directly from any java component. ElegantJ PDF Library provides PDFGraphics object to generate PDF directly from any java component. Using this, user can directly generate PDF from any JAVA lightweight component and JAVA Swing Component.

o        PDF Graphics: This JAVA Library provides PDFGraphics object to generate PDF directly from any java component.  Using this PDFGraphics JAVA Library, user can directly generate PDF from components listed below –

§         From any java swing component

§         From any lightweight component

Ø       Dynamic reporting directly from any data source to PDF

Ø       ElegantJ PDF Library provides 40 bit encryption for PDF documents

Ø       Support for Tables using PDF Table to display data in grid format. Customizable row(s) and column(s).  Table outline color and outline width.  Background, foreground and font at row, column and cell level.  Apply PDFPattern at table, row, column and cell level.  Apply alignment like LEFT, RIGHT, CENTER and JUSTIFY at table, row, column and cell level.  Set the data for table using 2-D vector

o        Support for Tables  

§         Customizable row(s) and column(s)

§         Table outline color and outline width

§         You can customize Row height at row level, and column width at column level in this JAVA Library

§         Background, foreground and font at row, column and cell level

§         Apply PDFPattern at table, row, column and cell level

§         Apply alignment like LEFT, RIGHT, CENTER and JUSTIFY at table, row, column and cell level

§         Set the data for table using 2-D vector in JAVA Library

Ø       Full support for document's meta information

Ø       This PDF JAVA Library provides default compression for the PDF documents

Ø       ElegantJ PDF Library provides full support for UNICODE. 

 

3.2  Text and fonts

Ø       Internationalization: ElegantJ PDF Library supports TrueType, Type1, CJK and Bi-Directional (BiDi) fonts, like Arabic fonts. 14 Type1 base fonts.  Type1 Font including embedding available in this PDF Library.  True Type font including embedding and sub-setting to keep pdf size small.  Supports Chinese, Japanese and Korean (CJK) language font support.  Supports Bi-Directional (BiDi), like Arabic Fonts

o        Unmatched Font support

§         14 Type1 base fonts

§         Type1 Font including embedding available in this JAVA Library

§         True Type font including, embedding and sub-setting to keep pdf size small

§         This JAVA Library supports Chinese, Japanese and Korean language font support

§         ElegantJ PDF Library supports Bi-Di (Bi-directional) fonts like Arabic fonts

Ø       Full support for Text: alignment, character and paragraph styles. Available alignments in this JAVA Library are - left, right, center and justify.  Features like text wrapping, subscript and superscript, indent, underline, strikeout.  ElegantJ PDF library supports word spacing, character spacing, horizontal scaling for text

o        Text Properties

§         Available Alignments in this JAVA Library are - left, right, center and justify

§         Text wrapping, subscript and superscript, indent, underline, strikeout

§         This JAVA Library supports word spacing, character spacing, horizontal scaling for text

Ø       Annotation support: Text annotation, Rubber Stamp annotation and Link Annotation

Ø       Full support for bookmarks is provided by this PDF Library. 

 

3.3  Image and Graphics

Ø       An array of Graphics objects: You can have graphic objects like Circle, Oval, Line, Arc, Rectangle and Polygon in this JAVA Library

o        Graphic Objects: This JAVA PDF Library supports following Graphic Objects

§         Circle

§         Oval (Ellipse)

§         Line

§         Arc

§         Rectangle

§         Polygon

Ø       Support for JPEG images and java image objects

Ø       ElegantJ PDF Library provides patterns that can be applied to text and graphics objects. Predefined patterns available are - Star, Circle, Oval, Check, Horizontal lines, vertical lines and Inclined line pattern.  You can set an PDFImage as pattern.  Also, you can supply Graphic pattern as per PDF Specifications

o        Patterns

§         Predefined patterns available for use in this JAVA Library are - Star, Circle, Oval, Check, Horizontal lines, vertical lines and Inclined line pattern

§         You can set an PDFImage as pattern

§         In this JAVA Library, you can supply Graphic pattern as per PDF Specifications

Ø       ElegantJ PDF Library provides a number of styles to choose from. E.g. Fill color, line color, line gap, etc.

o        Styles; for objects in ElegantJ PDF Library

§         You can set

§         Fill color

§         Line color

§         Font

§         Text alignment

§         Text underline

§         Text char spacing

§         Text word spacing

§         Text horizontal scaling

§         Text indent

§         Line weighting

§         Line dash

§         Line gap

§         Line join style

§         Line cap style.

 


4       Product Demo

 

4.1  Installing Demo

Extracted file(archive) contains demos directory.  All the demos are located in this demos directory. 

Your classpath environment variables must be set correctly in order to run the demos.  For windows users we have provided rundemo.bat file which will run demo directly.  All Demo Applets contain HTML file to run an Applet associated with it.

 

For more information on how to set classpath, refer Installation procedure.

 

4.2  View Demo

Application that generates a PDF document

This demo application demonstrates all PDF objects like PDFText with all attributes, Type1 Font, True Type Font, CJK Font, Graphics objects like (line, rectangle, circle, oval, arc, polygon), PDF Patterns, PDF Annotation, PDF Image and PDF Table objects.

 

To run this demo application

 

Go to ElegantJPDF\demos\applications\pdf_demo directory, then execute java -jar pdf_demo.jar command.

 

Generate PDF from servlet

This is a dynamically generated PDF using servlet, servlet will be called from submit of HTML form.

 

Note: Before running demo, please go through readme.txt, available in ElegantJPDF\demos\servlets\pdf_using_servlet directory.

 

To run this demo,

 

Go to ElegantJPDF\demos\servlets\pdf_using_servlet and follow the steps given below

 

Ø       Deploy PDFDataServlet on any java based web server PDFDataServlet reside in servlet directory

Ø       Open InputForm.html in any ASCII editor and put valid URL of the servlet in action value of form tag

Ø       Open InputForm.html in any web browser and then fill up the form

Ø       After filling form, click submit button of the same form

Ø       After submitting form you will get dynamically generated PDF in the same window.

 

PDFGraphics demo

Shows how to generate PDF directly from any java component, this demo provides the PDF generation from JTextArea, JTextPane, JPanel and JTable

 

Note: Before running demo, please go through readme.txt exists in the ElegantJPDF\demos\applications\pdf_graphics directory

 

To run this demo,

 

Go to ElegantJPDF\demos\applications\pdf_graphics and follow the following steps

 

Ø       If you are windows user execute rundemo.bat or execute java -jar pdf_graphics_demo.jar command

Ø       Configure/Edit JTextArea or JTextPane or JTable or JPanel

Ø       After configuring any component out of the JTextArea, JTextPane, JTable or JPanel, click Generate PDF button

Ø       On clicking Generate PDF button, PDF file named test.pdf will be generated in the same directory

Ø       Open test.pdf in PDF viewer.

 

Note: For windows users we have provided the rundemo.bat file to run respective demo application.

 


 

5       Installation and Registration

 

5.1  Prerequisite

Before installing ElegantJ PDF Library, please ensure that your computer system and development environment are setup and working as per expectations. Person evaluating ElegantJ PDF Library is expected to be able to write and execute simple Java applications.

 

We provide free pre-purchase technical support to help you complete process of evaluation. Mail to support@ElegantJPDF.com for pre-purchase technical support.

 

To be able to use ElegantJ PDF Library, the computer system is required to have -

 

Ø       An IDE that supports Java 2 or higher, or

Ø       JDK 1.2.2 or higher

 

Please note that evaluation version of ElegantJ PDF Library cannot be deployed for commercial, non-commercial or any other purpose in any possible way. You may not build any software, applets or applications for distribution with evaluation version of ElegantJ PDF Library.

 

This evaluation version is to be solely used by you to evaluate suitability of ElegantJ PDF Library for your needs. For more details please go through License Agreement.

 

5.2  Installation Procedure

On extracting EJPDFLib.zip, following directories will be created -

 

Directory [jars] contains Jar file(s)

Directory [demos] contains demo application(s) with source code

Directory [docs] contains User Guide and Java API

 

 

Installing on Windows 95/98

 

To include ElegantJ PDF in CLASSPATH, add following statement to your autoexec.bat file,

 

set CLASSPATH= %CLASSPATH%;C:\ELEGANTJPDF\jars\ejpdf.jar;

 

Restart Windows to make changes effective.

 

 

Installing on Windows NT / 2000

 

Go to Control Panel and select System. You will find environment variables on Environment tab in Windows NT systems and on Advanced tab in Windows 2000 systems.

 

Find CLASSPATH environment variable or create it.

To include ElegantJ PDF in the CLASSPATH, specify or add following value for variable -

 

[EXISTING-CLASSES]; C:\ELEGANTJPDF\jars\ejpdf.jar;

 

 

Installing on UNIX / Linux

 

Before you begin using ElegantJ PDF, you must manually configure CLASSPATH environment variable. CLASSPATH must point to the location of classes and installation directory.

 

For example, to set CLASSPATH for ElegantJ PDF,

 

 

setenv CLASSPATH.:/usr/local/ELEGANTJPDF/jars/ejpdf.jar:

 

If you are using Bourne Shell, commands are,

 

CLASSPATH= $CLASSPATH:.:/usr/local/ELEGANTJPDF/jars/ejpdf.jar:export CLASSPATH

 

 

5.3  Using with Different IDEs

ElegantJ PDF Library file(s) is located in the \jars\subdirectory.

 

This set of documentation contains guidelines for importing ElegantJ PDF to different IDEs.

 

ElegantJ PDF works well with any PDF compliant Integrated Development Environment (IDE).

 

5.3.1Borland JBuilder

Follow the steps given below to create a new category and install the Bean into Borland JBuilder.

 

Create a New Category

Ø       Click menu Tools > Configure Palette. It opens Palette Properties dialog box.

Ø       Click on Add button. It opens Add Page dialog box.

Ø       Specify name (e.g., ElegantJ PDF) and click on OK button.

Ø       New Category will be created.

 

Create New Library and Install/Import Bean

Ø       On Palette Properties dialog box, click on Add components tab.

Ø       Select newly created page (e.g., ElegantJ PDF).

Ø       Click on Select Library button. It opens Select a Different Library dialog box.

Ø       Click on New button. It opens New Library Wizard dialog box.

Ø       Specify name for library and click on Add button. It opens Select One or More Directories dialog box.

Ø       Select directory where jar files are located, or select jar file to be imported. Click on OK button. Dialog box will be closed and New Library Wizard dialog box appears in front.

Ø       Click on OK button on New Library Wizard dialog box. It opens Select a Different Library dialog box.

Ø       Confirm that newly created library is selected. Click on OK button. It opens Add Components under Palette Properties.

Ø       Click on Add from Selected Libraries button. It opens Results dialog box. Click on OK button.

Ø       Results dialog box disappears. Click on OK button on Palette Properties dialog box.

Ø       ElegantJ PDF Library is ready to be used.

 

5.3.2Sun Java Studio Creator

Follow the steps given below to create a new category and install ElegantJ PDF into Sun Java Studio Creator 2.

Ø       Click menu Tools>Library Manager. It opens Library Manager dialog box.

 

Create New Library

Click on New Library button. It opens New Library dialog box. Write a Library Name and select Component Libraries from Library Type combo box. Click OK.

 

Load Component As a Jar File

Click on Add Jar/Folder button. It opens File dialog box. Locate jar file (i.e. /ElegantJPDF/jars/ejpdf.jar), and Click on OK button. The selected jar file appears in Library Classpath List.

 

Ø       Click on OK Button.

 

Create a new Project. (e.g., ElegantJPDF)

Ø       Right click on Created Project (e.g., ElegantJPDF).

Ø       Select property.

Ø       Project Properties dialog box will open.

Ø       Select Libraries from Categories tree on left pane.

Ø       On right pane, click on Add Library.

Ø       It opens Add Library dialog box.

Ø       Select a Library from list, which is created from Library Manager.

Ø       Click on Add Library button.

Ø       Click OK button on Project Properties dialog box.

 

5.3.3NetBeans

Follow the steps given below to create a new category and install ElegantJ PDF into NetBeans IDE.

Ø       Click menu Tools > Palette Manager. It opens Palette Manager dialog box.

 

Create New Category

Ø       Click on New Category button.

Ø       It opens New Palette Category dialog box. Write a New category Name and Click on OK button to add a category name into Palette Manager.

Ø       Click on Add From Jar button. It opens Install Component to Palette dialog box.

Ø       Choose a component from Available Components list.

Ø       Click on Next button.

Ø       Locate/Choose a jar containing components (e.g., /ElegantJPDF/jars/ejpdf.jar).

Ø       Click on Next button.

Ø       Select the Palette Category to add the components.

Ø       Click on Finish button.

Ø       The component is added into the selected Palette Category.

Ø       Click on Close button.

 

5.3.4Eclipse Editor

Follow the steps given below to create a new category and install ElegantJ PDF into Eclipse Editor.

 

Create New Project (i.e. ElegantJ PDF)

Ø       Right click on created Project (right click on ElegantJ PDF). It opens Properties dialog box for Project (i.e. ElegantJ PDF)

Ø       Select Java Build Path from Left pane tree.

Ø       On right pane, click on Libraries tab and click on Add External JARs button.

Ø       It opens File dialog box, locate a jar file.

Ø       Click on OK button on File dialog box.

Ø       The located jar file is displayed into the list.

Ø       Click on OK button on Properties dialog box.


 

5.4  Getting and Using the License Key

5.4.1How to Purchase

You can purchase a license from our Web site http://www.ElegantJPDF.com. You can also contact our sales team sales@ElegantJPDF.com.

 

On purchasing a license, you will receive a mail having your license key.

 

License key can be applied to ElegantJ PDF Library using directly with the source code.

 

5.4.2Configuring Directly within Source Code

When you use the ElegantJ PDF within code, you need to set the key by providing value in setLicenseKey method.

 

Note:

Instead of typing the license key, we suggest you to copy the license key from mail and paste it at required place. Make sure that the selection does not have leading or trailing spaces.

 

ClassName object = new ClassName();
object.setLicenseKey("LICENSE_KEY");
 

 

Example

 

PDF pdf = new PDF();
pdf.setLicenseKey("LICENSE_KEY");

 


 

6       Programmer’s Guide

 

6.1  ElegantJ PDF Library

 

6.1.1Creating an instance of ElegantJ PDF

Ø       To create an instance of ElegantJ PDF,

 

Example1: Create PDF object with default page mode.  Default page mode is Catalog.USEONE

 

com.elegantj.pdf.PDF pdf = new com.elegantj.pdf.PDF();

 

Example 2: Create PDF object with specified page mode.

 

com.elegantj.pdf.PDF pdf = new

com.elegantj.pdf.PDF(com.elegantj.pdf.Catalog.USEOUTLINES); // which creates the PDF object with specified page mode

 

This creates PDF object with specified page mode.  Page mode determines how the document will present itself to the viewer when it first opens.  Available values for page mode are -

 

com.elegantj.pdf.Catalog.USENONE

com.elegantj.pdf.Catalog.USEOUTLINES

com.elegantj.pdf.Catalog.USETHUMBS

com.elegantj.pdf.Catalog.FULLSCREEN

 

6.1.2Creating and adding a Page to PDF

Ø       Page object provides each page of PDF.

 

Ø       Page object can be created in following ways,

 

First way:

 

com.elegantj.pdf.Page page = new com.elegantj.pdf.Page(pdf.getPages());

 

This creates the Page with specified Pages object.

 

Second way:

 

com.elegantj.pdf.Page page = new com.elegantj.pdf.Page(pdf.getPages(), com.elegantj.pdf.Page.ROTATE_90);

 

This creates Page with specified Pages and rotation to rotate the page.  Permissible values for rotation are -

 

com.elegantj.pdf.Page.ROTATE_0

com.elegantj.pdf.Page.ROTATE_90

com.elegantj.pdf.Page.ROTATE_180

com.elegantj.pdf.Page.ROTATE_270

 

Third way:

 

com.elegantj.pdf.Page page = new com.elegantj.pdf.Page(pdf.getPages(), com.elegantj.pdf.MediaBox.MEDIA_a4);

 

This creates Page with specified Pages and specified mediabox.  Mediabox represent page size (width and height) in pixels.

 

Fourth way: 

 

com.elegantj.pdf.Page page = new com.elegantj.pdf.Page(pdf.getPages(), com.elegantj.pdf.MediaBox.MEDIA_a4, com.elegantj.pdf.Page.ROTATE_90);

 

This creates Page with specified Pages, mediabox and rotation.

 

Ø       To add page to PDF,

 

pdf.add(page);

 

This adds page to the PDF.

 

 

6.1.3Creating True Type font

Ø       TrueTypeFont provides true type font for PDF. True Type Font can be created in following way,

 

String fontFilePath = "c:\\windows\\fonts\\arial.ttf"; // font file path

int fontStyle = com.elegantj.pdf.TrueTypeFont.REGULAR; // font style

String encoding = com.elegantj.pdf.TrueTypeFont.WINANSI; // encoding

boolean isEmbedded = true; // if embedding the font or not

boolean isSubset = true; // if subset or not, which excludes the unneeded chararacters

com.elegantj.pdf.TrueTypeFont trueTypeFont = new com.elegantj.pdf.TrueTypeFont(fontFilePath, fontStyle, encoding, isEmbedded, isSubset);

 

This creates TrueTypeFOnt with the specified font file path, font style, font encoding, if embedding font or not and if subseting the font or not.

 

The possible values for font style are:

 

com.elegantj.pdf.TrueTypeFont.REGULAR

com.elegantj.pdf.TrueTypeFont.BOLD

com.elegantj.pdf.TrueTypeFont.ITALIC

com.elegantj.pdf.TrueTypeFont.BOLDITALIC

 

If embeding is set to true, then font is embedded to the file, so that PDF file will also be opened on a compujer where respective fonts are not installed.

 

If subseting is set to true, then embedding PDF library removes characters that are not needed.  This keeps PDF file of smaller size.

 

 

6.1.4Creating Type1 font

Ø       Type1Font provides the type1 font for the PDF.

 

Ø       Type1 Font can be created in following ways,  

 

First way:

 

com.elegantj.pdf.Type1Font base14Type1Font = new com.elegantj.pdf.Type1Font(com.elegantj.pdf.Type1Font.COURIER, com.elegantj.pdf.TypeFont.WINANSI);

 

This creates type1 font with specified font and specified encoding.

The specified values for the base font name are:

 

com.elegantj.pdf.Type1Font.COURIER

com.elegantj.pdf.Type1Font.COURIER_BOLD

com.elegantj.pdf.Type1Font.COURIER_BOLDOBLIQUE

com.elegantj.pdf.Type1Font.COURIER_OBLIQUE

com.elegantj.pdf.Type1Font.HELVETICA

com.elegantj.pdf.Type1Font.HELVETICA_BOLD

com.elegantj.pdf.Type1Font.HELVETICA_BOLDOBLIQUE

com.elegantj.pdf.Type1Font.HELVETICA_OBLIQUE

com.elegantj.pdf.Type1Font.SYMBOL

com.elegantj.pdf.Type1Font.TIMES_BOLD

com.elegantj.pdf.Type1Font.TIMES_BOLDITALIC

com.elegantj.pdf.Type1Font.TIMES_ITALIC

com.elegantj.pdf.Type1Font.TIMES_ROMAN

com.elegantj.pdf.Type1Font.ZAPFDINGBATS

 

Second way:

 

String afmFilePath = "afmFilePath";

String pfbFilePath = "pfbFilePath";

com.elegantj.pdf.Type1Font type1Font = new com.elegantj.pdf.Type1Font(afmFilePath, pfbFilePath, com.elegantj.pdf.Type1Font.WINANSI);

 

This creates Type1Font with specified afm and pfb file path and encoding.

 

 

6.1.5Creating TrueTypeCJK font

Ø       TrueTypeCJKFont facilitates the user to user true type CJK font in PDF.  TrueTypeCJKFont provides the True Type Chinese, Japanese and Korean fonts (also Bi-Di fonts like Arabic) for the PDF.

 

Ø       True Type CJK Font can be created in following way:

 

String cjkFontFilePath = "c:\\windows\\Msgothic.ttc";

int fontStyle = com.elegantj.pdf.TrueTypeCJKFont.BOLD;

String encoding = com.elegantj.pdf.TrueTypeCJKFont.IDENTITY_H;

com.elegantj.pdf.TrueTypeCJKFont trueTypeCJKFont = new com.elegantj.pdf.TrueTypeCJKFont(cjkFontFilePath, fontStyle, encoding);

 

This creates TrueTypeCJKFont with the specified file path, font style and encoding.

 

Possible values for font style are -

 

com.elegantj.pdf.TrueTypeCJKFont.REGULAR

com.elegantj.pdf.TrueTypeCJKFont.BOLD

com.elegantj.pdf.TrueTypeCJKFont.ITALIC

com.elegantj.pdf.TrueTypeCJKFont.BOLDITALIC

 

Possible values for the encoding are -

 

com.elegantj.pdf.TrueTypeCJKFont.IDENITY_H

com.elegantj.pdf.TrueTypeCJKFont.IDENITY_V

 

 

6.1.6Creating CJK font

Ø       CJKFont provides the Chinese, Japanese and Korean fonts for the PDF.  Following is the procedure to create CJKFont with specified font and style -

 

int font = com.elegantj.pdf.CJKFont.HEISEIKAKUGO_W5;

int fontStyle = com.elegantj.pdf.CJKFont.REGULAR;

com.elegantj.pdf.CJKFont cjkFont = new com.elegantj.pdf.CJKFont(font, fontStyle);

 

This creates CJKFont with the specified font and the font style.

 

Possible values for the font are -

 

com.elegantj.pdf.CJKFont.HEISEIKAKUGO_W5

com.elegantj.pdf.CJKFont.HEISEIMIN_W3

com.elegantj.pdf.CJKFont.HYGOTHIC_MEDIUM

com.elegantj.pdf.CJKFont.HYSMYEONGJO_MEDIUM

com.elegantj.pdf.CJKFont.HYSMYEONGJOSTD_MEDIUM

com.elegantj.pdf.CJKFont.KOZMINPRO_REGULAR

com.elegantj.pdf.CJKFont.MHEI_MEDIUM

com.elegantj.pdf.CJKFont.MSUNG_LIGHT

com.elegantj.pdf.CJKFont.MSUNGSTD_LIGHT

com.elegantj.pdf.CJKFont.STSONG_LIGHT

com.elegantj.pdf.CJKFont.STSONGSTD_LIGHT

 

Possible values for the font style are -

 

com.elegantj.pdf.CJKFont.REGULAR

com.elegantj.pdf.CJKFont.BOLD

com.elegantj.pdf.CJKFont.ITALIC

com.elegantj.pdf.CJKFont.BOLDITALIC

 

6.1.7Creating and Adding PDFText to page

Ø       PDFText can be created in following ways, 

 

First way:

 

String text = "Specified text";

com.elegantj.pdf.PDFText pdfText = new com.elegantj.pdf.PDFText(text);

 

This creates PDFText with specified text, it will draw the text to the rectangle made by mediabox and the alignment for the text will be considered LEFT.

 

Second way:

 

String text = "Specified text";

int x = 10;

int y = 10;

com.elegantj.pdf.PDFText pdfText = new com.elegantj.pdf.PDFText(text, x, y);

 

This creates PDFText with specified text, x and y coordinates.  It draws text to rectangle made by x, y, mediabox's width and height and alignment for left alignment will be considered.

 

Third way:

 

String text = "Specified text";

int upperLeftX = 0;

int upperLeftY = 0;

int lowerRightX = 200;

int lowerRightY = 200;

com.elegantj.pdf.PDFText pdfText = new com.elegantj.pdf.PDFText("Specified Text", upperLeftX, upperLeftY, lowerRightX, lowerRightY);

 

This creates PDFText with specified text, upperLeftX, upperLeftY, lowerRightX and lowerRightY.  If specified text contains new line characters like '\r' or '\n', new line character gets appended to PDF, i.e. next gets drawn to new line in PDF.  If specified text's length goes out of rectangle width, then line get wrapped if wrap style word is true, i.e. it draws only characters which are fit within the rectangle width and the remaining characters appears in the next line.

 

Ø       To set alignment of PDFText, 

 

Permissible values are,

 

com.elegantj.pdf.PDFText.PDFText.LEFT

com.elegantj.pdf.PDFText.RIGHT

com.elegantj.pdf.PDFText.CENTER

com.elegantj.pdf.PDFText.JUSIFY

 

The default value is that of LEFT

 

pdfText.setAlignment(com.elegantj.pdf.PDFText.LEFT); // Sets alignment to LEFT

 

Ø       To set fill color,

 

java.awt.Color fillColor = java.awt.Color.red;

pdfText.setFillColor(fillColor);

 

Ø       To set outline color, 

 

Set value of outline mode to true before setting outline color.

 

java.awt.Color outlineColor = java.awt.Color.black;

pdfText.setOutlineMode(true);

pdfText.setOutlineColor(black);

 

Ø       To set PDFFont, set PDFFont using

 

pdfText.setPDFFont(pdfFont); // pdfFont is object of TrueTypeFont, Type1Font, CJKFont or TrueTypeCJKFont

 

Ø       To set font size

 

pdfText.setFontSize(20); // sets font size to 20

 

Ø       To set horizontal scaling

 

pdfText.setHorizontalScaling(200); // sets horizontal scaling

 

Ø       To set indent

 

pdfText.setIndent(10); // sets indent

 

This sets indent for PDFText i.e. number of pixels to be left for the first line of this PDFText object.  Pixels are left to keep gap on the first line of Paragraph.  Specify value of indent.  Default value is 0.  Indent value must be less than specified PDFText width.  Indent works only with the alignment LEFT and JUSTIFY.

 

Ø       To set PDFPattern to PDFText

 

pdfText.setPattern(pdfPattern); //sets the pdfPattern

 

Ø       To set underline true

 

pdfText.setUnderLine(true);

 

Ø       To set strike out true

 

pdfText.setStrikeOut(true);

 

Ø       To set word spacing

 

pdfText.setWordSpacing(5); // sets the word spacing to 5

 

Ø       To set char spacing

 

pdfText.setCharSpacing(5); // sets the char spacing to 5

 

Ø       To create clone object

 

com.elegantj.pdf.PDFText pdfText2 = (com.elegantj.pdf.PDFText)pdfText.clone();

 

6.1.8Adding PDFText to the Page

Ø       The PDFText object can be added to the Page using following code

 

com.elegantj.pdf.PDF pdf = new com.elegantj.pdf.PDF();

com.elegantj.pdf.Page page = new com.elegantj.pdf.Page(pdf.getPages(), com.elegantj.pdf.MediaBox.MEDIA_a4);

com.elegantj.pdf.PDFText text = new com.elegantj.pdf.PDFText("Specified Text");

page.addText(text);

 

On adding text to the page, if specified text does not fit within specified rectangle then it returns the overflowed string from page.addText method.

 

String overflowedString = page.addText(pdfText);

 

 

6.1.9Getting last Y coordinate on the page

Ø       PDFText contains the getLastY method.  Call this method after PDFText has been added to the page. This returns the last Y coordinate of the page after adding PDFText to the page.

 

int lastY = pdfText.getLastY() // which returns the last Y coordinate of page, after PDFText has been added

 

This method is useful in the following cases:

 

case 1: If given text is less than the area of the rectangle is built by upperLeftX, upperLeftY, lowerRightX and lowerRigghtY.

 

case 2: If upperLeftX, upperLeftY, lowerRightX and lowerRightY is not provided during PDFText object creation.

 

case 3: If only upperLeftX and upperLeftY are provided during PDFText object creation.

 

So, using this method user can pick last Y value on page, and can recreate next PDFText object based on this Y value.

 

It returns the last Y coordinate of the page after adding this text to the page.  To get proper value of this, call it immidiately after adding the PDFText to the Page.

 

This value is mostly used when PDFText makes automatic wrapping.  So, in that case, case if user wants to know the last Y, after knowing lastY user can build new PDFText object from this y value easily.

 

6.1.10      Creating and adding PDFLine to Page

Ø       PDFLine provides line object for the PDF.

 

Ø       To create line object for the PDF,

 

int x1 = 100;

int x2 = 100;

int y1 = 200;

int y2 = 200;

com.elegantj.pdf.PDFLine pdfLine = new com.elegantj.pdf.PDFLine(x1, x2, y1, y2);

 

This creates PDFLine using x1, x2, y1 and y2.

 

Ø       To set the startX, startY, endX and endY

 

pdfLine.setStartX(100);

pdfLine.setStartY(100);

pdfLine.setEndX(200);

pdfLine.setEndY(200);

 

Ø       To set cap style

 

pdfLine.setCapStyle(com.elegantj.pdf.PDFLine.BUTT_CAPS);

 

Permissible values for cap style are :

 

com.elegantj.pdf.PDFLine.BUTT_CAPS

com.elegantj.pdf.PDFLine.ROUND_CAPS

com.elegantj.pdf.PDFLine.SQUARE_CAPS

 

Ø       To set join style

 

pdfLine.setJoinStyle(com.elegantj.pdf.PDFLine.ROUND_JOINS);

 

Permissible values for join style are -

 

com.elegantj.pdf.PDFLine.MITER_JOINS

com.elegantj.pdf.PDFLine.ROUND_JOINS

com.elegantj.pdf.PDFLine.BEVEL_JOINS

 

Ø       To set line color

 

java.awt.Color lineColor = java.awt.Color.red;

pdfLine.setLineColor(lineColor);

 

Ø       To set line width

 

int lineWidth = 5;

pdfLine.setLineWidth(lineWidth);

 

Ø       To set dash pattern

 

int dashLength = 10;

int gapLength = 10;

pdfText.setDashPattern(dashLength, gapLength);

 

Ø       To clone the PDFLine

 

com.elegantj.pdf.PDFLine pdfLine2 = (com.elegantj.pdf.PDFLine)pdfLine.clone();

 

Ø       To add PDFLine to page,

 

page.addGraphics(pdfLine);

 

This adds the PDFLine to the page.

 

 

6.1.11      Creating and adding PDFRectangle to Page

Ø       PDFRectangle provides rectangle object for the PDF.

 

Ø       To create PDFRectangle:

 

int x = 100;

int y = 100;

int width = 200;

int height = 100;

int outlineWidth = 5;

java.awt.Color outlineColor = java.awt.Color.black;

java.awt.Color fillColor = java.awt.Color.blue;

 

com.elegantj.pdf.PDFRectangle rect = new com.elegantj.pdf.PDFRectangle(x, y, width, height, outlineWidth, outlineColor, fillColor);

rect.setFillMode(true);

 

This creates PDFRectangle with the x, y, width, height, outlineWidth, outlineColor and fillColor.

 

Ø       To set fill color

 

java.awt.Color fillColor = java.awt.Color.red;

pdfRectangle.setFillMode(true);

pdfRectangle.setFillColor(fillColor);

 

Ø       To set line color

 

java.awt.Color outLineColor = java.awt.Color.black;

pdfRectangle.setOutlineColor(outLineColor);

 

Ø       To set outline width

 

int outlineWidth = 5;

pdfRectangle.setOutlineWidth(outlineWidth);

 

Ø       To set x, y, width and height

 

int x = 5;

int y = 5;

int width = 100:

int height = 200;

 

pdfRectangle.setX(x);

pdfRectangle.setY(y);

pdfRectangle.setWidth(width);

pdfRectangle.setHeight(height);

 

Ø       To set join style for lines of rectangle

 

pdfRectangle.setJoinStyle(com.elegantj.pdf.PDFRectangle.ROUND_JOINS);

 

The possible values for the join style are -

 

com.elegantj.pdf.PDFGraphicsObject.MITER_JOINS,

com.elegantj.pdf.PDFGraphicsObject.ROUND_JOINS,

com.elegantj.pdf.PDFGraphicsObject.BEVEL_JOINS

 

Ø       To set PDFPattern

 

pdfRectangle.setPDFPattern(pdfPattern); // which sets the pdf pattern to the PDFRectangle

 

Ø       To clone the PDFRectangle

 

com.elegantj.pdf.PDFRectangle pdfRectangle2 = (com.elegantj.pdf.PDFRectangle)pdfRectangle.clone();

 

Ø       To add PDFRectangle to the page

 

page.addGraphics(pdfRectangle);

 

This adds PDFRectangle to the pdf page.

 

 

6.1.12      Creating and adding PDFCircle to Page

Ø       PDFCircle Provides Circle object for PDF.

 

Ø       To create PDFCircle object,

 

int x = 100;

int y = 100;

int radius = 50;

int outlineWidth = 2;

java.awt.Color outlineColor = java.awt.Color.black;

java.awt.Color fillColor = java.awt.Color.red;

com.elegantj.pdf.PDFCircle circle = new com.elegantj.pdf.PDFCircle(x, y, radius, outlineWidth, outlineColor fillColor);

circle.setFillMode(true);

 

This creates PDFCircle with the specified x, y, radius, outline width, outline color and fill color.

 

Ø       To set x, y, and radius

 

int x = 100;

int y = 100;

int radius = 25;

 

pdfCircle.setX(x);

pdfCircle.setY(y);

pdfCircle.setRadius(radius);

 

Ø       To set fill color

 

java.awt.Color fillColor = java.awt.Color.red;

pdfCircle.setFillMode(true);

pdfCircle.setFillColor(fillColor);

 

Ø       To set outline color

 

java.awt.Color outlineColor = java.awt.Color.black;

pdfCircle.setOutlineColor(outlineColor);

 

Ø       To set outline width

 

int outlineWidth = 5;

pdfCircle.setOutlineWidth(outlineWidth);

 

Ø       To set PDFPattern

 

pdfCircle.setPDFPattern(pdfPattern);

 

Ø       To clone the PDFCircle object

 

PDFCirlce pdfCircle2 = (com.elegantj.pdf.PDFCircle)pdfCircle.clone();

 

Ø       To Add PDFCircle to page

 

page.addGraphics(pdfCircle);

 

This adds PDFCircle to the page.

 

6.1.13      Creating and adding PDFOval to Page

Ø       PDFOval provides Oval object for PDF.

 

Ø       To create PDFOval object

 

int x = 100;

int y = 100;

int width = 200;

int height = 50;

int outlineWidth = 5;

java.awt.Color outlineColor = java.awt.Color.black;

java.awt.Color fillColor = java.awt.Color.red;

 

com.elegantj.pdf.PDFOval oval = new com.elegantj.pdf.PDFOval(x, y, width, height, outlineWidth, outlineColor, fillColor);

oval.setFillMode(true);

 

This creates PDFOval with the specified x, y, width, height, outline width, outline color and fill color;

 

Ø       To set x, y, width and height

 

int x = 100;

int y = 100;

int width = 25;

int height = 20;

 

pdfOval.setX(x);

pdfOval.setY(y);

pdfOval.setWidth(width);

pdfOval.setHeight(height);

 

Ø       To set fill color

 

java.awt.Color fillColor = java.awt.Color.red;

pdfOval.setFillMode(true);

pdfOval.setFillColor(fillColor);

 

Ø       To set outline color

 

java.awt.Color outlineColor = java.awt.Color.black;

pdfOval.setOutlineColor(outlineColor);

 

Ø       To set outline width

 

int outlineWidth = 5;

pdfOval.setOutlineWidth(outlineWidth);

 

Ø       To set PDFPattern

 

pdfOval.setPDFPattern(pdfPattern);

 

Ø       To clone the PDFCircle object

 

com.elegantj.pdf.PDFOval pdfOval2 = (com.elegantj.pdf.PDFOval)pdfOval.clone();

 

Ø       To add PDFOval to the page,

 

page.addGraphics(pdfOval);

 

This adds PDFOval to the page.

 

 

6.1.14      Creating and Adding PDFArc to Page

Ø       PDFArc object provides arc object for the PDF.

 

Ø       To create PDFArc object, To create a PDFArc, we need a start point, end point and 2 control points.

 

int x1 = 100;

int y1 = 130;

int x2 = 500;

int y2 = 130;

int cx1 = 200;

int cy1 = 170;

int cx2 = 350;

int cy2 = 170;

int outlineWidth = 5;

java.awt.Color outLineColor = java.awt.Color.black;

java.awt.Color fillColor = java.awt.Color.green;

com.elegantj.pdf.PDFArc pdfArc = new com.elegantj.pdf.PDFArc(x1, x2, y1, y2, cx1, cy1, cx2, cy2, outlineWidth, outlineColor, fillColor);

arc.setFillMode(true);

 

This creates PDFArc with specified 2 end points x1, y1 and  x2, y2, 2 control points cx2, cx2 and cy1, cy2 and outline width, outline color and fill color.

 

Ø       To set x1, y1, x2, y2, cx1, cy2

 

pdfArc.setX1(x1);

pdfArc.setY1(y1);

pdfArc.setX2(x2);

pdfArc.setY2(y2);

pdfArc.setCX1(cx1);

pdfArc.setCY1(cy1);

pdfArc.setCX2(cx2);

pdfArc.setCY2(cy2);

 

Ø       To set outline color and fill color

 

java.awt.Color outlineColor = java.awt.Color.black;

java.awt.Color fillColor = java.awt.Color.red;

pdfArc.setOutlineColor(outlineColor);

pdfArc.setFillMode(truie);

pdfArc.setFillColor(fillColor);

 

Ø       To set outline width

 

pdfArc.setOutlineWidth(5);

 

Ø       To set PDFPattern

 

pdfArc.setPDFPattern(pdfPattern);

 

Ø       To clone the PDFArc

 

com.elegantj.pdf.PDFArc pdfArc2 = (com.elegantj.pdf.PDFArc)pdfArc.clone();

 

Ø       To add PDFArc to the Page,

 

page.addGraphics(arc);

 

This adds pdfArc to the page.

 

 

6.1.15      Creating and adding PDFPolygon to Page

Ø       PDFPolygonobject provides polygon object for the PDF.

 

Ø       To create a PDFPolygon object,

 

int x[] = new int[]{100 + 50, 150 + 50, 300 + 50, 350 + 50, 400 + 50, 100 + 50};

int y[] = new int[]{180, 130, 130, 180, 310, 310};

int nPoints = 6;

com.elegantj.pdf.PDFPolygon polygon = new com.elegantj.pdf.PDFPolygon(x, y, nPoints);

 

This creates PDFPolygon with specified x points, y points and nPoints.

 

Ø       To set x, y coordinates and points,

 

pdfPolygon.setXCoordinates(new int[]{100 + 50, 150 + 50, 300 + 50, 350 + 50, 400 + 50, 100 + 50});

pdfPolygon.setYCoordinates(new int[]{180, 130, 130, 180, 310, 310});

pdfPolygon.setPoints(6);

 

Ø       To set the fill color, outline color and outline with

 

java.awt.Color fillColor = java.awt.Color.red;

java.awt.Color outlineColor = java.awt.Color.black;

int outlineWidth = 5;

pdfPolygon.setFillMode(true);

pdfPolygon.setFillColor(fillColor);

pdfPolygon.setOutlineWidth(outlineWidth);

 

Ø       To set line join style

 

pdfPolygon.setJoinStyle(com.elegantj.pdf.PDFPolygon.ROUND_JOINS);

 

Permissible values for join style are

 

com.elegantj.pdf.PDFPolygon.MITER_JOINS

com.elegantj.pdf.PDFPolygon.ROUND_JOINS

com.elegantj.pdf.PDFPolygon.BEVEL_JOINS

 

Ø       To apply the PDFPattern to the PDFPolygon

 

pdfPolygon.setPDFPattern(pdfPattern);

 

Ø       To create the clone of the PDFPolygon

 

com.elegantj.pdf.PDFPolygon pdfPolygon2 = (com.elegantj.pdf.PDFPolygon)pdfPolygonl;

 

Ø       To add PDFPolygon to the Page

 

page.addGraphics(pdfPolygon);

 

This adds pdfPolygon to the Page.

 

6.1.16      Creating and adding PDFImage to page

Ø       PDFImage provides image object for the PDF.  This supports JPEG image.

 

Ø       PDFImage can be created in any of the following ways, 

 

First way:

 

java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(imageURL);

com.elegantj.pdf.PDFImage pdfImage = new com.elegantj.pdf.PDFImage(image)

 

This creates PDFImage with the specified java.awt.Image.

 

Second way:

 

java.net.URL url = getClass().getResource("image.jpg");

com.elegantj.pdf.PDFImage pdfImage = new com.elegantj.pdf.PDFImage(url);

 

This creates the PDFImage with the specified image URL.

 

Ø       To set the x, y, width and height

 

pdfImage.setX(x);

pdfImage.setY(y);

pdfImage.setImageWidth(imageWidth);

pdfImage.setImageHeight(imageHeight);

 

Ø       To clone the PDFImage object,

 

com.elegantj.pdf.PDFImage image2 = (com.elegantj.pdf.PDFImage)image.clone();

 

Ø       To add PDFImage to the PDF

 

page.addImage(pdfImage);

 

This adds the pdfImage to the page

 

6.1.17      Creating and applying PDFPattern

Ø       PDFPattern provides different type of patterns for PDF

 

Ø       To create PDFPattern,

 

com.elegantj.pdf.PDFPattern pdfPattern = new com.elegantj.pdf.PDFPattern();

 

Ø       To set pattern style

 

int patternStyle = com.elegantj.pdf.PDFPattern.CHECK_PATTERN;

pdfPattern.setPatternStyle(patternStyle);

 

Permissible values for pattern style are -

 

com.elegantj.pdf.PDFPattern.CHECK_PATTERN

com.elegantj.pdf.PDFPattern.CIRCLE_PATTERN

com.elegantj.pdf.PDFPattern.HORIZONTAL_LINE_PATTERN

com.elegantj.pdf.PDFPattern.INCLINED_LINE_PATTERN

com.elegantj.pdf.PDFPattern.OVAL_PATTERN

com.elegantj.pdf.PDFPattern.STAR_PATTERN

com.elegantj.pdf.PDFPattern.VERTICAL_LINE_PATTERN

 

Ø       To set background, foreground

 

java.awt.Color background = java.awt.Color.cyan;

java.awt.Color foreground = java.awt.Color.red;

pdfPattern.setBackground(background);

pdfPattern.setForeground(foreground);

 

Ø       To set bounding box width and height

 

int boundingBoxWidth = 100;

int boundingBoxHeight = 50;

pdfPattern.setBoundingBoxWidth(boundingBoxWidth);

pdfPattern.setBoundingBoxHeight(boundingBoxHeight);

 

Ø       To set image as pattern

 

pdfPattern.setImage(pdfImage); // which sets the PDFImage as a pattern

 

This sets PDFImage as pattern.

 

Ø       To set Pattern Graphics -- For advanced user only

 

String patternGraphics = "THE PATTERN GRAPHICS AS PER ADOBE PDF SPECIFICATION";

pdfPattern.setPatternGraphics(patternGraphics);

 

This sets pattern graphic.  This graphic must be according to the PDF specification.  If user wants to use only predefined type of pattern style, then there is no need to do setting.  If this pattern graphics is not proper, Acrobat Reader could not open this PDF file successfully.  If one sets pattern graphic explicitly for PDFPattern, then Foreground, Background, PatternStyle will be not considered.  Also, if user has set the pattern graphic, user would have to set the BoundingBoxWidth and BoundingBoxHeight.  Else, this pattern graphics will not work and pattern generated based on the current pattern style will appear.

 

Ø       To clone the PDFPattern

 

com.elegantj.pdf.PDFPattern pdfPattern2 = (com.elegantj.pdf.PDFPattern)pdfPattern.clone();

 

This creates the clone of the PDFPattern.

 

6.1.18      Applying PDFPattern to any Graphic Object

Ø       PDFPattern canbe applied to following PDF Objects :

 

com.elegantj.pdf.PDFText

com.elegantj.pdf.PDFLine

com.elegantj.pdf.PDFRectangle

com.elegantj.pdf.PDFCircle

com.elegantj.pdf.PDFOval

com.elegantj.pdf.PDFArc

com.elegantj.pdf.PDFPolygon

com.elegantj.pdf.PDFTable

 

To set PDFPattern to any of the above listed objects,

 

com.elegantj.pdf.PDFPattern pdfPattern = new com.elegantj.pdf.PDFPattern(com.elegantj.pdf.PDFPattern.CIRCLE_PATTERN);

pdfText.setPattern(pdfPattern);

 

Using this method you can apply PDFPattern to the any graphics object which are listed above.

 

 

6.1.19      Creating and adding PDFRubberStampAnnotation to the page

Ø       PDFRubberStampAnnotation object provides the rubber stamp annotation for the PDF.

 

Ø       To create PDFRubberStampAnnotation, 

 

String text = "PDF rubber stamp annotation";

int x = 100:

int y = 100;

int width = 200;

int height = 50;

com.elegantj.pdf.PDFFont pdfFont = new com.elegantj.pdf.TrueTypeFont("c:/windows/fonts/arial.ttf", com.elegantj.pdf.PDFFont.REGULAR, com.elegantj.pdf.PDFFont.WINANSI, true, true);

com.elegantj.pdf.PDFRubberStampAnnotation annot = new com.elegantj.pdf.PDFRubberStampAnnotation(text, x, y, width, height, pdfFont);

 

This creates PDFRubberStampAnnotation with specified text, x, y, width, height and pdfFont.

 

To clone the PDFRubberStampAnnotation

 

com.elegantj.pdf.PDFRubberStampAnnotation annot2 = (com.elegantj.pdf.PDFRubberStampAnnotation)annot.clone();

 

To add PDFRubberStampAnnotation to the page,

 

page.addAnnotation(annot);

 

This adds PDFRubberStampAnnotation to the page.

 

 

6.1.20      Creating and adding PDFTextAnnotation to the page

Ø       PDFTextAnnotation provides text annotation for the PDF.

 

Ø       To create PDFTextAnnotation, 

 

Stirng text = "Annotation text";

int x = 100;

int y = 100;

int width = 200;

int height = 100;

com.elegantj.pdf.PDFTextAnnotaion annot = new com.elegantj.pdf.PDFTextAnnotation(text, 100, 100, 200, 100);

 

This creates PDFTextAnnotation with the specified text, x, y, width and height.

 

Ø       To set title and color

 

annot.setTitle("Title"); // which sets the title of the PDFTextAnnotation

annot.setColor(java.awt.Color.black); // which sets the color for the PDFTextAnnotation

 

Ø       To set the mode

 

annot.setOpen(true); // keeps annotation open on opening PDF

 

Ø       To clone the PDFTextAnnotation

 

com.elegantj.pdf.PDFTextAnnotation annot2 = (com.elegantj.pdf.PDFTextAnnotation)annot.clone();

 

This clones the PDFTextAnnotation.

 

Ø       To add PDFTextAnnotation to the page,

 

page.addAnnotation(annot);

 

This adds the PDFTextAnnotation to the page.

 

 

6.1.21      Creating and adding PDFLinkAnnotation to the page

Ø       PDFLinkAnnotation provides link annotation for the PDF.

 

Ø       PDFLinkAnnotation can be created in following ways,

 

First way:

 

int x = 100;

int y = 100;

int width = 200;

int height = 20;

java.net.URL url = new java.net.URL("http://www.elegantJBeans.com");

com.elegantj.pdf.PDFLinkAnnotation annot = new com.elegantj.pdf.PDFLinkAnnotation(x, y, width, height, url);

 

This creates the PDFLinkAnnotation with the specified x, y, width, height and URL.

 

Second way:

 

com.elegantj.pdf.Page destpage = new com.elegantj.pdf.Page(pdf.getPages(), com.elegantj.pdf.MediaBox.MEDIA_a4);

int x = 100;

int y = 100;

int width = 200;

int height = 20;

int dest_X = 0;

int dest_Y = 0;

com.elegantj.pdf.PDFLinkAnnotation annot = new com.elegantj.pdf.PDFLinkAnnotation(destPage, x, y, width, height, dest_X, dest_Y);

 

This creates the PDFLinkAnnotation object with the specified destination page, x, y, width, height and x, y coordinates on the destination page.

 

Ø       To set color, zoom factor and border width

 

annot.setColor(java.awt.Color.black);

annot.setZoomFactor(100);

annot.setBorderWidth(2);

 

Ø       To clone PDFLinkAnnotation

 

com.elegantj.pdf.PDFLinkAnnotation annot2 = (com.elegantj.pdf.PDFLinkAnnotation)annot.clone();

 

This clones PDFLinkAnnotation.

 

Ø       To add PDFLinkAnnotation to the page,

 

page.addAnnotation(annot);

 

This adds the PDFLinkAnnotation to the page.

 

 

6.1.22      Creating and adding PDFTable to the page

Ø       PDFTable provides Table object for PDF

 

Ø       PDFTable can be created in following ways, 

 

First way:

 

int x = 100;

int y = 100;

int width = 500;

int height = 700;

com.elegantj.pdf.PDFTable table = new com.elegantj.pdf.PDFTable(x, y, width, height);

 

This creates table with specified x, y, width and height.

 

Second way:

 

int x = 100;

int y = 100;

int width = 500;

int height = 700;

int rowCount = 10;

int columnCount = 5;

com.elegantj.pdf.PDFTable table = new com.elegantj.pdf.PDFTable(x, y, width, height, rowCount, columnCount);

 

This creates table with specified x, y, width, height and row count and column count.

 

Ø       To set row count and column count

 

int rowCount = 10;

int columnCount = 5;

table.setRowCount(rowCount);

table.setColumnCount(columnCount);

 

Ø       To set color and width of outline

 

java.awt.Color outlineColor = java.awt.Color.black;

int outlineWidth = 5;

table.setOutlineColor(outlineColor); // sets the outline color as black

table.setOutlineWidth(outlineWidth); // set the outline width as 5 pixels

 

Ø       To set alignment at table, row, column and cell level

 

table.setDefaultAlignment(com.elegantj.pdf.PDFTable.LEFT); // sets default alignment for table to LEFT

table.setRowAlignmentAt(0, com.elegantj.pdf.PDFTable.LEFT); // sets alignment for row 0 to LEFT

table.setColumnAlignmentAt(0, com.elegantj.pdf.PDFTable.LEFT); // sets alignment for column 0 to LEFT

table.setCellAlignmentAt(0, 0, com.elegantj.pdf.PDFTable.LEFT); // sets the alignment for the cell (0,0) to LEFT

 

Permissible values for alignment are:

 

com.elegantj.pdf.PDFTable.LEFT

com.elegantj.pdf.PDFTable.RIGHT

com.elegantj.pdf.PDFTable.CENTER

 

Ø       To set background at table, row, column and cell level

 

table.setDefaultBackground(java.awt.Color.cyan); // sets default background for the table to cyan

table.setRowBackgroundAt(0, java.awt.Color.cyan); // sets row background for row 0 to cyan

table.setColumnBackgroundAt(0, java.awt.Color.cyan); // sets column background for column 0 to cyan

table.setCellBackgroundAt(0, 0, java.awt.Color.cyan); // sets cell background for cell (0, 0) to cyan

 

Ø       To set foreground at table, row, column and cell level

 

table.setDefaultForeground(java.awt.Color.black); // sets default foreground for table to black

table.setRowForegroundAt(0, java.awt.Color.black); // sets row foreground for row 0 to black

table.setColumnForegroundAt(0, java.awt.Color.black); // sets column foreground for column 0 to black

table.setCellForegroundAt(0, 0, java.awt.Color.black); // sets cell foreground for cell (0, 0) to black

 

Ø       To set background pattern at table, row, column and cell level

 

table.setDefaultBackground(pdfPattern); // sets PDFPattern as background for the table

table.setRowBackgroundAt(0, pdfPattern); // sets PDFPattern as background for row 0

table.setColumnBackgroundAt(0, pdfPattern); // sets the PDFPattern as background for column 0

table.setCellBackgroundAt(0, 0, pdfPattern); // sets the PDFPattern as background for cell (0, 0)

 

Ø       To set font at table, row, column and cell level

 

table.setDefaultFont(pdfFont, 10); // sets PDFFont for table with font size as 10

table.setRowFontAt(0, pdfFont, 10); // sets PDFFont for row 0 and font size as 10

table.setColumnFontAt(0, pdfFont, 10); // sets PDFFont for column 0 and font size as 10

table.setCellFontAt(0, 0, pdfFont, 10); // sets PDFFont for cell (0, 0) and font size as 10

 

Ø       To set data for PDFTable

 

java.util.Vector data = new java.util.Vector();

 

java.util.Vector rowData = new Vector();

rowData.addElement("Cell 1 1");

rowData.addElement("Cell 1 2");

rowData.addElement("Cell 1 2");

data.addElement(rowData);

 

rowData = new java.util.Vector();

rowData.addElement("Cell 2 1");

rowData.addElement("Cell 2 2");

rowData.addElement("Cell 2 3");

data.addElement(rowData);

 

table.setData(data);

 

Above vector contains the 2 rows which set the data to the PDFTable.

 

Ø       To set value at a specified cell

 

table.setValueAt("value", 0, 0); // sets the value for cell (0, 0)

 

Ø       To set row height at row level

 

table.setRowHeightAt(0, 20); // sets height of row 0 to 20 pixels

 

Ø       To set row heights

 

java.util.Vector rowHeights = new java.util.Vector();

rowHeights.addElement(new Integer(20));

rowHeights.addElement(new Integer(20));

table.setRowHeights(rowHeights);

 

This sets row heights.

 

Ø       To set column width at column level

 

table.setColumnWidthAt(0, 20); // sets the width of column 0 to 20 pixels

 

Ø       To set the column widths

 

java.util.Vector columnWidths = new java.util.Vector();

columnWidths.addElement(new Integer(100));

columnWidths.addElement(new Integer(100));

table.setColumnWidths(columnWidths);

 

This sets the column widths.

 

Ø       To add PDFTable object to the page

 

page.addTable(table);

 

This adds PDFTable to the page.

 

 

6.1.23      Creating Outline Tree

Ø       Outlines provides the Outlines or bookmarks tree for the PDF.

 

Ø       Outline Tree can be created in following ways,

 

First way:

 

com.elegantj.pdf.PDF pdf = new com.elegantj.pdf.PDF(com.elegantj.pdf.Catalog.USEOUTLINES);

com.elegantj.pdf.Outlines base = pdf.getOutlines();

com.elegantj.pdf.Outlines outlines = new com.elegantj.pdf.Outlines(pdf);

base.add(outlines);

 

This creates default base outline object with specified pdf, then adds outlines to the base outline of PDF.

 

Second way:

 

com.elegantj.pdf.PDF pdf = new com.elegantj.pdf.PDF(Catalog.USEOUTLINES);

String title = "Title";

 

com.elegantj.pdf.Page destinationPage = new com.elegantj.pdf.Page(pdf.getPages(), com.elegantj.pdf.MediaBox.MEDIA_a4);

 

com.elegantj.pdf.Outlines base = pdf.getOutlines();

com.elegantj.pdf.Outlines outlines = new com.elegantj.pdf.Outlines(pdf, title, destinationPage);

base.add(outlines);

 

This creates outline object with specified PDF, title and destination page, and then adds outlines to the base outline of pdf.

 

Third way:

 

com.elegantj.pdf.PDF pdf = new com.elegantj.pdf.PDF(com.elegantj.pdf.Catalog.USEOUTLINES);

String title = "Title";

int x = 0;

int y = 0;

int width = 100;

int height = 100;

 

com.elegantj.pdf.Page destinationPage = new com.elegantj.pdf.Page(pdf.getPages(), com.elegantj.pdf.MediaBox.MEDIA_a4);

 

com.elegantj.pdf.Outlines base = pdf.getOutlines();

com.elegantj.pdf.Outlines outlines = new com.elegantj.pdf.Outlines(pdf, title, destinationPage, x, y, width, height);

base.add(outlines);

 

This creates outlines object with specified pdf, title, destination page and x, y, width and height of the destination page, (which becomes visible on clicking the outline) then adds the outlines to the base outline of PDF.

 

Other outlines object can be added to the base outline object.

 

Ø       To add outlines to the existing outlines without creating Outlines object,

Two procedures given below directly adds outlines to the base / existing outlines.

 

First way:

 

outlines.add("Title", destinationPage); // adds the outline with title "Title" and target page

 

This internally creates Outlines with specified title and destination page, and then it adds newly created outlines to the existing outlines object.

 

Second way:

 

outlines.add("Title", destinationPage, x, y , width, height); // adds the outline with title "Title",  target page,  x, y, width and height.

 

This internally creates Outlines with specified title, destination page, x, y, width and height, and then it adds the newly created outlines to the existing outlines object.

 

 

6.1.24      Example Using Outlines

Ø       Code given below creates the whole outlines, following snippets taken from EJPDFDemo.java, which is included inside the ElegantJ PDF Bundle).

 

com.elegantj.pdf.PDF pdf = new com.elegantj.pdf.PDF(com.elegantj.pdf.Catalog.USEOUTLINES);

 

// Get instance of root of outlines

 

com.elegantj.pdf.Outlines baseOutline = pdf.getOutlines();

 

// Create new outlines with destinations page

 

com.elegantj.pdf.Outlines pdfTextDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Text Demo", pdfTextAttributesPage1);

com.elegantj.pdf.Outlines pdfTextDemo1 = new com.elegantj.pdf.Outlines(pdf, "Text Attributes 1", pdfTextAttributesPage1);

com.elegantj.pdf.Outlines pdfTextDemo2 = new com.elegantj.pdf.Outlines(pdf, "Text Attributes 2", pdfTextAttributesPage2);

 

// adds outlines to outlines

 

pdfTextDemo.add(pdfTextDemo1);

 

// adds outlines to outlines

 

pdfTextDemo.add(pdfTextDemo2);

com.elegantj.pdf.Outlines pdfFontDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Font Demo", pdfFontPage);

com.elegantj.pdf.Outlines pdfLineDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Line Demo", pdfLinePage);

com.elegantj.pdf.Outlines pdfRectangleDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Rectangle Demo", pdfRectanglePage);

com.elegantj.pdf.Outlines pdfCircleDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Circle Demo", pdfCirclePage);

com.elegantj.pdf.Outlines pdfOvalDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Oval Demo", pdfOvalPage);

com.elegantj.pdf.Outlines pdfArcDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Arc Demo", pdfArcPage);

com.elegantj.pdf.Outlines pdfPolygonDemo = new com.elegantj.pdf.Outlines(pdf, "PDFPolygonDemo", pdfPolygonPage);

com.elegantj.pdf.Outlines pdfPatternDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Pattern Demo", pdfPatternPage1);

com.elegantj.pdf.Outlines pdfPatternDemo1 = new com.elegantj.pdf.Outlines(pdf, "Pattern with Text", pdfPatternPage1);

com.elegantj.pdf.Outlines pdfPatternDemo2 = new com.elegantj.pdf.Outlines(pdf, "Pattern with Graphics", pdfPatternPage2);

 

// adds outlines to outlines

 

pdfPatternDemo.add(pdfPatternDemo1);

 

// adds outlines to outlines

 

pdfPatternDemo.add(pdfPatternDemo2);

com.elegantj.pdf.Outlines pdfAnnotationDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Annotations Demo", pdfAnnotationPage1);

com.elegantj.pdf.Outlines pdfAnnotationDemo1 = new com.elegantj.pdf.Outlines(pdf, "Rubber Stamp Annotation", pdfAnnotationPage1);

com.elegantj.pdf.Outlines pdfAnnotationDemo2 = new com.elegantj.pdf.Outlines(pdf, "Other Annotation", pdfAnnotationPage2);

 

// adds outlines to outlines

 

pdfAnnotationDemo.add(pdfAnnotationDemo1);

 

// adds outlines to outlines

 

pdfAnnotationDemo.add(pdfAnnotationDemo2);

com.elegantj.pdf.Outlines pdfImageDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Image Demo", pdfImagePage);

com.elegantj.pdf.Outlines pdfTableDemo = new com.elegantj.pdf.Outlines(pdf, "PDF Table Demo", pdfTablePage1);

com.elegantj.pdf.Outlines pdfTableDemo1 = new com.elegantj.pdf.Outlines(pdf, "PDF Table 1", pdfTablePage1);

com.elegantj.pdf.Outlines pdfTableDemo2 = new com.elegantj.pdf.Outlines(pdf, "PDF Table 2", pdfTablePage2);

com.elegantj.pdf.Outlines pdfTableDemo3 = new com.elegantj.pdf.Outlines(pdf, "PDF Table 3", pdfTablePage3);

pdfTableDemo.add(pdfTableDemo1);

pdfTableDemo.add(pdfTableDemo2);

pdfTableDemo.add(pdfTableDemo3);

 

// finally add outlines to base outline

 

baseOutline.add(pdfTextDemo);

baseOutline.add(pdfFontDemo);

baseOutline.add(pdfLineDemo);

baseOutline.add(pdfRectangleDemo);

baseOutline.add(pdfCircleDemo);

baseOutline.add(pdfOvalDemo);

baseOutline.add(pdfArcDemo);

baseOutline.add(pdfPolygonDemo);

baseOutline.add(pdfPatternDemo);

baseOutline.add(pdfAnnotationDemo);

baseOutline.add(pdfImageDemo);

baseOutline.add(pdfTableDemo);

 

 

6.1.25      Working with Document Meta Information

Ø       ElegantJ PDF Library provides full support for document meta information.

 

com.elegantj.pdf.PDF pdf = new com.elegantj.pdf.PDF();

com.elegantj.pdf.Info info = pdf.getInfo();

 

Ø       To set author name for PDF doc

 

info.setAuthor("Author");

 

Ø       To set creator name for PDF doc

 

info.setCreator("Creator");

 

Ø       To set the title for PDF doc

 

info.setTitle("Title");

 

Ø       To set subject for PDF doc

 

info.setSubject("Subject");

 

Ø       To set keywords for PDF doc

 

info.setKeywords("keyword1, keyword2, keyword3, keyword4, keyword5");

 

6.1.26      Writing PDF to output Stream

Ø       To write PDF to the output stream,

 

java.io.FileOutputStream fos = new java.io.FileOutputStream("c:\test.pdf");

pdf.write(fos);

 

Above code writes PDF document to test.pdf file.

 

 

6.1.27      The difference between CJKFont and TrueTypeCJKFont and when to use them

CJKFont provides the built in Chinese, Japanese and Korean CJK / type0 fonts.

 

The built in CJK fonts are listed below.

 

Font Name

Description

HEISEIKAKUGO_W5

The HeiseiIkakugo_W5 Japanese font 

HEISEIMIN_W3

The HeiseiMin_W3 Japanese font 

HYGOTHIC_MEDIUM

The HYGoThic_Medium Korean font 

HYSMYEONGJO_MEDIUM

The HYSMyeongJo_Medium Korean font 

HYSMYEONGJOSTD_MEDIUM

The HYSMyeongJoStd_Medium Korean font 

KOZMINPRO_REGULAR

The KozMinPro_Regular Japanese font 

MHEI_MEDIUM

The MHei_Medium Chinese font 

MSUNG_LIGHT

The MSung_Light Chinese font 

MSUNGSTD_LIGHT

The MSungStd_Light Chinese font 

STSONG_LIGHT

The STSONG_LIGHT Chinese font 

STSONGSTD_LIGHT

The STSongStd_Light Chinese font 

 

If you want to use one of the above listed fonts then you can use CJKFont in PDF.

 

PDF with CJKFont can not be generated with OS other then Chinease / Japanease / Korean, also Such files will only be displayed correctly on chinease / Japanease / Korean.

 

On other side,

 

TrueTypeCJKFont facilitates user to generate PDF on any language's OS, because of it embeds the true type CJK font in PDF itself, So, user can also view this PDF on machine with any language's OS.

 

6.1.28      Generating PDF dynamically from servlet

Ø       Sample code to generate the PDF from servlet is listed below.  Following code generates PDF with single page and contains single text "ElegantJ PDF Library".

 

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException

{

    ServletOutputStream out = null;

    PDF pdf = null;

    MediaBox mediaBox = MediaBox.MEDIA_a4;

    Page page = null;

    PDFText pdfText = null;

 

    try

    {

        response.setContentType("application/pdf");

        out = response.getOutputStream();

 

        // creating new pdf object, base class of pdf generator

        pdf = new PDF(Catalog.USEOUTLINES);

 

        // creates PDFPage

        page = new Page(pdf.getPages(), mediaBox);

 

        pdfText = new PDFText("ElegantJ PDF Library", 50, 25, mediaBox.width - 100, 80);

        pdfText.setFontSize(16);

        pdfText.setFillColor(FORE_COLOR);

        pdfText.setUnderLine(true);

        page.addText(pdfText);

 

        pdf.write(out);

        out.flush();

    }

    catch(Exception e)

    {

        e.printStackTrace();

    }

} 

 

6.1.29      Making PDFRectangle with rounded joins

Ø       To create the PDFRectangle with round joins, set join style to PDFRectangle.ROUND_JOINS.

 

Code given below is sample code for this.

 

import java.awt.*;

import java.io.*;

import com.elegantj.pdf.*;

 

// PDFRectDemo class is demo of PDFRectangle Object

public class PDFRectDemo

{

    // Default constructor

    public PDFRectDemo()

    {

        try

        {

            // creating file output stream

            FileOutputStream fos = new FileOutputStream("PDFRectDemo.pdf");

 

            // a mediabox to set size of the page, here is media A4

            MediaBox mediaBox = MediaBox.MEDIA_a4;

 

            // creating new pdf object, base class of pdf generator

            PDF pdf = new PDF();

 

            // creating page

            Page page = new Page(pdf.getPages(), mediaBox);

 

            // creating new PDFRectangle object

            PDFRectangle rect1 = new PDFRectangle(100, 100, 200, 100);

            rect1.setOutlineWidth(10);

 

            // ----- You can set ROUND JOIN using setJoinStyle method of PDFRectangle -----

            rect1.setJoinStyle(PDFGraphicsObject.ROUND_JOINS);

 

            // add rectangle to the page

            page.addGraphics(rect1);

 

            // call write method of pdf and pass output stream as an argument

            // here we pass fos as output stream

            pdf.write(fos);

            fos.close();

        }

        catch(Exception e)

        {

            e.printStackTrace();

        }

 

        // main method for this class

        public static void main(String args[])

        {

            // instantiating PDFRectDemo

            PDFRectDemo demo = new PDFRectDemo();

            System.exit(0);

        }

    }

}

 

6.1.30      Generating PDF directly from any java component

ElegantJ PDF provides the PDFGraphics object to generate PDF directly from any java component, using this PDFGraphics user can directly generate PDF from following components

 

Ø       From any java swing component

Ø       From any lightweight component

 

Ø       To generate PDF from swing JTable

 

// Following code snippet shows how to generate PDF directly from JTable

 

// First step - Creating JTable

 

javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel(); // creates table model

javax.swing.JTable table = new javax.swing.JTable(); // creates JTable

table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);

 

java.util.Vector columnNames = new java.util.Vector(); // creates the vector of column names // creates vector of column names

columnNames.addElement("Employee ID");

columnNames.addElement("First Name");

columnNames.addElement("Last Name");

columnNames.addElement("Address");

columnNames.addElement("Salary");

 

java.util.Vector data = new java.util.Vector(); // creates the vector to store data for the JTable // creates vector to store data for JTable

 

java.util.Vector rowData = new java.util.Vector(); // creates the new row data // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Fran");

rowData.addElement("Whitney");

rowData.addElement("49 East Washington Street-Needham-MA-Zip 02192");

rowData.addElement("$45700.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Matthew");

rowData.addElement("Cobb");

rowData.addElement("77 Pleasant Street-Waltham-MA-Zip 02154");

rowData.addElement("$62000.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Philip");

rowData.addElement("Chin");

rowData.addElement("59 Pond Street-Atlanta-GA-Zip 30339");

rowData.addElement("$38500.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Julie");

rowData.addElement("Jordan");

rowData.addElement("144 Great Plain Avenue-Winchester-MA-Zip 01890");

rowData.addElement("$51432.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Robert");

rowData.addElement("Breault");

rowData.addElement("58 Cherry Street-Milton-MA-Zip 02186");

rowData.addElement("$57490.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Melissa");

rowData.addElement("Espinoza");

rowData.addElement("112 Apple Tree Way-Stow-MA-Zip 01775");

rowData.addElement("$36490.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Jeannett");

rowData.addElement("Bertrand");

rowData.addElement("209 Concord Street-Acton-MA-Zip 01720");

rowData.addElement("$32780.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Marc");

rowData.addElement("Dill");

rowData.addElement("89 Hancock Street-Milton-MA-Zip 02186");

rowData.addElement("$54800.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Jane");

rowData.addElement("Francis");

rowData.addElement("12 Hawthorne Drive-Concord-MA-Zip 01742");

rowData.addElement("$53870.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Natasha");

rowData.addElement("Shishov");

rowData.addElement("15 Milk Street-Waltham-MA-Zip 02154");

rowData.addElement("$72995.000");

data.addElement(rowData); // adds the row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Kurt");

rowData.addElement("Driscoll");

rowData.addElement("154 School Street-Waltham-MA-Zip 02154");

rowData.addElement("$48023.690");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Rodrigo");

rowData.addElement("Guevara");

rowData.addElement("East Main Street-Framingham-MA-Zip 01701");

rowData.addElement("$42998.000");

data.addElement(rowData); // adds row to data vector

 

rowData = new Vector(); // creates new row data

rowData.addElement("emp-00000" + data.size() + 1);

rowData.addElement("Ram");

rowData.addElement("Gowda");

rowData.addElement("79 Page Street-Natick-MA-Zip 01760");

rowData.addElement("$59840.000");

data.addElement(rowData); // adds row to data vector

 

model.setDataVector(data, columnNames); // sets data and column names for JTable

 

table.getColumn(table.getColumnName(0)).setPreferredWidth(105); // sets the preferred width for column

table.getColumn(table.getColumnName(1)).setPreferredWidth(80); // sets the preferred width for column

table.getColumn(table.getColumnName(2)).setPreferredWidth(80); // sets the preferred width for column

table.getColumn(table.getColumnName(3)).setPreferredWidth(304); // sets the preferred width for column

table.getColumn(table.getColumnName(4)).setPreferredWidth(90); // sets the preferred width for column

 

// Second step - generating PDF from JTable

 

PDF pdf = new PDF(); // creates the PDF

 

int tableWidth = table.getSize().width;

int tableWidth = table.getSize().width; // gets table width

int tableHeight = table.getSize().height; // gets table height

int pageHeight = MediaBox.MEDIA_a4.getHeight(); // assign height of a4 size as page height

 

MediaBox mediaBox = new MediaBox(-10, 10, tableWidth + 20, pageHeight + 20); // creates the media box

PDFGraphics pdfGraphics = new PDFGraphics(pdf, mediaBox); // creates the PDFGraphics with specified pdf and media box

 

int noOfPages = (int)Math.ceil(tableHeight * 1.0 / pageHeight); // counts the no. of pages will be generated

 

boolean wasDoubleBuffered = false

if(table.isDoubleBuffered()) // if double buffered is on it turns it to off, to get fast printing of pdf

{

  wasDoubleBuffered = true;

  table.setDoubleBuffered(false);

} // creates media box

PDFGraphics pdfGraphics = new PDFGraphics(pdf, mediaBox); // creates PDFGraphics with specified pdf and media box

 

int noOfPages = (int)Math.ceil(tableHeight * 1.0 / pageHeight); // counts the number of pages that will be generated

 

boolean wasDoubleBuffered = false

if(table.isDoubleBuffered()) // if double buffered is on, it turns it off to get fast printing of pdf

{

  wasDoubleBuffered = true;

  table.setDoubleBuffered(false);

}

 

for(int i = 0; i < noOfPages; i++) // iterate through the noOfPages

{

  y = i * pageHeight;

 

  pdfGraphics.createPage(); // creates the page

 

  if(header != null && i == 0)  // prints header of JTable

  {

    pdfGraphics.translate(-x, -y); // translate the graphics

    header.printAll(pdfGraphics);

    pdfGraphics.translate(x, y);  // translate graphics to original position

    pdfGraphics.translate(0, header.getSize().height); // translate graphics to ignore header of JTable

  }

  pdfGraphics.translate(-x, -y);

  pdfGraphics.translate(-x, -y); // translate graphics

  table.printAll(pdfGraphics); // prints JTable

  pdfGraphics.translate(x, y); // translate graphics to original position

}

 

if(wasDoubleBuffered) // turn on the double buffering if previoously component had double buffering on

  table.setDoubleBuffered(true); // turn on double buffering if previous component had double buffering on

  table.setDoubleBuffered(true);

 

try

{

  FileOutputStream out = new FileOutputStream("demo_pdf_graphics.pdf"); // creates pdf file

  pdf.write(out); // writes pdf to file

  out.close(); // closes the stream

  out = null;

}

catch(Exception ex)

{

  ex.printStackTrace();

}

pdfGraphics.dispose();

catch(Exception ex)

{

  ex.printStackTrace();

}

pdfGraphics.dispose(); // disposes the PDFGraphics

pdfGraphics = null;

 

Similarly, you can generate PDF directly from any java swing component or any lightweight component.