How to view word document in WPF application
6919 단어 application
How to view word document in WPF application (CSVSTOViewWordInWPF)
Introduction
The Sample demonstrates how to view word document in WPF application. WPF does not support to view Word documents directly but some customers want to show word document in WPF. So we can use WPF DocumentViewer control to host fixed document such as XPS document. And we also can convert word document to xps document using VSTO.
Building the Sample
Before building the sample, please make sure that you have Installed Microsoft Office 2010 on your machine.
Running the Sample
Step 1. Open CSVSTOViewWordInWPF.sln and click Ctrl+F5 to run the project. You will see the following form:
Step 2. Click "Select Word File"button to select an existing word document on your machine
Step 3. Click "View Word Doc"button to View Word document in WPF DocumentViewer control. If word document isn't exist, when you click the "View Word Doc", you will get the prompt message with "The file is invalid. Please select an existing file again."
If word document is existing on machine and there is no error occurs, you will see the following form:
Using the Code
Step 1. Create WPF Application project via Visual Studio
Step 2. Add references needed to the project
Step 3. Import the needed namespace into the mainWindow.xaml.cs class.
C#
using System; using System.IO; using System.Windows; using System.Windows.Xps.Packaging; using Microsoft.Office.Interop.Word; using Microsoft.Win32; using Word = Microsoft.Office.Interop.Word;
Step 4. Design WPF UI form using XAML codesXAML
<Grid> <Grid.RowDefinitions> <RowDefinition Height="70"></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <Label Name="lable1" Margin="3,6,0,0" Content="Word Document :" VerticalAlignment="Top" HorizontalAlignment="Left" /> <TextBox Name="txbSelectedWordFile" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="110,10,300,0" HorizontalContentAlignment="Left" /> <Button HorizontalAlignment="Right" VerticalAlignment="Top" Width="150" Content="Select Word File" Name="btnSelectWord" Margin="0,10,130,0" Click="btnSelectWord_Click" /> <Button HorizontalAlignment="Left" Margin="3,40,0,0" VerticalAlignment="Top" Content="View Word Doc" Width="100" Name="btnViewDoc" Click="btnViewDoc_Click" /> <DocumentViewer Grid.Row="1" Name="documentviewWord" VerticalAlignment="Top" HorizontalAlignment="Left"/> </Grid>
Step 5. Handle the events in behind class.C#
/// <summary> /// Select Word file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSelectWord_Click(object sender, RoutedEventArgs e) { // Initialize an OpenFileDialog OpenFileDialog openFileDialog = new OpenFileDialog(); // Set filter and RestoreDirectory openFileDialog.RestoreDirectory = true; openFileDialog.Filter = "Word documents(*.doc;*.docx)|*.doc;*.docx"; bool? result =openFileDialog.ShowDialog(); if (result==true) { if (openFileDialog.FileName.Length > 0) { txbSelectedWordFile.Text = openFileDialog.FileName; } } } /// <summary> /// Convert the word document to xps document /// </summary> /// <param name="wordFilename">Word document Path</param> /// <param name="xpsFilename">Xps document Path</param> /// <returns></returns> private XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename) { // Create a WordApplication and host word document Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); try { wordApp.Documents.Open(wordFilename); // To Invisible the word document wordApp.Application.Visible = false; // Minimize the opened word document wordApp.WindowState = WdWindowState.wdWindowStateMinimize; Document doc = wordApp.ActiveDocument; doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS); XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read); return xpsDocument; } catch (Exception ex) { MessageBox.Show("Error occurs, The error message is " + ex.ToString()); return null; } finally { wordApp.Documents.Close(); ((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges); } } /// <summary> /// View Word Document in WPF DocumentView Control /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnViewDoc_Click(object sender, RoutedEventArgs e) { string wordDocument =txbSelectedWordFile.Text; if (string.IsNullOrEmpty(wordDocument) || !File.Exists(wordDocument)) { MessageBox.Show("The file is invalid. Please select an existing file again."); } else { string convertedXpsDoc = string.Concat(Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps"); XpsDocument xpsDocument =ConvertWordToXps(wordDocument, convertedXpsDoc); if (xpsDocument == null) { return; } documentviewWord.Document = xpsDocument.GetFixedDocumentSequence(); } }
Reprinted from http://code.MSDN.Microsoft.com/office/CS vs to view word in WPF-neither 347436/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Pre-Query SamplesValidate the current query criteria or provide additional query criteria programmatically, just before sending the SELEC...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.