Using iText on the new SourceBeat.com Website
I saw a blog the other day about using iText to manipulate PDFs. I have really wanted to take a look at iText, but just have not had the chance. So thanks to this blog, I finally took the time to look at it and really liked it. After checking out the related article, it took me all of 30 minutes to learn iText and replace SourceBeat?s current PDF encryption code (originally pdftk). It was too easy. Below is an example and unit test showing how SourceBeat is now using iText.
package com.sourcebeat.util;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
public class EncryptorTest extends TestCase {
protected final Log log = LogFactory.getLog(getClass());
protected Encryptor encryptor;
protected String unencryptedFile = "test/unencrypted.pdf";
protected String encryptedFile = "test/encrypted.pdf";
public void setUp() throws Exception {
encryptor = new Encryptor();
}
public void tearDown() throws Exception {
encryptor = null;
}
public void testEncrypt() throws Exception {
// Encrypt the file
encryptor.encrypt(unencryptedFile, encryptedFile, "userPass", "ownerPass");
// Make sure that the file was written
File newFile = new File(encryptedFile);
assertTrue(newFile.canRead());
// remove the file
newFile.delete();
}
}
It is pretty simple. As you can see Encryptor.encrypt() method takes the path to the original unencrypted file, the path to the output (the new encrypted file), and the user and owner passwords. You can see this method below:
package com.sourcebeat.util;
import com.lowagie.text.pdf.PdfEncryptor;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class Encryptor {
public void encrypt(String inputFile,
String outputFile,
String userPassword,
String ownerPassword) throws Exception {
PdfReader reader = new PdfReader(inputFile);
PdfEncryptor.encrypt(reader,
new FileOutputStream(outputFile),
false,
userPassword,
ownerPassword,
PdfWriter.AllowAssembly
| PdfWriter.AllowDegradedPrinting
| PdfWriter.AllowFillIn
| PdfWriter.AllowModifyAnnotations
| PdfWriter.AllowPrinting
| PdfWriter.AllowScreenReaders);
}
}
Easy enough?you first have to create a PdfReader using the passed in input file path and then invoke the PdfEncryptor.encrypt() method. The parameters passed to this method are relatively self-explanatory, with the exception of the third parameter, false. The third parameter is a boolean, which represents the encryption strength (true for 128 bit key length, false for 40 bit key length). That is it. It is now part of the, soon to be released, new SourceBeat.com site.
I hope to take enough time to test this and perhaps it could be invaluable in my near future Java projects.
No comments:
Post a Comment