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

问题描述 投票:0回答:1

我需要通过Java保护Word(2013)文档的某些部分,并使它们只读。Apache POI有可能吗?如果是的话,怎么办?我只发现保护整个文档的可能性。

((我不仅需要保护页眉和页脚,还需要保护正文部分的某些行。)

ms-word apache-poi protection
1个回答
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

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

 }
}

此代码需要jar中提到的所有模式ooxml-schemas-*.jar的完整FAQ-N10025

如果您想强制执行填充表单保护,那么它将变得更加复杂,因为这将需要多个部分。

© www.soinside.com 2019 - 2024. All rights reserved.