You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFBox 2.0.29添加CMS签名后PDF签名损坏的问题求助

PDFBox 2.0.29添加CMS签名后PDF签名损坏的问题求助

大家好,我最近在做PDF签名功能时遇到了个麻烦,想请各位帮忙看看。

我尝试用PdfBox 2.0.29版本结合CMS签名给PDF文档签名,但每次生成的PDF里签名都是损坏的,打开后会提示“document has been altered or corrupted since it was signed”。我希望能把签名成功添加到PDF中,并且让签名处于有效状态,不知道有没有办法解决这个问题?

以下是我目前使用的代码:

public ResponseEntity<String> signPdf(@RequestParam String pdfPath, @RequestParam String cmsSignature64){
    try{
        // Decode CMS signature from Base64
        byte[] cmsSignature = java.util.Base64.getDecoder().decode(cmsSignature64);
        
        // Load the PDF document
        Path pdfFilePath = Path.of(pdfPath);
        if(!Files.exists(pdfFilePath)){
            return ResponseEntity.badRequest().body("PDF file not found at:" + pdfPath);
        }
        
        File inputFile = pdfFilePath.toFile();
        PDDocument document = PDDocument.load(inputFile);
        
        // Create a new signature
        PDSignature signature = new PDSignature();
        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
        signature.setReason("QualifiedCertification");
        signature.setLocation("");
        signature.setSignDate(Calendar.getInstance());
        signature.setContents(new byte[8192]);
        
        // Add the signature field with a specific name
        signature.setName("DetachedSignature");
        document.addSignature(signature);
        
        // Prepare the external signature
        ExternalSigningSupport externalSigning = document.saveIncrementalForExternalSigning(new FileOutputStream(inputFile));
        
        // Write the detached CMS signature to the PDF
        externalSigning.setSignature(cmsSignature);
        
        // Save and close the document
        document.close();
        
        return ResponseEntity.ok("PDF signed successfully:" + pdfFilePath.toString());
    }catch(Exception e){
        e.printStackTrace();
        return ResponseEntity.status(500).body("Error while signing PDF:" + e.getMessage());
    }
}

备注:内容来源于stack exchange,提问作者Rui Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:28:03