torsdag 17 oktober 2013

Stamp a pdf with it's file name.

Need to stamp  a pdf file with it's filename? Here you go:
Usage:
pdfstamper
usage: pdfstamper
 -d,--directory <input folder>   All pdf's in this folder will be
                                 processed
 -i,--input <input file>         This file will be processed
 -x,--xoffset <x offset>         The horizontal offset from the rightmost
                                 part of the page
 -y,--yoffset <y offset>         The vertical offset from the top of the
                                 page

Eclipse project:
Download File
excutable jar:
Download File
runnable unix cmd:
Download File

Source:
import java.io.File;
import java.io.FileFilter;
import java.util.List;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class PDFStamper {

    /**
     * @param args the command line arguments
     */
    public static final FileFilter pdfFileFilter = new FileFilter() {

        public boolean accept(File file) {
            return file.isFile() && file.getName().toLowerCase().endsWith(".pdf");
        }
    };

    public static void closeQuietly(PDDocument doc) {
        if (doc != null) {
            try {
                doc.close();
            } catch (Exception exception) {
                //do something here if you wish like logging 
            }
        }
    }

    public static void checkPages(File[] sourcePdfFiles, String prefix, int offsetX, int offsetY) {

        for (File sourcePdfFile : sourcePdfFiles) {
            stampFile(sourcePdfFile.getName(), prefix, offsetX, offsetY, sourcePdfFile);
        }
    }

  private static void stampFile(String textToInsert, String prefix,
   int offsetX, int offsetY, File sourcePdfFile) {
  PDFont font = PDType1Font.HELVETICA_BOLD;
  float fontSize = 12.0f;
  PDDocument pdoc = null;
  try {

       pdoc = PDDocument.load(sourcePdfFile);
      List allPages = pdoc.getDocumentCatalog().getAllPages();
      for(PDPage page : allPages)
      {
       PDRectangle pageSize = page.findMediaBox();
          float stringWidth = font.getStringWidth(textToInsert);
          float centeredPosition = (pageSize.getWidth() - (stringWidth * fontSize) / 1000f) / 2f;
          float right = (pageSize.getWidth() - (stringWidth * fontSize) / 1000f-offsetX);
          float top = (pageSize.getHeight()-offsetY);

           PDPageContentStream contentStream = new PDPageContentStream(pdoc, page, true, true);
          contentStream.beginText();
          contentStream.setFont(font, fontSize);
          contentStream.moveTextPositionByAmount(right, top);
          contentStream.drawString(textToInsert);
          contentStream.endText();
          contentStream.close();
      }
      
      File resultFile = new File(sourcePdfFile.getParentFile(), prefix + sourcePdfFile.getName());
      pdoc.save(resultFile.getAbsolutePath());


   } catch (Exception e) {
      System.err.println("An exception occured in parsing the PDF Document." + e.getMessage());
  } finally {
      closeQuietly(pdoc);
  }
 }

    public static void main(String[] args) {
     int offsetX=20;
     int offsetY=20;
      String modifiedFilePrefix = "modified-";
     Options options = new Options();
     Option inputFolder = OptionBuilder.hasArgs(1).withArgName("input folder")
          .withDescription("All pdf's in this folder will be processed").isRequired(false)
          .withLongOpt("directory").create("d");
     Option inputFile = OptionBuilder.hasArgs(1).withArgName("input file")
          .withDescription("This file will be processed").isRequired(false)
          .withLongOpt("input").create("i");
     Option offsetXOpt = OptionBuilder.hasArgs(1).withArgName("x offset")
          .withDescription("The horizontal offset from the rightmost part of the page").isRequired(false)
          .withLongOpt("xoffset").create("x");  
     Option offsetYOpt = OptionBuilder.hasArgs(1).withArgName("y offset")
          .withDescription("The vertical offset from the top of the page").isRequired(false)
          .withLongOpt("yoffset").create("y");  
   
     options.addOption(inputFolder);
     options.addOption(inputFile);
     options.addOption(offsetXOpt);
     options.addOption(offsetYOpt);
     
     CommandLineParser parser = new BasicParser();
       try {
   CommandLine line = parser.parse(options, args);
   if(line.hasOption("offsetX"))
   {
    offsetX=Integer.parseInt(line.getOptionValue("offsetX"));
   }
   if(line.hasOption("offsetY"))
   {
    offsetY=Integer.parseInt(line.getOptionValue("offsetY"));

    }
   if(line.hasOption("input"))
   {
    File pdfFile = new File(line.getOptionValue("input"));
          stampFile(pdfFile.getName(), modifiedFilePrefix, offsetX, offsetY, pdfFile);
    
   }
   if(line.hasOption("directory"))
   {
    File pdfFilesFolder = new File(line.getOptionValue("directory"));
          File[] pdfFiles = pdfFilesFolder.listFiles(pdfFileFilter);
          checkPages(pdfFiles,modifiedFilePrefix,offsetX,offsetY);
   }
   if(line.getOptions().length==0)
   {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp( "pdfstamper", options );
   }
  } catch (ParseException e) {
   HelpFormatter formatter = new HelpFormatter();
   formatter.printHelp( "pdfstamper", options );
  
  } // args are the arguments passed to the  the application via the main method

     
        
        //when a file is processed, the result will be saved in a new file having the location of the source file 
        //and the same name of source file prefixed with this
       
        
    }
}