Reputation: 385
I build word addin that have two check-boxes to swabbing between TEXT view and XML View. And in the XML viewing I restrict the editing. When the user return back to TEXT viewing I remove the restriction for editing. The code:
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);
}
The code is working with out any problem but if the Word Doc have an image when the user trying to return back to TEXT viewing the the code throw exception (The file was corrupted) in this code:
Globals.DLPAddIn.Application.Documents.Open(fileName);
I think when I restrict the editing it remove the image file. If it's like that how can i solve this problem.
Upvotes: 1
Views: 494
Reputation: 176169
Your current approach does not work when there are images or other resources in the document because your strip all images when creating the Word document containing only the XML of the MainDocumentPart
.
One solution to this is to show the OpenXML in the so-called Flat OPC format. This format describes the entire OpenXML (zip) package in a single XML document (without the hierarchical structure of the OpenXML package).
The easiest way to obtain the XML in Flat OPC format is to use the Document.WordOpenXML
property:
var doc = Globals.DLPAddIn.Application.ActiveDocument;
var xml = doc.WordOpenXML;
var newDoc = Globals.DLPAddIn.Application.Documents.Add();
newDoc.Range.Text = xml
Upvotes: 1