The content of the test document is as shown in the figure above.
// 打开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;
If you want to make the editable part of a protected document uneditable, you only need to delete the editor in the area. For example, if you put the above document through the following toss, all parts of the document will be uneditable:
$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;