Is production: true
#migrated

Add password to PDF using pdfbox

Created: 19 Mar 2023 Modified: 19 Mar 2023 Lang: English



[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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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]