pdfbox签名和保护,无需保存在文件系统中

时间:2019-04-15 11:31:54

标签: java encryption pdfbox signature

在生成和保护pdf之后,pdfbox是否支持在运行时签名。目前,我已经成功地从文件系统加载并完成了此任务。

我正在尝试对受保护的pdf进行签名,并返回生成的doc而没有再次保存它,因此在整个过程中都没有pdf保存机制。

public byte[] attachPdf(){
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PDDocument doc = sign(generatedPdf());//generated pdf
    doc.save(byteArrayOutputStream);
    response = new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
    doc.close();
}


public PDDocument sign(PDDocument doc1){
        //FileOutputStream fos = new FileOutputStream(signFile);
        //PDDocument doc = PDDocument.load(inputFile, "*******");
        //doc.setAllSecurityToBeRemoved(true);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        doc1.save(byteArrayOutputStream);
        PDDocument doc = PDDocument.load(byteArrayOutputStream.toByteArray());
        int accessPermissions = SigUtils.getMDPPermission(doc);

        PDSignature signature = null;
        PDRectangle rect = null;

        if (signature == null)
        {
            // create signature dictionary
            signature = new PDSignature();
        }

        if (rect == null)
        {
            rect = createSignatureRectangle(doc, humanRect);
        }
        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
        signature.setName("test");
        signature.setLocation("testL");
        signature.setReason("testR");
        signature.setSignDate(Calendar.getInstance());
        SignatureInterface signatureInterface = isExternalSigning() ? null : this;
        signatureOptions = new SignatureOptions();
        signatureOptions.setVisualSignature(createVisualSignatureTemplate(doc, doc.getNumberOfPages()-1, rect, signature));
        signatureOptions.setPage(doc.getNumberOfPages()-1);
        doc.addSignature(signature, signatureInterface, signatureOptions);
        //doc.save(baos);
        //doc.saveIncremental(fos);
        //IOUtils.closeQuietly(signatureOptions);
        return doc;
        }

1 个答案:

答案 0 :(得分:1)

  • 根据建议更改为新的 ByteArrayOutputStream 对象并使用 saveIncremental 方法使其有效。下面的代码段。

public PDDocument sign(PDDocument doc1){
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     doc1.save(byteArrayOutputStream);
     PDDocument doc = PDDocument.load(byteArrayOutputStream.toByteArray());
     int accessPermissions = SigUtils.getMDPPermission(doc);

     //sign doc here
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     doc.saveIncremental(baos);
     IOUtils.closeQuietly(signatureOptions);
     return baos.toByteArray();
}