Removing PDF attachments via itext

Posted by r00fus on Stack Overflow See other posts from Stack Overflow or by r00fus
Published on 2010-05-10T21:18:19Z Indexed on 2010/05/10 21:24 UTC
Read the original article Hit count: 351

Filed under:
|
|
|

I'm trying to remove attachments from a number of my pdf files (I can extract via pdftk, so preserving them is not an issue).

I coded the following based on an example found from a google search:

    import java.io.FileOutputStream;
    import java.io.IOException;
    import com.lowagie.text.*;
    import com.lowagie.text.pdf.*;

    class pdfremoveattachment {

    public static void main(String[] args) throws IOException, DocumentException {
        if (args.length < 2) {
            System.out.println("Usage: java PDFremoveAttachments source.pdf target.pdf"); 
            System.exit(1);
        }
        PdfReader sourcePDF = new PdfReader(args[0]);
        removeAttachments(sourcePDF);   
        FileOutputStream targetFOS = new FileOutputStream(args[1]);
        PdfStamper targetPDF = new PdfStamper(sourcePDF,targetFOS);
        targetPDF.close();
    }

    public static void removeAttachments(PdfReader reader) {  
            PdfDictionary catalog = reader.getCatalog();
//      System.out.println(catalog.getAsDict(PdfName.NAME)); // this would print "null"
        PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
//      System.out.println(names.toString());    //this returns NPE
            if( names != null)   {

      PdfDictionary files = (PdfDictionary) PdfReader.getPdfObject(names.get(PdfName.FILEATTACHMENT));  
                    if( files!= null ){  
                            for( Object key : files.getKeys() ){
              files.remove((PdfName)key);        
                            }
      files = (PdfDictionary) PdfReader.getPdfObject(names.get(PdfName.EMBEDDEDFILES));
            }   
                    if( files!= null ){
                            for( Object key : files.getKeys() ){
              files.remove((PdfName)key);
                            }

            reader.removeUnusedObjects();
                }  
            }
      } 
    }

If anyone knows how I might be able to remove attachments, I'd greatly appreciate a reply.

© Stack Overflow or respective owner

Related posts about itext

Related posts about java