我构建了具有两个复选框的 word 插件,用于在 TEXT 视图和 XML 视图之间进行擦拭。在 XML 查看中,我限制了编辑。当用户返回文本查看时,我删除了编辑限制。编码:
private void ShowDocBodyXML_Click(object sender, RibbonControlEventArgs e)
{
var doc = Globals.DLPAddIn.Application.ActiveDocument;
doc.Save();
string fileName = doc.FullName;
doc.Close();
using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true))
{
MainDocumentPart mainPart = document.MainDocumentPart;
Body body = mainPart.Document.Body;
string text = body.InnerXml;
body.RemoveAllChildren();
DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(text));
}
Globals.DLPAddIn.Application.Documents.Open(fileName);
doc = Globals.DLPAddIn.Application.ActiveDocument;
object missing = System.Reflection.Missing.Value;
doc.Protect(Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyReading,
missing, missing, missing, missing);
doc.Save();
}
private void ShowDocBodyText_Click(object sender, RibbonControlEventArgs e)
{
var doc = Globals.DLPAddIn.Application.ActiveDocument;
object missing = System.Reflection.Missing.Value;
if (doc.ProtectionType != WdProtectionType.wdNoProtection)
doc.Unprotect(missing);
doc.Save();
string fileName = doc.FullName;
doc.Close();
using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true))
{
MainDocumentPart mainPart = document.MainDocumentPart;
Body body = mainPart.Document.Body;
string text = body.InnerText;
body.RemoveAllChildren();
body.InnerXml = text;
}
Globals.DLPAddIn.Application.Documents.Open(fileName);
}
该代码可以正常工作,但是如果当用户尝试返回 TEXT 时 Word Doc 有图像,则在此代码中查看代码抛出异常(文件已损坏):
Globals.DLPAddIn.Application.Documents.Open(fileName);
我认为当我限制编辑时,它会删除图像文件。如果是这样,我该如何解决这个问题。