如何使用Apache PDFBox在以新PDF格式写入时以只读模式设置交互式PDF表单?

时间:2014-11-12 06:37:39

标签: pdfbox

我正在使用 Apache PDFBox库以可填写的PDF格式(AcroFrom)填写信息。完成信息填写后,我需要写一个新的PDF文件(以不可编辑的格式)

我尝试了setReadOnly()方法,该方法在AccessPermission类中可用。但我仍然可以编辑新创建的PDF文档中的值。

代码:

private static PDDocument _pdfDocument;

public static void main(String[] args) {

String originalPdf = "C:/sample/Original.pdf";
String targetPdf = "C:/sample/target.pdf";

 try {
        populateAndCopy(originalPdf, targetPdf);
 -----------
 -----------
 -----------
 -----------
 }

 } // Main method complted




private static void populateAndCopy(String originalPdf, String targetPdf) throws IOException, COSVisitorException {
    _pdfDocument = PDDocument.load(originalPdf);

    _pdfDocument.getNumberOfPages();

    _pdfDocument.getCurrentAccessPermission().setCanModify(false);
    _pdfDocument.getCurrentAccessPermission().setReadOnly();
    System.out.println(_pdfDocument.getCurrentAccessPermission().isReadOnly());
    _pdfDocument.save(targetPdf);
    _pdfDocument.close();
}      

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

您的代码未设置任何加密,这就是问题所在。

试试这个:

    AccessPermission ap = new AccessPermission();
    ap.setCanModify(false);
    ap.setReadOnly();
    StandardProtectionPolicy spp = new StandardProtectionPolicy("owner-password", "", ap);
    spp.setEncryptionKeyLength(128);
    doc.protect(spp);
    doc.save(targetPdf);
    doc.close();

我设置了128作为密钥长度,因为1.8不支持256而且40太短。

用户可以在没有密码的情况下打开文档(请参阅空密码参数),但他只有受限制的权限。

答案 1 :(得分:0)

public static void main(String[] args)  {

    try {
    String formTemplate = "xyz.pdf";

    // load the document
    PDDocument pdfDocument = PDDocument.load(new File(formTemplate));

    // get the document catalog
    PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();

    // as there might not be an AcroForm entry a null check is necessary
    if (acroForm != null)
    {
        // Retrieve an individual field and set its value.
        PDTextField field1 = (PDTextField) acroForm.getField( "_lastName" );
        field1.setValue("pppp");
        PDTextField field2 = (PDTextField) acroForm.getField( "_firstName" );
        field2.setValue(aaaa");
    }


    // flatten() method saves the PDF read only
    acroForm.flatten();

    // Save and close the filled out form.
    pdfDocument.save("xyz.pdf");
    pdfDocument.close();
    System.out.println("Done!!");

    } catch(Exception e) {
        e.printStackTrace();

    }

}
相关问题