How To View PDF Documents


Important: PDF support is provided by the open source PDF reader that only implements part of the PDF specification. The PDF engine is work in progress and your documents may not render properly.

The following step-by-step tutorial demonstrates how to view PDF documents with Document Toolkit. The download link for the complete source code of this tutorial is available at the bottom of this page.

1) Open Visual Studio 2010 and create a new Silverlight 4 application

2) Use NuGet to add references to the DocumentToolkit and DocumentToolkit.Pdf packages (see How To Install Document Toolkit using NuGet).

3) Add an existing PDF document to the project as content. Right-click the project, select Add > Existing Item... and select a PDF document from disk. Make sure you set the Build Action to Content, which causes the document to appear as file in the XAP package.

If you do not have a PDF document available, you can download and use TestDocument.pdf

4) Open the MainPage.xaml and add the following elements and XML namespace declaration:

xmlns:doc="http://schemas.firstfloorsoftware.com/documenttoolkit"

<doc:DocumentDataSource x:Name="DataSource" LoadError="DataSource_LoadError" />
<doc:DocumentViewer x:Name="Viewer" DocumentDataSource="{Binding ElementName=DataSource}"/> 

5) Make sure the LoadError event handler is implemented in the code-behind. The below snippet simply displays an error messagebox.

using FirstFloor.Documents.Controls;

private void DataSource_LoadError(object sender, ErrorEventArgs e)
{
    MessageBox.Show(e.Error.Message);
}

6) To load a document we need to assign the PdfDocumentReader to the DocumentDataSource. The following code snippet demonstrates how the PDF document that was previously added as content to the project is loaded.

using FirstFloor.Documents.Pdf;

this.DataSource.PackageReader = new PdfDocumentReader(new Uri("TestDocument.Pdf", UriKind.Relative));


And that's it. To view PDF instead of XPS documents you only need to use the PdfDocumentReader. All other elements in the Document Toolkit remain the same, you use the same DocumentViewer, DocumentDataSource and so on.

Tutorial source code: PdfDocumentViewer.zip

Last edited Dec 5, 2011 at 10:13 AM by kozw, version 9

Comments

aurora7795 Dec 2, 2014 at 3:06 PM 
Tried running the tutorial source code and got the following error:

Could not read the XPS package. Either the package is not valid XPS or the package reader does not support the ZIP format of the package.

Any ideas? Thanks
Martin