Viewing text documents in WPF
this my text file document viewer selecting file from FileDialog on program start shows nothing, add DocX as link, what is this error?
<Window x:Class="Wordviewer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="524" Width="901">
<Grid Background="#FF464966">
<DocumentViewer HorizontalAlignment="Left" Margin="12,41,0,0"
Name="documentViewer1" VerticalAlignment="Top" Height="508" Width="923" BorderBrush="#FFA28D8D" />
<TextBox Height="29" HorizontalAlignment="Left" Margin="12,6,0,0"
Name="FileNameTextBox" VerticalAlignment="Top" Width="730" TextChanged="SelectedFileTextBox_TextChanged" />
<Button Content="Browse" Height="30" HorizontalAlignment="Left" Margin="757,6,0,0"
Name="BrowseButton" VerticalAlignment="Top" Width="178" Click="BrowseButton_Click" FontWeight="Bold">
<Button.BorderBrush>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="#FFD0BDBD" Offset="1" />
</LinearGradientBrush>
</Button.BorderBrush>
</Button>
</Grid>
and this one
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".doc";
dlg.Filter = "Word documents|*.doc;*.docx";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
FileNameTextBox.Text = filename;
var document = DocX.Load(filename);
string contents = document.Text;
// Use the file
}
}
source to share
In short, you cannot. A control DocumentViewer
in WPF cannot display Word document files ( .doc
, .docx
). It is designed to display XPS files, which is a conceptually different kind of document, similar to PDF files.
(To the uninitiated, Word differs from PDF and XPS documents (although they look the same when printed) in that they are editable, pay-compatible, structured documents, whereas PDFs and XPS documents essentially just say printer to print (e.g. PostScript) - think about this when comparing vector art to bitmap, even though they may look the same.)
There are ways to get around this, all of which involve converting a Word document to XPS. The first route is to use Office Automation to load Word in the process and convert the document to XPS, which requires Word to be installed and available on the system. The second option is to use a third party library like Aspose or Gem.
source to share
You have one option, you can use the Interop Office libraries, open a Word document along with them and then save them as XPS and then view. But I think it's a little hard.
Check it out: http://www.dotnetperls.com/word
source to share