使用谷歌“java openpdf 密码示例”我找到了这个网站:https ://knpcode.com/java-programs/password-protected-pdf-using-openpdf-java/以及有关您的问题的一些信息。
这是两个示例程序(只是复制/粘贴它们,而不是测试)。不要忘记将Bouncy Castle作为安全提供者。
加密(“安全”)PDF:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class PasswordProtectedPDF {
public static final String ENCRYPTED_PDF = "F://knpcode//result//OpenPDF//PP.pdf";
// User and owner password
final static String USER_PASSWORD = "user";
final static String OWNER_PASSWORD = "owner";
public static void main(String[] args) {
try {
Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(ENCRYPTED_PDF));
// set password, user permissions and encryption
writer.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
doc.open();
Paragraph para = new Paragraph("Password protected PDF where only content printing is permitted content can't be copied.");
doc.add(para);
doc.close();
writer.close();
} catch (DocumentException | FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用 OpenPDF 阅读受密码保护的 PDF:
import java.io.IOException;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.parser.PdfTextExtractor;
public class ReadPDF {
// PDF to be read
public static final String READ_PDF = "F://knpcode//result//OpenPDF//PP.pdf";
final static String OWNER_PASSWORD = "owner";
public static void main(String[] args) {
PdfReader pdfreader = null;
try {
pdfreader = new PdfReader(READ_PDF, OWNER_PASSWORD.getBytes());
// get pages in PDF
int pages = pdfreader.getNumberOfPages();
PdfTextExtractor pdfTextExtractor = new PdfTextExtractor(pdfreader);
// Iterate through pages to read content
for(int i = 1; i <= pages; i++) {
// Extract content of each page
String contentOfPage = pdfTextExtractor.getTextFromPage(i, true);
System.out.println(contentOfPage );
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(pdfreader != null) {
pdfreader.close();
}
}
}
}