Previewing Microsoft Office Documents and PDF in WPF using a Preview Handler Host


Hi,

I had recently to implement a mechanism for showing documents into a WPF application. The very first solution was to start a new process using the path of the selected file. The only condition for this to work it’s that the file extension should have been previously registered to be opened with an specific application. A drawback is that the document is shown by an external application that we are not able to handle (at all or at least easily).

Then the client decided showing documents by embedding them into the application. So, I started researching about how to display Portable documents, Word documents, Excel documents into a WPF application. Finally after some research I got to a nice solution which will display many documents formats with the only condition of having the proper software installed into the PC where the application is gonna run.

The Problem
Showing a office document (XLS, DOC, XLSX, DOCX) or portable document (PDF) into a WPF APP.

Remarks
This is not a bullet proof solution, but it is kind extensible for brave developers. The relays on the installed Preview Handlers. For example for visualizing Microsoft Office documents you will have to have installed Microsoft Office in the computer where the application is going to run. It’s the same case for PDF files, where you need to have a Preview Handler installed.
Moreover, the technology of Preview Handler has been built using native code, in order to embedded into a WPF application the app will be hosting WinForm content, this introduces a different set of restrictions about the interaction of the control once it has been instantiated.

The Solution
Preview Handlers is a technology added into Windows Vista, and it’s meant to readonly quick preview of files. It’s available on Windows Explorer
Enabling Previews in Windows Vista Folders
The Microsoft article [1] about Preview Handlers has an utility application which lists the available preview handlers in your system. Moreover after some research, I found the first implementation in [2] which was using Windows Forms and C# for development. Finally I found a more elaborated solution from Coding4Fun [3]. Since this point the solution for WPF was straightforward because it was only matter of loading a WinForm contro into WPF by using Interop components.

1) Grab the code from http://c4fdevkit.codeplex.com/ project. To use the Preview Handler Host you will need only two projects.
/Preview Handlers/Source/VCS/PreviewHandlerFramework
/Preview Handlers/Source/VCS/PreviewHandlerHost

Compile them and the create a new WPF project. The codeplex project hasn’t been updated in awhile, thus you’re more likely to have to update the solution file to a new version of visual studio.

2) Add to your WPF application (or library) a reference to WindowsFormIntegration library. This will allow the application to host WinForm controls. Also add System.Windows.Forms since it will be required by the Preview Handler libraries.

3) The use the WindowsFormsHost tag to embed the PreviewHandlerHostControl as the follwing XAML shows:


        <button></button>

            <C4F_DevKit_PreviewHandler_PreviewHandlerHost:PreviewHandlerHostControl x:Name="previewHandlerHostControlInstance" />

4) Finally our C# code that for our sample is quite simple. We just select a file and let the PreviewHandlerHost control do the work.

using System;
using System.Windows;

namespace PreviewHandlerWpfApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.OpenFileDialog();
            if (dlg.ShowDialog().Value)
            {
                previewHandlerHostControlInstance.FilePath = dlg.FileName;
            }
        }
    }
}

Here is an screenshot of my mighty document viewer:

Sample.Word.Document.Capture

Finally the code is available at GitHub https://github.com/hmadrigal/playground-dotnet/tree/master/MsDesktop.PreviewHandlers Have fun!

References

 

 

Advertisements

16 comments

  1. Thanks, for the sharing of your know how, it was very helpful.

    I have to add a notice: some small fix was required in my case PreviewHandlerHostControl class in GeneratePreview() method:
    StreamWrapper stream = new StreamWrapper(File.Open(_filePath, FileMode.Open));
    was replaced
    StreamWrapper stream = new StreamWrapper(File.Open(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read));

  2. Hi HMADRIGAL,
    do you have any ideas why this solution doesn’t work in Environment Windows 8? Adober Reader handler throws an exception and Office Previews (Office 2013) don’t work.

    Activator.CreateInstance hangs with Office handlers:
    ((IPreviewHandler)_comInstance).DoPreview();

    By Adobe Reader exception comes later in line
    ((IPreviewHandler)_comInstance).DoPreview();

    In Windows 7 environment + Office 2010 it works perfectly: i have previews for files with extensions PDF, doc, docx, xls, xlsx, ppt, pptx, vsd.

  3. Hi @Iryna Grimpe

    Excuse me, I forgot to mention that I coded this sample on Windows 7 and Office 2010. I haven’t checked its behavior on Windows 8 yet.

    Were you able to resolve the issue on Windows 8?
    If not, I’ll try to check the sample on Windows 8 over weekend.

    Kind regards,
    Herber

    1. Well that’s is interesting idea. From the top of my head, I don’t think it’s possible, but you will have to look for an option to communicate with the Preview Handler.

    1. @Mina
      I have ran the code on Windows 8. It is working well for Office documents (you must need to have installed Office in order to this to work properly).

      The PDF you need to install Acrobat PDF or Fox It PDF. If will try first with Adobe PDF reader, if it does not work as expected then try with Fox It Preview Handler (at http://timheuer.com/blog/archive/2008/05/09/foxit-pdf-preview-handler.aspx ).

      If you experience an issue, don’t hesitate to share your experience and I’ll try to support you as much as I can.

      Kind Regards,
      Herber

    1. I am sorry I do not have Win XP SP3 for checking it. My only suggestion is to try to run the same app in a different box. There a few cases where the Preview Handler does not get registered properly in a given computer. So, there is a chance that it is an issue that only happens in your box.

      Herb

  4. Hmadrigal, I’m trying to get it working with Microsoft Outlook MSG files but when I preview the email, the styling of the whole document is messed up and embedded images aren’t visible… Do you have any solutions??

    PS: for Word Documents its the same…

    1. Hi Jouke,

      Well not really sure how to solve your issue, but you can try re-installing office, it will attempt to re-install the preview handlers and that may work in your case.
      For PDF previewing you may consider installing FoxIt Preview Hanlder (or FoxIt PDF reader).

      Cheers,
      Herber

      1. Hi Herber,

        I’ll give it a try and will let you know! For PDF I’m using the Foxit Preview Handler! Awesome thanks for the tip!!

        Regards,
        Jouke

  5. Hi,
    The sample app tells me “No Preview Available” on windows 8.1 (I have foxit reader installed and preview is available in explorer).
    Any idea?

    1. @David,

      Sorry for my late response. The last weekend I tried to see what’s happening on Windows 8.1 (aka W8.1) . After some googling, I noticed that W8.1 does not include a default Preview Handler, I have do an additional test on my other PC with W8.1.
      Hopefully I will find some room over this weekend.

      Cheers,
      Herb

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s