New to Telerik UI for WPF? Download free 30-day trial

Loading a Multipage Tiff File in a RadPdfViewer Using TiffBitmapDecoder

Environment

Product Version 2021.2.913
Product RadPDFViewer for WPF

Description

How to show a multipage Tiff file in the RadPdfViewer with the help of the System.Windows.Media.Imaging.TiffBitmapDecoder.

Solution

This functionality can be achieved by splitting the multipage TIFF file into single page ones. Then to insert them into a RadFixedDocument as a RadFixedPages content.

Example 1: Loading the TIFF file

private void LoadTiff(object sender, RoutedEventArgs e) 
{ 
    RadFixedDocument radFixedDocument = new RadFixedDocument(); 
 
    Bitmap[] bitmaps = this.SplitTiff("SampleData/test.tiff"); 
    for (int i = 0; i < bitmaps.Length; i++) 
    { 
        BitmapSource bitmapSource = ConvertToBitmapSource(bitmaps[i]); 
        RadFixedPage documentPage = new RadFixedPage(); 
        ImageSource imageSource = new ImageSource(bitmapSource, ImageQuality.High); 
        documentPage.Content.AddImage(imageSource); 
        radFixedDocument.Pages.Add(documentPage); 
    } 
 
    this.pdfViewer.Document = radFixedDocument; 
} 

Example 2: Splitting the TIFF file

private Bitmap[] SplitTiff(string inputFilePath) 
{ 
    Bitmap[] bitmaps; 
 
    using (MemoryStream stream = new MemoryStream(File.ReadAllBytes(inputFilePath))) 
    { 
        TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); 
 
        int noOfPages = tiffDecoder.Frames.Count; 
        bitmaps = new Bitmap[noOfPages]; 
 
        for (int i = 0; i < noOfPages; ++i) 
        { 
            Bitmap bitmap; 
            using (var outStream = new MemoryStream()) 
            { 
                BitmapEncoder bitmapEncoder = new BmpBitmapEncoder(); 
                bitmapEncoder.Frames.Add(BitmapFrame.Create(tiffDecoder.Frames[i])); 
                bitmapEncoder.Save(outStream); 
                bitmap = new Bitmap(outStream); 
            } 
 
            bitmaps[i] = bitmap; 
        } 
    } 
 
    return bitmaps; 
} 

Example 3: Converting the Bitmap to a BitmapSource

private BitmapSource ConvertToBitmapSource(Bitmap bitmap) 
{ 
    BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( 
        bitmap.GetHbitmap(), 
        IntPtr.Zero, 
        Int32Rect.Empty, 
        BitmapSizeOptions.FromEmptyOptions()); 
 
    return bitmapSource; 
} 

Notes

There is a request to create a new TIFF Viewer Control. Make sure to cast your vote for it as this directly affects its priority: New Control: TIFF Viewer.

In this article