Skip to content

Instantly share code, notes, and snippets.

@akihiro4chawon
Created March 26, 2011 05:22
Show Gist options
  • Save akihiro4chawon/888044 to your computer and use it in GitHub Desktop.
Save akihiro4chawon/888044 to your computer and use it in GitHub Desktop.
PDF のパスワードを解除。(注意:印刷「許可しない」フラグなどが外れてしまいます)
import java.io.FileOutputStream
import com.itextpdf.text.DocWriter
import com.itextpdf.text.pdf.{PdfStamper, PdfReader}
object FreePdf {
val usage = """
|FreePdf [-password password] input-pdf-file output-pdf-file
| Option:
| -password password: Owner(Master) password of the file
""".stripMargin
def getOptions(opts: Map[String, String], xs: List[String]) : Map[String, String] = xs match {
case "-password" :: password :: tail => getOptions(opts + ("password" -> password), tail)
case Nil => throw new Exception("infile/outfile not specified")
case infile :: Nil => throw new Exception("outfile not specified")
case infile :: outfile :: Nil => opts + ("infile" -> infile) + ("outfile" -> outfile)
case infile :: outfile :: extra => throw new Exception("unknown command line argument:" + extra.mkString(" "))
}
def main(args: Array[String]) {
val opts: Map[String, String] =
try {
getOptions(Map(), args.toList)
} catch {
case e: Exception => {
println(usage)
println(e.getMessage)
exit(-1)
}
}
val password = opts.getOrElse("password", "")
val encryptedFileName = opts("infile")
val decryptedFileName = opts("outfile")
val reader = new PdfReader(encryptedFileName, DocWriter.getISOBytes(password));
val stamper = new PdfStamper(reader, new FileOutputStream(decryptedFileName));
stamper.close
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment