package it.stefanochizzolini.clown.samples; import it.stefanochizzolini.clown.documents.Document; import it.stefanochizzolini.clown.documents.Page; import it.stefanochizzolini.clown.documents.contents.colorSpaces.DeviceRGBColor; import it.stefanochizzolini.clown.documents.contents.composition.AlignmentXEnum; import it.stefanochizzolini.clown.documents.contents.composition.AlignmentYEnum; import it.stefanochizzolini.clown.documents.contents.composition.PrimitiveFilter; import it.stefanochizzolini.clown.documents.contents.fonts.StandardType1Font; import it.stefanochizzolini.clown.files.File; import it.stefanochizzolini.clown.tools.PageStamper; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; /** This sample demonstrates how to stamp the page number on alternated corners of an existing document's pages.

Remarks

Stamping is just one of the several ways PDF contents can be manipulated using PDF Clown: contents can be inserted as (raw) data chunks, mid-level content objects, external forms, etc.

@author Stefano Chizzolini (http://www.stefanochizzolini.it) @version 0.0.6 */ public class PageNumberingSample implements ISample { public void run( PDFClownSampleLoader loader ) { // 1. Opening the PDF file... File file; { // (boilerplate user choice -- ignore it) String filePath = loader.getPdfFileChoice("Please select a PDF file"); try{file = new File(filePath);} catch(Exception e){throw new RuntimeException(filePath + " file access error.",e);} } Document document = file.getDocument(); // 2. Stamp the document! stamp(document); // (boilerplate metadata insertion -- ignore it) loader.buildAccessories(document,this.getClass(),"Page numbering","numbering a document's pages"); // 3. Serialize the PDF file (again, boilerplate code -- see the PDFClownSampleLoader class source code)! loader.serialize(file,this.getClass().getSimpleName()); } private void stamp( Document document ) { // 1. Instantiate the stamper! /* NOTE: The PageStamper is optimized for dealing with pages. */ PageStamper stamper = new PageStamper(); // 2. Numbering each page... StandardType1Font font = new StandardType1Font( document, StandardType1Font.FamilyNameEnum.Courier, true, false ); DeviceRGBColor redColor = new DeviceRGBColor(1, 0, 0); int margin = 32; for(Page page : document.getPages()) { // 2.1. Associate the page to the stamper! stamper.setPage(page); // 2.2. Stamping the page number on the foreground... { PrimitiveFilter foreground = stamper.getForeground(); foreground.setFont(font,16); foreground.setFillColor(redColor); Dimension2D pageSize = page.getSize(); int pageNumber = page.getIndex() + 1; boolean pageIsEven = (pageNumber % 2 == 0); foreground.showText( Integer.toString(pageNumber), new Point2D.Double( (pageIsEven ? margin : pageSize.getWidth() - margin), pageSize.getHeight() - margin ), (pageIsEven ? AlignmentXEnum.Left : AlignmentXEnum.Right), AlignmentYEnum.Bottom, 0 ); } // 2.3. End the stamping! stamper.flush(); } } }