Crionics LOGO

TUTORIALS

 

 How to use Creator: The basics

As easy as 1, 2, 3...

 

Create the document

In this tutorial we will explain the basics of creating a PDF document using jPDF Creator.
First, we need a PDF document to work with:

PdfDocument doc = new PdfDocument();

Note that we could have specified some attributes for the new document - such as the default page size, a password and/or the PDF revision - to use for the generation.

Now we need a page to draw on, and, along the page, we also need its page size. The Java API defines the page size in an object called PageFormat which describes the size of the paper and the imageable area of the page in which the application will draw.

// Append a page in the document:
Page page=Page.createInstance(doc);

// Get the page format:
PageFormat pf=page.getPageFormat();
int page_x=(int)pf.getWidth();
int page_y=(int)pf.getHeight();

 

Draw on the page

Now that we have the page and its dimensions, let's draw some graphical primitives on it.

// Recover the Graphics2D of the page:
Graphics2D g2d=page.getGraphics();

// Draw a green-filled elipse on the page:
g2d.setColor(Color.green);
g2d.fillOval(0,0,page_x,page_y);

// Draw a rectangle in black:
g2d.setColor(Color.black);
g2d.drawRect(0+10,0+40,page_x-20,page_y-100);

// Draw a blue diagonal line with an 8 pixels-width pencil:
g2d.setColor(Color.blue);
g2d.setStroke(new BasicStroke(8));
g2d.drawLine(0,0,page_x,page_y);

// Draw some text filled with a gradient fill:
g2d.setPaint(new GradientPaint(0,0,Color.black, page_x,page_y,Color.white));
g2d.setFont(new Font("Sans", Font.BOLD, 100));
g2d.drawString("Hello world..",15, page_y/2);

// Important: DO NOT forget to dispose() :
g2d.dispose();

jPDF Creator supports all Java2D methods including complex fills (gradients, patterns) and transparency.
There are many Java2D books available on the market today. Online resources (such as this tutorial) are also thorough and very helpful.

 

Save the document and run the application

Final step? Save the document to a file and close it in order to release memory.

doc.saveAs("SimpleJava2DDemo.pdf");
doc.close();

The full source code of this tutorial is part of the distribution.
Please click on this link to display the generated PDF.


© 2000-2007 Crionics Inc. Report issues with this page