使用Java

时间:2019-05-14 18:25:55

标签: java apache-poi

我需要标识具有扩展名.docx的word文档的特定部分或部分,并禁用它,以便其他用户无法对其进行修改。什么是在Java中最好的api。请提供一个完整的有意义的示例,包括有关罐子和所有罐子的细节。预先感谢...。

1 个答案:

答案 0 :(得分:0)

尝试Apache POI Library。我已经能够以byte[]的形式读取Word文档(.docx)并锁定文件的某些部分以进行编辑。在下面的示例中,假定书签被放置在文档中,因此指定应锁定哪些部分,以及应将哪些保留为可编辑状态。

//Open word document with Apache POI
    InputStream inputStream = new ByteArrayInputStream(wordDoc);
    XWPFDocument document = new XWPFDocument(inputStream);

    //Collect all Bookmarks from the document
    List<Bookmark> bookmarks = getBookmarks(document);

    //Collect all editable sections from the document
    List<EditableSection> editableSections = getEditableSections(bookmarks);

    //NOW MARK THE SECTIONS IN THE DOCUMENT WHICH ARE EDITABLE
    Random random = new Random();
    String randomId = Integer.toString(random.nextInt(1000000000));

    for(EditableSection section: editableSections)
    {
        CTPermStart permStart = section.getStart().getCTP().addNewPermStart();
        permStart.setEdGrp(STEdGrp.EVERYONE);
        permStart.setId(randomId);

        CTPerm permEnd = section.getEnd().getCTP().addNewPermEnd();
        permEnd.setId(randomId);
    }

    //Enforce the readonly protection everywhere except where it was marked safe
    document.enforceReadonlyProtection(wordProtectPassword, HashAlgorithm.md5);

    ByteArrayOutputStream res = new ByteArrayOutputStream();
    document.write(res);
    return res.toByteArray();


public class EditableSection {

    private XWPFParagraph start;
    private XWPFParagraph end;

    public EditableSection(XWPFParagraph start, XWPFParagraph end) {
        this.start = start;
        this.end = end;
    }

    public XWPFParagraph getStart() {
        return start;
    }

    public void setStart(XWPFParagraph start) {
        this.start = start;
    }

    public XWPFParagraph getEnd() {
        return end;
    }

    public void setEnd(XWPFParagraph end) {
        this.end = end;
    }
}

public class Bookmark {

    private String bookmark;
    private XWPFParagraph paragraph;

    public Bookmark(XWPFParagraph paragraph, String bookmark) {
        this.paragraph = paragraph;
        this.bookmark = bookmark;
    }

    public String getBookmark() {
        return bookmark;
    }

    public void setBookmark(String bookmark) {
        this.bookmark = bookmark;
    }

    public XWPFParagraph getParagraph() {
        return paragraph;
    }

    public void setParagraph(XWPFParagraph paragraph) {
        this.paragraph = paragraph;
    }
}