Monday, May 16, 2011

Hide the PDF properties Using iText

Requried jar files: bcprov-jdk15-140.jar, and itext-2.1.2.jar
Source code:

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfDestination;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
public class HidePdfProperties {
/**
* @param args
*/
public static void main( String[] args ) {
// TODO Auto-generated method stub
hidePdfProperties( "D:\\Ganga\\ganga_Test_New.pdf" );
}
/**
* To restrict the PDF properties
*
* @return response OutputStream
*/
public static void hidePdfProperties( String aFileName ) {
PdfReader reader;
Document document = null;
try {
reader = new PdfReader( aFileName );
// Already Encrypted
if ( reader.isEncrypted() ) {
reader = new PdfReader( aFileName, "test".getBytes() );
}
int totalPages = reader.getNumberOfPages();
document = new Document( reader.getPageSizeWithRotation( 1 ) );
PdfCopy copy =
new PdfCopy( document, new FileOutputStream(
"D:\\Ganga\\ganga_Test_Ency.pdf" ) );
// Hide the PDF properties
copy.setViewerPreferences( PdfWriter.HideMenubar );
copy.setViewerPreferences( PdfWriter.HideToolbar );
// test is the password for encrypt the file
// Using the same name we can UNENCRYPT the file
// if the file is encrypted then only print button own be displayed
// in right option
copy.setEncryption( null, "test".getBytes(),
PdfWriter.ALLOW_MODIFY_CONTENTS, PdfWriter.ENCRYPTION_AES_128 );
PdfAction action = null;
document.open();
for ( int pageNumber = 1; pageNumber <= totalPages; pageNumber++ ) {
copy.addPage( copy.getImportedPage( reader, pageNumber ) );
}
// Resize the page
action =
PdfAction.gotoLocalPage( 1, new PdfDestination(
PdfDestination.XYZ, 0, 10000, 0.70f ), copy );
copy.setOpenAction( action );
document.close();
} catch ( IOException anIOException ) {
anIOException.printStackTrace();
} catch ( DocumentException aDocumentException ) {
aDocumentException.printStackTrace();
} finally {
try {
if ( document != null && document.isOpen() ) {
document.close();
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
}

No comments:

Post a Comment