Recolor Red Strokes

PDF Modify Container Write

Demonstrates how to modify the stroke colors of shapes within a graphics container by detecting red strokes and recoloring them.

Сode Snippet

public static class Extensions
{
    public static bool IsRed(this Color color)
    {
        var rgbColor = (RgbColor)color.Convert(PixelFormat.Format24bppRgb);

        return rgbColor.R > (rgbColor.G + rgbColor.B);
    }
}

internal class RecolorRedStrokes
{
    public static void Run()
    {
        using (var reader = new PdfReader("GraphicsContainer.pdf"))
        using (var gc = reader.Frames[0].GetContent())
        using (var writer = new PdfWriter("GraphicsContainer_RecolorRedStrokes.pdf"))
        using (var gr = writer.GetGraphics())
        {
            writer.AddPage(gc.Width, gc.Height, gc.DpiX, gc.DpiY);

            foreach (var shapeItem in gc.Items.OfType<ShapeItem>())
            {
                if (shapeItem.Pen != null && shapeItem.Pen.Color.IsRed())
                {
                    shapeItem.Pen = new Pen(RgbColor.DarkMagenta, shapeItem.Pen.Width);
                }
            }

            gr.DrawContainer(gc, 0, 0);
        }
    }
}

Input

GraphicsContainer.pdf

Download

Output

GraphicsContainer_RecolorRedStrokes.pdf

Download

GraphicsContainer_RecolorRedStrokes.png

For AI-assisted development: Download Graphics Mill Code Samples XML Catalog