Convert PDF to an image using a dither matrix

Convert PDF to an image using a dither matrix

This code sample shows how to convert a PDF page to a bitmap image, while applying a dither matrix to the generated image. Dithering is the processing of applying a matrix to the original image and thereby adding seemingly randomized noise. This is done to prevent color banding and other large scale patterns to occur in your image. Read more.

Michelangelos David Floyd Steinberg

using (FileStream fs = new FileStream(@"..\..\input.pdf", FileMode.Open, FileAccess.Read))
    Document d = new Document(fs);

    int[][] DitherMatrix = new int[][] {
            new int[] { 9, 9, 7 }, 
            new int[] { 4, 1, 0 }, 
            new int[] { 0, 5, 2 }};
    Page page = d.Pages[0];

    Bitmap bitmap = new Bitmap((int)page.Width, (int)page.Height);

    ConvertToTiffOptions options = new ConvertToTiffOptions();

    //set a dithering matrix
    options.DitherMatrix = DitherMatrix;

    using (MemoryStream ms = new MemoryStream())
        using (Graphics graphics = Graphics.FromImage(bitmap))
            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            page.ConvertToTiff(ms, options);
        bitmap = new Bitmap(ms, false);