Reputation: 784
I've been able to generate a simple word document using a format similar to the format used in this SO question, however whenever I open the document it opens in print layout view. Is there a way that I can programmatically make it open in web layout view by default?
Upvotes: 1
Views: 1603
Reputation: 12815
Yes, you can by using a OpenXML.WordProcessing.View
. You need to create a View
with its Val
set to ViewValues.Web
. Then you need to create a Settings
object and append the view
to it. Finally, you need to create a DocumentSettingsPart
and set its Settings
property to the settings
object you've created.
That sounds worse than it is, below is a complete method taking the code from the question you mention plus code for the above. I've removed the memory stream code from that answer to simplify things; this code will create a file on disk.
public static void CreateWordDoc(string filename)
{
using (var wordDocument = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("Hello world!"));
//the following sets the default view when loading in Word
DocumentSettingsPart documentSettingsPart = mainPart.AddNewPart<DocumentSettingsPart>();
Settings settings = new Settings();
View view1 = new View() { Val = ViewValues.Web };
settings.Append(view1);
documentSettingsPart.Settings = settings;
mainPart.Document.Save();
}
}
Upvotes: 1