'How to password protect a existing pdf file using java8 & iText?
I am using the spring boot project to implement my code with the following dependencies :
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.69</version>
</dependency>
I have written the following code, and I can make my pdf file password protected, but the code will produce an additional file**[protectedOutput.pdf]** to make that happen. I want my existing pdf to only be made password protected without using a new pdf at a specific path.
Code is as follows :
package com.example.encryptMyPdf;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EncryptMyPdfApplication{
public static void main(String[] args) throws FileNotFoundException, DocumentException, IOException {
PdfReader reader = new PdfReader("/Users/ayushg/desktop/protected.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/Users/ayushg/desktop/protectedOutput.pdf"));
stamper.setEncryption("password".getBytes(), "owner_password".getBytes(),PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_256);
stamper.close();
reader.close();
System.out.println("pdf is password protected now ");
SpringApplication.run(EncryptMyPdfApplication.class, args);
}
}
Any suggestions on the same are very much welcomed. Thanks in advance!
Solution 1:[1]
When manipulating a PDF using a PdfReader/PdfStamper pair, the reader still needs the original PDF to read from while the stamper already stores new data to its output. Thus, they cannot both directly work on the same file system file.
So if you want the result to end up in the same file system file as the source and don't want to create temporary files in the file system either, you'll have to temporarily store input or output elsewhere, e.g. in memory.
For example, to use an in-memory copy of the source file:
java.io.File file = new java.io.File("...");
byte[] bytes = java.nio.file.Files.readAllBytes(file.toPath());
PdfReader reader = new PdfReader(bytes);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(file));
...
stamper.close();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mkl |
