Is production: true
#migrated

Title: Add password to PDF using pdfbox

Created: 19 Mar 2023 Modified: 19 Mar 2023

Description:



[deen-pdf]

Tool in jvm achieve the add password and remove password

[Example using java]

By following the java example, the the pdf is added password.

I rewrote the code in scala.

object EncryptPwd{
  import java.io.File
  import org.apache.pdfbox.pdmodel.PDDocument
  import org.apache.pdfbox.pdmodel.encryption.{AccessPermission, StandardProtectionPolicy}
  def main(args: Array[String]): Unit = {
    val pathOfPdf = {
      val f = new File(args(0))
      if(f.exists() && f.isFile)
        f
      else throw new RuntimeException(s"PDF File[${args(0)}] not exits or not a file")
    }
    val pathOfEncryptedPdf = {
      val f = new File(args(1))
      if(f.exists())
        throw new RuntimeException(s"Encrypted PDF[${args(1)}] is already exists")
      else f
    }
    val ownerPassword = args(2)
    val userPassword = args(3)
    
    val doc = PDDocument.load(pathOfPdf)
    val ap = new AccessPermission()
    val spp = new StandardProtectionPolicy(ownerPassword,userPassword, ap)
    spp.setEncryptionKeyLength(256)
    spp.setPermissions(ap)
    doc.protect(spp)

    doc.save(pathOfEncryptedPdf)
    doc.close()
  }
}

[Legacy Link]