New to Telerik Document ProcessingStart a free 30-day trial

Invert PDF Document Colors

Updated on Feb 19, 2026
Product VersionProductAuthor
2021.1.322RadPdfProcessingMartin Velikov

Description

This article describes how to invert the background and text colors within a PDF document by iterating its content.

Solution

The provided code snippets demonstrates how to import a PDF document and invert its background and text color by iterating its content.

Import PDF file and Invert its Background and Content Color

csharp

	RadFixedDocument document;
	PdfFormatProvider provider = new PdfFormatProvider();
	using (Stream input = File.OpenRead(path))
	{
		document = provider.Import(input);
	}

	TextColor = RgbColors.White;
	BackGroundColor = RgbColors.Black;

	InvertBackgroundColor(document);
	InvertContentColor(document);

	string exportedDocument = "ExportedDocument6.pdf";
	if (File.Exists(exportedDocument))
	{
		File.Delete(exportedDocument);
	}

	using (Stream output = File.OpenWrite(exportedDocument))
	{
		provider.Export(document, output);
	}

As the PDF document has no background concept we are creating a RectangleGeometry using the page size and setting the desired color to it.

Invert Document's Background Color

csharp

	private static void InvertBackgroundColor(RadFixedDocument document)
	{
		foreach (RadFixedPage page in document.Pages)
		{
			Graphics.Path path = new Graphics.Path();
			path.Fill = BackGroundColor;
			Graphics.RectangleGeometry rectangle = new Graphics.RectangleGeometry(page.MediaBox);
			path.Geometry = rectangle;
			page.Content.Insert(0, path);
		}
	}

The following methods show how to invert the document elements' color by recursively iterating their content and setting the desired color using the relevant Fill property.

Invert Document Content`s Color

csharp

	private static void InvertContentColor(RadFixedDocument document)
	{
		foreach (RadFixedPage page in document.Pages)
		{
			InvertCollectionColors(page.Content);
		}
	}

	private static void InvertCollectionColors(ContentElementCollection contentElementCollection)
	{
		foreach (ContentElementBase contentElement in contentElementCollection)
		{
			if (contentElement is TextFragment textFragment)
			{
				textFragment.Fill = TextColor;
			}
			else if (contentElement is Graphics.Path path && path.Fill.Equals(TextColor))
			{
				path.Fill = BackGroundColor;
			}
			else if (contentElement is Form form)
			{
				InvertCollectionColors(form.FormSource.Content);
			}
		}
	}
In this article
DescriptionSolution
Not finding the help you need?
Contact Support