Greycastle Logo

Copy pure text from WPF DocumentViewer XPS

I (as previously mentioned) use the WPF DocumentViewer for previewing word documents as XPSs. Howerver, as curious users are often more curious then they should be I´ve found that some users wish to copy text from the XPS directly to Word.

This gives us some amount of pain since the RTF copied from the XPS might be quite invalid in regard to format (font, size, boldness etc). So, I found myself in need of selecting only the unformatted text.

This link helped me a lot, we can simply intercept the DocumentViewer copy-command and paste the text we want for ourselves in the clipboard.

<DocumentViewer x:Name="DocViewer">
<DocumentViewer.CommandBindings>
<CommandBinding Command="ApplicationCommands.Copy" CanExecute="CanExecuteCopy" Executed="OnExecuteCopy" />
</DocumentViewer.CommandBindings>
</DocumentViewer>

Then for the codebehind, we utilize reflection to retrieve the non-public TextSelection property:

public string SelectedText {
    get {
        var selectionProperty = DocViewer.GetType ().GetProperty ("TextSelection", BindingFlags.Instance | BindingFlags.NonPublic);
        var selection = selectionProperty.GetValue (DocViewer, null) as TextSelection;
        return selection != null ? selection.Text : null;
    }
}

private void OnExecuteCopy (object sender, ExecutedRoutedEventArgs e) {
    Clipboard.SetText (SelectedText);
    e.Handled = true;
}

private void CanExecuteCopy (object sender, CanExecuteRoutedEventArgs e) {
    e.CanExecute = SelectedText != null;
}

Enjoy 🙂

© 2024 Greycastle