PDF: Удаление содержимого с PDF страницы. Метки редактирования.
В этом разделе
Процесс удаления содержимого из PDF страницы следует использовать для постоянного удаления конфиденциальной информации со страницы документа, например, для удаления некоторых конфиденциальных данных перед передачей документа третьим лицам. Функциональность может быть использована также для удаления выделенного текста.
Важно!
После удаления содержимого необходимо выполнить упаковку PDF документа (
PdfDocument.Pack), иначе удаленные данные могут быть восстановлены и извлечены!
Программное удаление содержимого с PDF страницы
VintaSoft PDF .NET Plug-in позволяет:
-
Затемненить изображения или области изображений на PDF странице
:
- Затемнение прямоугольника на изображении-ресурсе или встроенном изображении (PdfImageResource.ClearRect)
- Затемнение графического контура на изображении-ресурсе или встроенном изображении (PdfImageResource.ClearPath).
- Затемнение областей изображений на PDF странице (PdfPage.ClearImages).
- Затемнение изображения без изменения параметров сжатия изображения.
- Затемнение изображений-ресурсов и встроенных изображений.
-
Удалить текст с PDF страницы
:
- Удаление указанного текста с PDF страницы (PdfPage.RemoveText).
- Удаление текста из указанных областей PDF страницы (PdfPage.RemoveText).
- Алгоритм удаления текста сохраняет форматирование окружающего текста.
-
Удалить векторную графику с PDF страницы
:
-
Удалить аннотации с PDF страниц
:
-
Удалить любое содержимое (текст, изображения, векторную графику, аннотации) с PDF страницы.
(PdfPage.RemoveContentAndBlackOutResources):
- Удаление содержимого PDF страниц.
- Затемнение всех изображений, используемых на PDF странице.
- Удаление содержимого и затемните изображения во всех формах, используемых на PDF странице.
- Удаление всех аннотаций и появлений аннотаций с PDF страницы.
Вот C#/VB.NET код, который демонстрирует, как найти текст на PDF странице и удалить найденный текст с PDF страницы:
/// <summary>
/// Searches and removes specified text on all pages of PDF document.
/// </summary>
/// <param name="inputPdfFilename">The name of input PDF file.</param>
/// <param name="outputPdfFilename">The name of output PDF file.</param>
/// <param name="textToRemove">The text to remove.</param>
public static void TestFindAndRemoveTextOnAllPages(
string inputPdfFilename,
string outputPdfFilename,
params string[] textToRemove)
{
// open document
using (Vintasoft.Imaging.Pdf.PdfDocument document = new Vintasoft.Imaging.Pdf.PdfDocument(inputPdfFilename))
{
// if there is a text to remove
if (textToRemove.Length > 0)
{
// create a list that contains text regions to remove
System.Collections.Generic.List<Vintasoft.Imaging.Text.TextRegion> textRegions =
new System.Collections.Generic.List<Vintasoft.Imaging.Text.TextRegion>();
// for each page
foreach (Vintasoft.Imaging.Pdf.Tree.PdfPage page in document.Pages)
{
// clear a list of text regions to remove
textRegions.Clear();
// for all text strings that must be remove
for (int i = 0; i < textToRemove.Length; i++)
{
// search text string on PDF page
Vintasoft.Imaging.Text.TextRegion[] searchedText = SimpleTextSearchOnPdfPage(page, textToRemove[i]);
// if text is found
if (searchedText != null && searchedText.Length > 0)
// add searched text to a list of text for removing
textRegions.AddRange(searchedText);
}
// if PDF page contains text regions with text to remove
if (textRegions.Count > 0)
// remove text regions from PDF page
page.RemoveText(textRegions.ToArray());
}
}
// if names of source and destination files are the same
if (inputPdfFilename == outputPdfFilename)
// pack PDF document
document.Pack();
// if names of source and destination files are different
else
// pack source PDF document to specified file
document.Pack(outputPdfFilename);
}
}
/// <summary>
/// Searches a text string on PDF page.
/// </summary>
/// <param name="page">PDF page where text should be searched.</param>
/// <param name="text">Text to search.</param>
/// <returns>An array of text regions on PDF page where text was found.</returns>
public static Vintasoft.Imaging.Text.TextRegion[] SimpleTextSearchOnPdfPage(
Vintasoft.Imaging.Pdf.Tree.PdfPage page, string text)
{
System.Collections.Generic.List<Vintasoft.Imaging.Text.TextRegion> textRegions =
new System.Collections.Generic.List<Vintasoft.Imaging.Text.TextRegion>();
Vintasoft.Imaging.Text.TextRegion textRegion = null;
int startIndex = 0;
do
{
// search text
textRegion = page.TextRegion.FindText(text, ref startIndex, false);
// if text is found
if (textRegion != null)
{
// add searched text to a result
textRegions.Add(textRegion);
// shift start index
startIndex += textRegion.TextContent.Length;
}
} while (textRegion != null);
return textRegions.ToArray();
}
''' <summary>
''' Searches and removes specified text on all pages of PDF document.
''' </summary>
''' <param name="inputPdfFilename">The name of input PDF file.</param>
''' <param name="outputPdfFilename">The name of output PDF file.</param>
''' <param name="textToRemove">The text to remove.</param>
Public Shared Sub TestFindAndRemoveTextOnAllPages(inputPdfFilename As String, outputPdfFilename As String, ParamArray textToRemove As String())
' open document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(inputPdfFilename)
' if there is a text to remove
If textToRemove.Length > 0 Then
' create a list that contains text regions to remove
Dim textRegions As New System.Collections.Generic.List(Of Vintasoft.Imaging.Text.TextRegion)()
' for each page
For Each page As Vintasoft.Imaging.Pdf.Tree.PdfPage In document.Pages
' clear a list of text regions to remove
textRegions.Clear()
' for all text strings that must be remove
For i As Integer = 0 To textToRemove.Length - 1
' search text string on PDF page
Dim searchedText As Vintasoft.Imaging.Text.TextRegion() = SimpleTextSearchOnPdfPage(page, textToRemove(i))
' if text is found
If searchedText IsNot Nothing AndAlso searchedText.Length > 0 Then
' add searched text to a list of text for removing
textRegions.AddRange(searchedText)
End If
Next
' if PDF page contains text regions with text to remove
If textRegions.Count > 0 Then
' remove text regions from PDF page
page.RemoveText(textRegions.ToArray())
End If
Next
End If
' if names of source and destination files are the same
If inputPdfFilename = outputPdfFilename Then
' pack PDF document
document.Pack()
Else
' if names of source and destination files are different
' pack source PDF document to specified file
document.Pack(outputPdfFilename)
End If
End Using
End Sub
''' <summary>
''' Searches a text string on PDF page.
''' </summary>
''' <param name="page">PDF page where text should be searched.</param>
''' <param name="text">Text to search.</param>
''' <returns>An array of text regions on PDF page where text was found.</returns>
Public Shared Function SimpleTextSearchOnPdfPage(page As Vintasoft.Imaging.Pdf.Tree.PdfPage, text As String) As Vintasoft.Imaging.Text.TextRegion()
Dim textRegions As New System.Collections.Generic.List(Of Vintasoft.Imaging.Text.TextRegion)()
Dim textRegion As Vintasoft.Imaging.Text.TextRegion = Nothing
Dim startIndex As Integer = 0
Do
' search text
textRegion = page.TextRegion.FindText(text, startIndex, False)
' if text is found
If textRegion IsNot Nothing Then
' add searched text to a result
textRegions.Add(textRegion)
' shift start index
startIndex += textRegion.TextContent.Length
End If
Loop While textRegion IsNot Nothing
Return textRegions.ToArray()
End Function
Интерактивное удаление содержимого PDF страницы
VintaSoft PDF .NET Plug-in позволяет удалять содержимое визуально, используя PDF метки редактирования. PDF метка редактирования - это визуальный объект, определяющий область на PDF странице, откуда должно быть удалено содержимое.
Вот список поддерживаемых типов PDF меток редактирования:
Визуальный инструмент
PdfRemoveContentTool/
WpfPdfRemoveContentTool позволяет:
Вот C#/VB.NET код, который демонстрирует, как определить внешний вид PDF метки редактирования и применить PDF метки редактирования программно:
/// <summary>
/// Creates the redaction mark with custom appearance and applies the redaction mark
/// to PDF page.
/// </summary>
public static void TestRedactionMarkAppearance(Vintasoft.Imaging.UI.ImageViewer viewer)
{
// if image viewer does not have image
if (viewer.Image == null)
throw new System.InvalidOperationException();
// if image viewer contains not PDF page
Vintasoft.Imaging.Pdf.Tree.PdfPage page =
Vintasoft.Imaging.Pdf.PdfDocumentController.GetPageAssociatedWithImage(viewer.Image);
if (page == null)
throw new System.InvalidOperationException();
// create and set PdfRemoveContentTool as current tool of image viewer
Vintasoft.Imaging.Pdf.UI.PdfRemoveContentTool removeContentTool =
new Vintasoft.Imaging.Pdf.UI.PdfRemoveContentTool();
viewer.VisualTool = removeContentTool;
// create the redaction mark
Vintasoft.Imaging.Pdf.UI.RedactionMark mark =
new Vintasoft.Imaging.Pdf.UI.RedactionMark(viewer.Image);
// specify that redaction mark must remove all PDF content
mark.MarkType = Vintasoft.Imaging.Pdf.PdfRedactionMarkType.RemoveAll;
// calculate and specify the redaction mark rectangle
System.Drawing.RectangleF rect = page.MediaBox;
rect.Inflate(-rect.Width / 4, -rect.Height / 4);
mark.SelectedRect = rect;
// add the redaction mark to a list of redaction marks of visual tool
removeContentTool.Add(mark);
// create redaction mark appearance
Vintasoft.Imaging.Pdf.Drawing.GraphicsFigures.TextBoxFigure textBox =
new Vintasoft.Imaging.Pdf.Drawing.GraphicsFigures.TextBoxFigure(
new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Red),
"TOP SECRET",
page.Document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.Helvetica),
0);
textBox.TextAlignment = Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Center;
textBox.Brush = new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black);
textBox.AutoFontSize = true;
removeContentTool.RedactionMarkAppearance = textBox;
// apply redaction marks
removeContentTool.ApplyRedactionMarks();
}
''' <summary>
''' Creates the redaction mark with custom appearance and applies the redaction mark
''' to PDF page.
''' </summary>
Public Shared Sub TestRedactionMarkAppearance(viewer As Vintasoft.Imaging.UI.ImageViewer)
' if image viewer does not have image
If viewer.Image Is Nothing Then
Throw New System.InvalidOperationException()
End If
' if image viewer contains not PDF page
Dim page As Vintasoft.Imaging.Pdf.Tree.PdfPage = Vintasoft.Imaging.Pdf.PdfDocumentController.GetPageAssociatedWithImage(viewer.Image)
If page Is Nothing Then
Throw New System.InvalidOperationException()
End If
' create and set PdfRemoveContentTool as current tool of image viewer
Dim removeContentTool As New Vintasoft.Imaging.Pdf.UI.PdfRemoveContentTool()
viewer.VisualTool = removeContentTool
' create the redaction mark
Dim mark As New Vintasoft.Imaging.Pdf.UI.RedactionMark(viewer.Image)
' specify that redaction mark must remove all PDF content
mark.MarkType = Vintasoft.Imaging.Pdf.PdfRedactionMarkType.RemoveAll
' calculate and specify the redaction mark rectangle
Dim rect As System.Drawing.RectangleF = page.MediaBox
rect.Inflate(-rect.Width / 4, -rect.Height / 4)
mark.SelectedRect = rect
' add the redaction mark to a list of redaction marks of visual tool
removeContentTool.Add(mark)
' create redaction mark appearance
Dim textBox As New Vintasoft.Imaging.Pdf.Drawing.GraphicsFigures.TextBoxFigure(New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Red), "TOP SECRET", page.Document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.Helvetica), 0)
textBox.TextAlignment = Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Center
textBox.Brush = New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black)
textBox.AutoFontSize = True
removeContentTool.RedactionMarkAppearance = textBox
' apply redaction marks
removeContentTool.ApplyRedactionMarks()
End Sub
Приложение PDF Editor Demo
Приложение PDF Editor Demo и WPF Pdf Editor Demo содержит пример использования визуального инструмента
PdfRemoveContentTool, который позволяет:
- создавать, редактировать, удалять метки PDF редактирования
- изменять размер и расположение PDF меток редактирования
- наносить PDF метки редактирования (удаление содержимого)
- настроить параметры объекта, нарисованного на месте PDF метки редактирования, после ее применения.
Ниже можно увидеть скриншот удаления PDF содержимого с помощью визуального инструмента
PdfRemoveContentTool. На месте удаленного PDF содержимого ничего не появится:
Ниже можно увидеть скриншот удаления PDF содержимого с помощью визуального инструмента
PdfRemoveContentTool. На месте удаленного PDF содержимого появится черный прямоугольник с красным текстом: