public void doIt(String[] args) throws IOException {
if( args.length != 3 )
{
usage();
}
else
{
PDDocument document = null;
try
{
document = PDDocument.load( args[0] );
if( document.isEncrypted() )
{
throw new IOException( "Encrypted documents are not supported for this example" );
}
List allpages = new ArrayList();
document.getDocumentCatalog().getPages().getAllKids(allpages);
int numberOfPages = allpages.size();
for (int i=0; i < numberOfPages; i++)
{
PDPage apage = (PDPage) allpages.get(i);
List annotations = apage.getAnnotations();
PDAnnotationRubberStamp rubberStamp = new PDAnnotationRubberStamp();
rubberStamp.setName(PDAnnotationRubberStamp.NAME_TOP_SECRET);
rubberStamp.setRectangle(new PDRectangle(100,100));
rubberStamp.setContents("A top secret note");
// Create a PDXObjectImage with the given jpg
FileInputStream fin = new FileInputStream( args[2] );
PDJpeg mypic = new PDJpeg(document,fin);
//Define and set the target rectangle
PDRectangle myrect = new PDRectangle();
myrect.setUpperRightX(275);
myrect.setUpperRightY(575);
myrect.setLowerLeftX(250);
myrect.setLowerLeftY(550);
// Create a PDXObjectForm
PDStream formstream = new PDStream(document);
OutputStream os = formstream.createOutputStream();
PDXObjectForm form = new PDXObjectForm(formstream);
form.setResources(new PDResources());
form.setBBox(myrect);
form.setFormType(1);
// adjust the image to the target rectangle and add it to the stream
drawXObject(mypic, form.getResources(), os, 250, 550, 25, 25);
os.close();
PDAppearanceStream myDic = new PDAppearanceStream(form.getCOSStream());
PDAppearanceDictionary appearance = new PDAppearanceDictionary(new COSDictionary());
appearance.setNormalAppearance(myDic);
rubberStamp.setAppearance(appearance);
rubberStamp.setRectangle(myrect);
//Add the new RubberStamp to the document
annotations.add(rubberStamp);
}
document.save( args[1] );
}
catch(COSVisitorException exception)
{
System.err.println("An error occured during saving the document.");
System.err.println("Exception:"+exception);
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
Add a rubber stamp with an jpg image to every page of the given document. |