如何使用Apache POI保护word文档的各个部分

时间:2017-05-11 07:59:27

标签: ms-word apache-poi protection

我需要通过Java保护我的Word(2013)文档的部分内容,并使它们只读。 这可能与Apache POI有关吗?如果是,怎么样? 我只发现保护整个文件的可能性。

(我不仅需要保护页眉和页脚,还要保护身体部位的一些线条。)

1 个答案:

答案 0 :(得分:1)

您可以在Word文档中执行多种保护。如果您要强制执行只读保护,则可以使用CTPermStartCTPerm标记保护范围。

示例:

import java.io.*;

import org.apache.poi.wp.usermodel.*;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPermStart;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STEdGrp;

public class CreateWordPartialProtected {

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

  XWPFDocument document= new XWPFDocument();

  // create header
  XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT);

  XWPFParagraph paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  XWPFRun run = paragraph.createRun();  
  run.setText("The page header:");

  // create footer
  XWPFFooter footer = document.createFooter(HeaderFooterType.DEFAULT);

  paragraph = footer.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.CENTER);

  run = paragraph.createRun();  
  run.setText("Page ");
  paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* MERGEFORMAT");
  run = paragraph.createRun();  
  run.setText(" of ");
  paragraph.getCTP().addNewFldSimple().setInstr("NUMPAGES \\* MERGEFORMAT");

  // the body content
  paragraph = document.createParagraph();
  run=paragraph.createRun();  
  run.setText("This body part is protected.");
  paragraph = document.createParagraph();

  // CTPermStart marking the start of unprotected range  
  CTPermStart ctPermStart = document.getDocument().getBody().addNewPermStart();
  ctPermStart.setEdGrp(STEdGrp.EVERYONE);
  ctPermStart.setId("123456"); //note the Id

  paragraph = document.createParagraph();
  run=paragraph.createRun();  
  run.setText("This body part is not protected.");

  // CTPerm marking the end of unprotected range  
  document.getDocument().getBody().addNewPermEnd().setId("123456"); //note the same Id

  paragraph = document.createParagraph();

  paragraph = document.createParagraph();
  run=paragraph.createRun();  
  run.setText("This body part is protected again.");
  paragraph = document.createParagraph();

  document.enforceReadonlyProtection(); //enforce readonly protection

  document.write(new FileOutputStream("CreateWordPartialProtected.docx"));
  document.close();

 }
}

如果您希望强制执行填写表单保护,那么它会更复杂,因为那时需要多个部分。