Redact Text in PDF: C# & .NET Guide

In the modern world, there is often a need to remove or hide confidential information from PDF documents before distributing them. This can be related to the protection of personal data, trade secrets, or other reasons. SautinSoft.Pdf provides a convenient set of tools for working with PDF documents, including the ability to hide text. In this article, we will look at how to hide text in a PDF document using C# and .NET.

  1. Add SautinSoft.Pdf from NuGet.
  2. Load a PDF document.
  3. Redact (delete) all words "North" from the 1st page.
  4. Draw green rectangles atop the all removed words.
  5. Save the document in PDF format.

Using SautinSoft.Pdf, you can easily hide any information in PDF documents, making it an indispensable tool for working with confidential data. By following the steps outlined above, you will be able to effectively manage the content of your PDF files.

Redact

Полный код

using System;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Redact
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/redact.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            string pdfFile = Path.GetFullPath(@"..\..\..\simple text.pdf");

            var document = PdfDocument.Load(pdfFile);
            {
                // Assume we want to redact the word "North".
                string textToRedact = "North";

                var page = document.Pages[0];
                var texts = page.Content.GetText().Find(textToRedact);
                
                foreach (var text in texts)
                {
                    text.Redact();
                    // If you want, draw a green rectangle 
                    // at the places where was the text.
                    var bounds = text.Bounds;
                    var rectangle = page.Content.Elements.AddPath().AddRectangle(new PdfPoint(bounds.Left, bounds.Bottom), new PdfSize(bounds.Width, bounds.Height));
                    rectangle.Format.Fill.IsApplied = true;
                    rectangle.Format.Fill.Color = PdfColor.FromRgb(0, 1, 0);
                }
                // Save PDF Document.
                document.Save("out.pdf");
            }
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("out.pdf") { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Redact
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/redact.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free license:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Dim pdfFile As String = Path.GetFullPath("..\..\..\simple text.pdf")

			Dim document = PdfDocument.Load(pdfFile)
			If True Then
				' Assume we want to redact the word "North".
				Dim textToRedact As String = "North"

				Dim page = document.Pages(0)
				Dim texts = page.Content.GetText().Find(textToRedact)

				For Each PdfText In texts
					PdfText.Redact()
					' If you want, draw a green rectangle 
					' at the places where was the text.
					Dim bounds = PdfText.Bounds
					Dim rectangle = page.Content.Elements.AddPath().AddRectangle(New PdfPoint(bounds.Left, bounds.Bottom), New PdfSize(bounds.Width, bounds.Height))
					rectangle.Format.Fill.IsApplied = True
					rectangle.Format.Fill.Color = PdfColor.FromRgb(0, 1, 0)
				Next PdfText
				' Save PDF Document.
				document.Save("out.pdf")
			End If
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("out.pdf") With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.