1 31 package org.pdfbox.examples.pdmodel; 32 33 import java.io.IOException ; 34 import java.util.List ; 35 36 import org.pdfbox.exceptions.COSVisitorException; 37 38 import org.pdfbox.pdmodel.PDDocument; 39 import org.pdfbox.pdmodel.PDPage; 40 41 import org.pdfbox.pdmodel.common.PDRectangle; 42 import org.pdfbox.pdmodel.edit.PDPageContentStream; 43 44 import org.pdfbox.pdmodel.font.PDFont; 45 import org.pdfbox.pdmodel.font.PDType1Font; 46 47 48 55 public class AddMessageToEachPage 56 { 57 60 public AddMessageToEachPage() 61 { 62 super(); 63 } 64 65 75 public void doIt( String file, String message, String outfile ) throws IOException , COSVisitorException 76 { 77 PDDocument doc = null; 79 try 80 { 81 doc = PDDocument.load( file ); 82 83 List allPages = doc.getDocumentCatalog().getAllPages(); 84 PDFont font = PDType1Font.HELVETICA_BOLD; 85 float fontSize = 12.0f; 86 87 for( int i=0; i<allPages.size(); i++ ) 88 { 89 PDPage page = (PDPage)allPages.get( i ); 90 PDRectangle pageSize = page.findMediaBox(); 91 float stringWidth = font.getStringWidth( message ); 92 float centeredPosition = (pageSize.getWidth() - (stringWidth*fontSize)/1000f)/2f; 93 PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true); 94 contentStream.beginText(); 95 contentStream.setFont( font, fontSize ); 96 contentStream.moveTextPositionByAmount( centeredPosition, 30 ); 97 contentStream.drawString( message ); 98 contentStream.endText(); 99 contentStream.close(); 100 } 101 102 103 doc.save( outfile ); 104 } 105 finally 106 { 107 if( doc != null ) 108 { 109 doc.close(); 110 } 111 } 112 } 113 114 121 public static void main(String [] args) 122 { 123 AddMessageToEachPage app = new AddMessageToEachPage(); 124 try 125 { 126 if( args.length != 3 ) 127 { 128 app.usage(); 129 } 130 else 131 { 132 app.doIt( args[0], args[1], args[2] ); 133 } 134 } 135 catch (Exception e) 136 { 137 e.printStackTrace(); 138 } 139 } 140 141 144 private void usage() 145 { 146 System.err.println( "usage: " + this.getClass().getName() + " <input-file> <Message> <output-file>" ); 147 } 148 } | Popular Tags |