gpt4 book ai didi

pdfbox - 如何在使用 Apache PDFBox 编写新 PDF 时将交互式 PDF 表单设置为只读模式?

转载 作者:行者123 更新时间:2023-12-04 13:49:09 40 4
gpt4 key购买 nike

我正在使用 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();
}

请帮我解决这个问题。

最佳答案

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();

}

}

关于pdfbox - 如何在使用 Apache PDFBox 编写新 PDF 时将交互式 PDF 表单设置为只读模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880782/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com