Change the color inside a PDF

This code sample shows how to change color in a PDF using C# and VB.NET.

PDF before changing color

Black And White PDF

PDF after changing color

PDF After Converting Black And White PDF To Color

The code sample extracts all the graphics on the original page as a tree of shape objects. It traverses the tree and changes color properties of a selection of shape objects. It then creates a new PDF document from the modified shapes.

The text shapes are modified by setting the Brush property to blue. The brush is used to fill the interior of the glyphs.

The freehand shapes (paths) are modified by setting the Pen property to green and the Brush property to purple. This makes all the lines green and all the fills purple.

The image shapes require a different approach since they have no pen or brush. We extract the GDI+ bitmap and transform the colors using the color matrix. Next we create a new image shape from the transformed bitmap and replace the original image shape. The color matrix is quite versatile. By using different matrices you can implement e.g. a sepia tone or a negative filter. Read more.

Here is the code:

static void Main(string[] args)
{
    using (FileStream fileIn = new FileStream(@"..\..\..\inputDocuments\SellingYourHome.pdf", FileMode.Open, FileAccess.Read))
    {
        Document pdfIn = new Document(fileIn);
        Document pdfOut = ChangeColor(pdfIn);
        using (FileStream fileOut = new FileStream(@"..\..\out.pdf", FileMode.Create, FileAccess.Write))
        {
            pdfOut.Write(fileOut);
        }
    }
}


//
// Changes the color of all pages in one PDF document
//
static Document ChangeColor(Document pdf)
{
    Document pdfOut = new Document();

    foreach (Page page in pdf.Pages)
    {
        pdfOut.Pages.Add(ChangeColor(page));
    }

    return pdfOut;
}


//
// Changes the color of all shapes in one PDF page
//
static Page ChangeColor(Page page)
{
    Page newPage = new Page(page.Width, page.Height)
                        {
                            Orientation = page.Orientation
                        };
    ShapeCollection shapes = page.CreateShapes();
    ChangeColor(shapes);
    newPage.Overlay.Add(shapes);

    return newPage;
}


//
// This tries to find the type of a shape and chooses one of the ways to change the color
//
static void ChangeColor(ShapeCollection shapes)
{
    for (var i = 0; i < shapes.Count; i++)
    {
        Shape shape = shapes[i];

        if (shape is ShapeCollection)
        {
            // recurse
            ChangeColor(shape as ShapeCollection);
        }
        else if (shape is ImageShape)
        {
            shapes.RemoveAt(i);
            var newShape = ChangeColor(shape as ImageShape);
            shapes.Insert(i, newShape);
        }
        else if (shape is TextShape)
        {
            shapes.RemoveAt(i);
            var newShape = ChangeColor(shape as TextShape);
            shapes.Insert(i, newShape);
        }
        else if (shape is FreeHandShape)
        {
            shapes.RemoveAt(i);
            var newShape = ChangeColor(shape as FreeHandShape);
            shapes.Insert(i, newShape);
        }
        else
        {
            // other types of shapes remain the same in this code sample
        }
    }
}


//
// Change the color of a Text Shape
// All text will be colored blue
//
static TextShape ChangeColor(TextShape shape)
{
    RgbColor color = new RgbColor(0.00, 0.00, 255.00);
    shape.Brush = new TallComponents.PDF.Brushes.SolidBrush(color);

    return shape;
}


//
// Change the color of a freehandshape (like the horizontal lines)
// these will be colored with a green brush and a purple pen
//
static FreeHandShape ChangeColor(FreeHandShape shape)
{
    RgbColor brushColor = new TallComponents.PDF.Colors.RgbColor(192.00, 0.00, 192.00);
    shape.Brush = new TallComponents.PDF.Brushes.SolidBrush(brushColor);

    RgbColor penColor = new TallComponents.PDF.Colors.RgbColor(128.00, 255.00, 0.00);
    shape.Pen = new TallComponents.PDF.Pens.Pen(penColor);

    return shape;
}


//
// Change the color of a image
// these will be colored red using a color matrix
//
// Note:
// The color matrix is quite versatile. By using different matrices you can implement
// e.g. a sepia tone or a negative filter
//
// Sepia filter:
//  var colorMatrix = new ColorMatrix( new float[][]
//             {
//               new float[]{0.393f, 0.349f, 0.272f, 0.000f, 0.000f},
//               new float[]{0.769f, 0.686f, 0.534f, 0.000f, 0.000f},
//               new float[]{0.189f, 0.168f, 0.131f, 0.000f, 0.000f},
//               new float[]{0.000f, 0.000f, 0.000f, 1.000f, 0.000f},
//               new float[]{0.000f, 0.000f, 0.000f, 0.000f, 1.000f}
//             }
//
// Negative filter
//  var colorMatrix = new ColorMatrix( new float[][]
//             {
//               new float[]{-1,  0,  0,  0,  0},
//               new float[]{ 0, -1,  0,  0,  0},
//               new float[]{ 0,  0, -1,  0,  0},
//               new float[]{ 0,  0,  0,  1,  0},
//               new float[]{ 1,  1,  1,  1,  1}
//             }
//
static ImageShape ChangeColor(ImageShape image)
{
    int height = (int)image.VerticalSize;
    int width = (int)image.HorizontalSize;

    using (Bitmap bitmap = image.CreateBitmap())
    {
        Bitmap newBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
        using (Graphics graphics = Graphics.FromImage(newBitmap))
        {
            // Info on this color matrix can be found here:
            // See http://msdn.microsoft.com/library/ys160710.aspx
            ColorMatrix colorMatrix = new ColorMatrix(new float[][]
                {
                    new float[]{   1,  0,  0,  0,  0},
                    new float[]{   0,  1,  0,  0,  0},
                    new float[]{   0,  0,  1,  0,  0},
                    new float[]{   0,  0,  0,  1,  0},
                    new float[]{0.75f, 0,  0,  0,  1}
                });

            ImageAttributes imageAttributes = new ImageAttributes();
            imageAttributes.SetColorMatrix(colorMatrix);

            graphics.DrawImage(bitmap,
                                new System.Drawing.Rectangle(0, 0, width, height), // dest
                                0,      // X-upper left corner of the source
                                0,      // Y-upper left corner of the source
                                width,  // Width of the source
                                height, // Height of the source
                                GraphicsUnit.Pixel,
                                imageAttributes);
        }

        ImageShape changedImage = new ImageShape(newBitmap, true)
                                {
                                    Compression = Compression.Jpeg,
                                    Width = image.Width,
                                    Height = image.Height,
                                    Transform = image.Transform,
                                    Opacity = image.Opacity,
                                    BlendMode = image.BlendMode
                                };
        return changedImage;
    }
}
Shared Sub Main()
    Using fileIn As FileStream = New FileStream("..\..\..\inputDocuments\SellingYourHome.pdf", FileMode.Open, FileAccess.Read)
        Dim pdfIn As Document
        Dim pdfOut As Document

        pdfIn = New Document(fileIn)
        pdfOut = ChangeColor(pdfIn)
        Using fileOut As FileStream = New FileStream("..\..\out.pdf", FileMode.Create, FileAccess.Write)
            pdfOut.Write(fileOut)
        End Using
    End Using
End Sub


'
' Changes the color of all pages in one PDF document
'
Private Shared Function ChangeColor(pdf As Document) As Document
    Dim pdfOut As Document

    pdfOut = New Document()
    For Each page As Page In pdf.Pages
        pdfOut.Pages.Add(ChangeColor(page))
    Next

    Return pdfOut
End Function


'
' Changes the color of all shapes in one PDF page
'
Private Shared Function ChangeColor(page As Page) As Page
    Dim newPage As Page
    Dim shapes As ShapeCollection

    newPage = New Page(page.Width, page.Height)
    newPage.Orientation = page.Orientation
    shapes = page.CreateShapes()
    ChangeColor(shapes)
    newPage.Overlay.Add(shapes)

    Return newPage
End Function


'
' This tries to find the type of a shape and chooses one of the ways to change the color
'
Private Shared Sub ChangeColor(shapes As ShapeCollection)
    Dim shape As Shape

    For i As Integer = 0 To shapes.Count - 1
        shape = shapes(i)

        If TypeOf shape Is ShapeCollection Then
            ' recurse
            ChangeColor(TryCast(shape, ShapeCollection))

        ElseIf TypeOf shape Is ImageShape Then
            Dim newShape As ImageShape
            shapes.RemoveAt(i)
            newShape = ChangeColor(TryCast(shape, ImageShape))
            shapes.Insert(i, newShape)

        ElseIf TypeOf shape Is TextShape Then
            Dim newShape As TextShape
            shapes.RemoveAt(i)
            newShape = ChangeColor(TryCast(shape, TextShape))
            shapes.Insert(i, newShape)

        ElseIf TypeOf shape Is FreeHandShape Then
            Dim newShape As FreeHandShape
            shapes.RemoveAt(i)
            newShape = ChangeColor(TryCast(shape, FreeHandShape))
            shapes.Insert(i, newShape)

        Else
            ' other types of shapes remain the same in this code sample
        End If
    Next
End Sub


'
' Change the color of a Text Shape
' All text will be colored blue
'
Private Shared Function ChangeColor(shape As TextShape) As TextShape
    Dim color As TallComponents.PDF.Colors.RgbColor

    color = New TallComponents.PDF.Colors.RgbColor(0.0, 0.0, 255.0)
    shape.Brush = New TallComponents.PDF.Brushes.SolidBrush(color)

    Return shape
End Function


'
' Change the color of a freehandshape (like the horizontal lines)
' these will be colored with a green brush and a purple pen
'
Private Shared Function ChangeColor(shape As FreeHandShape) As FreeHandShape
    Dim brushColor As TallComponents.PDF.Colors.RgbColor
    Dim penColor As TallComponents.PDF.Colors.RgbColor

    brushColor = New TallComponents.PDF.Colors.RgbColor(192.0, 0.0, 192.0)
    shape.Brush = New TallComponents.PDF.Brushes.SolidBrush(brushColor)
    penColor = New TallComponents.PDF.Colors.RgbColor(128.0, 255.0, 0.0)
    shape.Pen = New TallComponents.PDF.Pens.Pen(penColor)

    Return shape
End Function


'
' Change the color of a image
' these will be colored red using a color matrix
'
'    
' Change the color of a image
' these will be colored red using a color matrix
'
' Note:
' The color matrix is quite versatile. By using different matrices you can implement
' e.g. a sepia tone or a negative filter
'
' Sepia filter:
'  var colorMatrix = new ColorMatrix( new float[][]
'             {
'               new float[]{0.393f, 0.349f, 0.272f, 0.000f, 0.000f},
'               new float[]{0.769f, 0.686f, 0.534f, 0.000f, 0.000f},
'               new float[]{0.189f, 0.168f, 0.131f, 0.000f, 0.000f},
'               new float[]{0.000f, 0.000f, 0.000f, 1.000f, 0.000f},
'               new float[]{0.000f, 0.000f, 0.000f, 0.000f, 1.000f}
'             }
'
' Negative filter:
'  var colorMatrix = new ColorMatrix( new float[][]
'             {
'               new float[]{-1,  0,  0,  0,  0},
'               new float[]{ 0, -1,  0,  0,  0},
'               new float[]{ 0,  0, -1,  0,  0},
'               new float[]{ 0,  0,  0,  1,  0},
'               new float[]{ 1,  1,  1,  1,  1}
'             }
'

Private Shared Function ChangeColor(image As ImageShape) As ImageShape
    Dim height As Integer
    Dim width As Integer

    height = CInt(image.VerticalSize)
    width = CInt(image.HorizontalSize)

    Using bitmap As Bitmap = image.CreateBitmap()
        Dim newBitmap As Bitmap
        Dim changedImage As ImageShape

        newBitmap = New Bitmap(width, height, PixelFormat.Format32bppArgb)
        Using graphics__1 As Graphics = Graphics.FromImage(newBitmap)
            Dim colorMatrix As ColorMatrix
            Dim imageAttributes As ImageAttributes

            ' Info on this color matrix can be found here:
            ' See http://msdn.microsoft.com/library/ys160710.aspx
            colorMatrix = New ColorMatrix(New Single()() _
                                { _
                                    New Single() {1, 0, 0, 0, 0}, _
                                    New Single() {0, 1, 0, 0, 0}, _
                                    New Single() {0, 0, 1, 0, 0}, _
                                    New Single() {0, 0, 0, 1, 0}, _
                                    New Single() {0.75F, 0, 0, 0, 1} _
                                })

            imageAttributes = New ImageAttributes()
            imageAttributes.SetColorMatrix(colorMatrix)

            ' dest
            ' X-upper left corner of the source
            ' Y-upper left corner of the source
            ' Width of the source
            ' Height of the source
            graphics__1.DrawImage(bitmap,
                                    New System.Drawing.Rectangle(0, 0, width, height),
                                    0,
                                    0,
                                    width,
                                    height,
                                    GraphicsUnit.Pixel,
                                    imageAttributes)
        End Using

        changedImage = New ImageShape(newBitmap, True) With _
                                    { _
                                        .Compression = Compression.Jpeg, _
                                        .Width = image.Width, _
                                        .Height = image.Height, _
                                        .Transform = image.Transform, _
                                        .Opacity = image.Opacity, _
                                        .BlendMode = image.BlendMode _
                                    }
        Return changedImage
    End Using
End Function