Change colors of black-and-white TIFF after converting from PDF

In this article, we will demonstrate how to change the color palette after converting a PDF document to 1bpp TIFF in C#.

Sample Image

In the following code sample, we render a PDF to a 1bpp TIFF. Then create a bitmap from the TIFF, create a new color palette, edit the entries of this palette and assign this new palette to the bitmap.

static void Main(string[] args)
{
    Document document = new Document(new FileStream(@"..\..\input.pdf", FileMode.Open));

    // Convert the PDF Document to TIFF file
    ConvertToTiffOptions tiffOptions = new ConvertToTiffOptions(300.0, TiffCompression.CcittG3);

    string tempPath = @"..\..\tmp.tiff";
    using (FileStream drawImage = new FileStream(tempPath,
        FileMode.OpenOrCreate, FileAccess.Write))
    {
        document.Pages[0].ConvertToTiff(drawImage, tiffOptions);
    }

    string tiffPath = @"..\..\newImage.bmp";
    using (Bitmap tiff = new Bitmap(tempPath))
    {
        // Create a new colorpalette
        System.Drawing.Imaging.ColorPalette palette = Create1bbPalette();

        // Set the palette to other colors
        palette.Entries[0] = System.Drawing.Color.FromArgb(0, 0, 64, 128);
        palette.Entries[1] = System.Drawing.Color.FromArgb(0, 223, 233, 245);

        // Set the palette of the bitmap to the new palette 
        // Palette entries must be changed before assign the palette to the bitmap
        tiff.Palette = palette;

        // Save the new image with the new colorpalette
        tiff.Save(tiffPath, System.Drawing.Imaging.ImageFormat.Bmp);
    }

    File.Delete(tempPath);
}

static protected System.Drawing.Imaging.ColorPalette Create1bbPalette()
{
    Bitmap bitmap =
        new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
    System.Drawing.Imaging.ColorPalette palette = bitmap.Palette;
    bitmap.Dispose();
    return palette;
}
Download PDFRasterizer.NET 3.0
We will send you a download link
Why do we ask your email address?
We send tips that speed up your evaluation
We let you know about bug fixes
You can always unsubscribe with one click
We never share your address with a 3rd party
Thank you for your download

We have sent an email with a download link.