簡體   English   中英

使用PDFBox保護PDF

[英]Protecting PDF using PDFBox

我真的在為PDFBox的文檔掙扎。 對於這樣一個受歡迎的圖書館信息似乎有點薄(對我來說!)。

無論如何,我有關於保護PDF的問題。 目前我想要的是控制用戶的訪問權限。 特別是我想阻止用戶修改PDF。

如果我省略訪問權限代碼,一切都很完美。 我正在從外部資源中讀取PDF。 然后我在閱讀並填充字段,在保存新PDF之前添加一些圖像。 這一切都很完美。

當我添加以下代碼來管理訪問時出現問題:

/* Secure the PDF so that it cannot be edited */
try {
    String ownerPassword = "DSTE$gewRges43";
    String userPassword = "";

    AccessPermission ap = new AccessPermission();
    ap.setCanModify(false);

    StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, userPassword, ap);
    pdf.protect(spp);
} catch (BadSecurityHandlerException ex) {
    Logger.getLogger(PDFManager.class.getName()).log(Level.SEVERE, null, ex);
}

當我添加此代碼時,所有文本和圖像都是從傳出的pdf中條帶化的。 這些字段仍然存在於文檔中,但它們都是空的,並且原始PDF的一部分以及在代碼中動態添加的所有文本和圖像都消失了。

更新:好的,盡我所知,問題來自與表單字段相關的錯誤。 我將嘗試一種沒有表單字段的不同方法,看看它給出了什么。

我找到了解決這個問題的方法。 看來,如果PDF來自外部源,有時PDF受到保護或加密。

如果從外部源加載PDF文檔並獲得保護時出現空白輸出,則可能使用加密文檔。 我有一個處理PDF文檔的流處理系統。 所以下面的代碼對我有用。 如果您只是使用PDF輸入,那么您可以將以下代碼與您的流程集成。

public InputStream convertDocument(InputStream dataStream) throws Exception {
    // just acts as a pass through since already in pdf format
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768"); //for large files

    PDDocument doc = PDDocument.load(dataStream, true);

    if (doc.isEncrypted()) { //remove the security before adding protections
        doc.decrypt("");
        doc.setAllSecurityToBeRemoved(true);
    }
    doc.save(os);
    doc.close();
    dataStream.close();
    os.close();
    return is;
}

現在拿回返回的InputStream並將其用於您的安全應用程序;

   PipedOutputStream os = new PipedOutputStream();
   PipedInputStream is = new PipedInputStream(os);

   System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768");
   InputStream dataStream = secureData.data();

   PDDocument doc = PDDocument.load(dataStream, true);
   AccessPermission ap = new AccessPermission();
   //add what ever perms you need blah blah...
   ap.setCanModify(false);
   ap.setCanExtractContent(false);
   ap.setCanPrint(false);
   ap.setCanPrintDegraded(false);
   ap.setReadOnly();

   StandardProtectionPolicy spp = new StandardProtectionPolicy(UUID.randomUUID().toString(), "", ap);

   doc.protect(spp);

   doc.save(os);
   doc.close();
   dataStream.close();
   os.close();

現在這應該返回一個沒有空白輸出的正確文檔!

訣竅是先刪除加密!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM