首页 > 解决方案 > 使用java取消保护word文档

问题描述

我们如何使用 java apache poi 取消对 word 文档的保护?我以编程方式使用密码将文档保护为只读。现在我想取消保护它。我们该怎么办?有什么方法可以取消保护文档。我使用了 removePasswordProtection() 但即使使用该方法后该文档也无法编辑。

我用于保护的示例代码是

XWPFDocument document=new XWPFDocument();
 document.enforceReadonlyProtection(strPassword,HashAlgorithm.sha1);

文档已成功获得保护。

但是,当我使用下面的代码片段取消保护文档时,它不起作用。

 if(document.isEnforcedReadonlyProtection())
     {
     if(document.validateProtectionPassword(strPassword))
     {
        document.removeProtectionEnforcement();
     }
     }

谁能帮助我可以使用什么方法来取消保护文档?

标签: javams-wordapache-poi

解决方案


无法重现。

以下代码生成两个Word文档。一个, WordProtected.docx, 被保护, 一个,WordUnprotected.docx保护被移除。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

import org.apache.poi.poifs.crypt.HashAlgorithm;

class XWPFReadOnlyProtection {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  String strPassword = "password";

  document.enforceReadonlyProtection(strPassword, HashAlgorithm.sha1);

  FileOutputStream fileout = new FileOutputStream("WordProtected.docx");
  document.write(fileout);
  fileout.close();
  document.close();

  document = new XWPFDocument(new FileInputStream("WordProtected.docx"));

  document.removeProtectionEnforcement();

  fileout = new FileOutputStream("WordUnprotected.docx");
  document.write(fileout);
  fileout.close();
  document.close();

 }
}

推荐阅读