iText5 如何制作受密码保护的 PDF 流

iText5 how to make password protected PDF Stream

这是我的代码:

public class PasswordToPDF {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
            PdfReader pdfReader = new PdfReader("C:/Users/XXXX/Desktop/CPIPDF.pdf");
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("C:/Users/XXXX/Desktop/test.pdf"));
            pdfStamper.setEncryption("abc".getBytes(), "abc".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
            pdfStamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

它适用于文件系统中的文档,但我如何将其转换为适用于 PDF 流?

不幸的是,没有为数据流的读写创建密码保护。我想 return 将 PDF 作为受密码保护的数据流。这可能吗?

        try {
            
            
            String pdfFileOutputPath = "C:/Users/XXXX/Desktop/test.pdf";
            String pdfFileInputPath = "C:/Users/XXXX/Desktop/CPIPDF.pdf";
            
            InputStream in = new FileInputStream(pdfFileInputPath);
           
            
            OutputStream fos = new FileOutputStream(new File(pdfFileOutputPath));
            
            in.transferTo(fos);
            
            
            Document document = new Document();
            
            PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
            

            String userPassword = "a";
            String ownerPassword = "b";

            pdfWriter.setEncryption(userPassword.getBytes(),
                         ownerPassword.getBytes(), PdfWriter.AllowPrinting,
                         PdfWriter.ENCRYPTION_AES_128);

            //document.open();
           
            //document.add(new Paragraph("This is Password protected PDF file"));

            //document.close();
            
            in.close();
            fos.close();

            System.out.println("PDF created in >> " + pdfFileOutputPath);

     } catch (Throwable e) {
            e.printStackTrace();
     }
public class PasswordToPDF {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
            
    
            byte[] bytesDecoded;
            
            String pdfFileInputPath = "C:/Users/XXXX/Desktop/CPIPDF.pdf";
            
            InputStream in = new FileInputStream(pdfFileInputPath);
            bytesDecoded = in.readAllBytes();
            
            ByteArrayInputStream inStream = new ByteArrayInputStream(bytesDecoded);
            PdfReader pdfReader = new PdfReader(inStream);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("C:/Users/XXXXX/Desktop/test.pdf"));
            pdfStamper.setEncryption("abc".getBytes(), "abc".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
            pdfStamper.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

有效!