问题
I need to protect parts of my Word (2013) document via Java and make them read only. Is that possible with Apache POI? And if yes, how? I only found the possibility to protect the whole document.
(I need to protect not only the header and footer but also some lines in the body part.)
回答1:
There are multiple kinds of protection you can enforcing in an Word
document. If you are enforcing read only protection, then you can exclude ranges from protection by marking them using CTPermStart and CTPerm.
Example:
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();
}
}
If you would want to enforce filling forms protection, then it would be more complex since then multiple sections would be necessary.
来源:https://stackoverflow.com/questions/43909661/how-to-protect-parts-of-a-word-document-with-apache-poi