php com word 设置可编辑区域(限制编辑,部分可编辑,部分不可编辑)

在这里插入图片描述
测试文档内容如上图。

 // 打开word 编辑
        $file = 'C:/Users/Administrator/Desktop/11.doc';
        $word = new \com("word.application",null,CP_UTF8) or die("Unable to instantiate Word");
        $word->Visible = 0;
        $word->Documents->Open($file,true,false);
        // wdAllowOnlyReading 3
        // https://docs.microsoft.com/en-us/office/vba/api/word.wdprotectiontype
        if($word->ActiveDocument->ProtectionType!=-1){
            $word->ActiveDocument->UnProtect('123456');
        }
        $Paragraphs = $word->ActiveDocument->Paragraphs;
        for ($i = 1; $i <= $Paragraphs->Count; $i++) {
            if($i==1||$i==3){ //给需要编辑的区域添加editor
                // -1 代表everyone
                $Paragraphs->Item($i)->Range->Editors->Add(-1);
            }
        }
        $word->ActiveDocument->Protect(3,false,'123456',false,true);
        $word->ActiveDocument->Save();
        $word->Quit();
        $word = null;

如果想把一个受保护的文档中可编辑部分变成不可编辑,只需删除其区域的editor即可,例如,把上面的文档再经过下面这么一折腾,文档的所有部分就都不可编辑了:

$file = 'C:/Users/Administrator/Desktop/11.doc';
        $word = new \com("word.application",null,CP_UTF8) or die("Unable to instantiate Word");
        $word->Visible = 0;
        $word->Documents->Open($file,true,false);

        $Paragraphs = $word->ActiveDocument->Paragraphs;
        for ($i = 1; $i <= $Paragraphs->Count; $i++) {
            $Editors = $Paragraphs->Item($i)->Range->Editors;
            if($Editors->Count>0){
                for($j=1;$j<=$Editors->Count;$j++){
                    $Editors->Item($j)->Delete();
                }
            }
        }

        $word->ActiveDocument->Save();
        $word->Quit();
        $word = null;

猜你喜欢

转载自blog.csdn.net/wang740209668/article/details/108604975
今日推荐