PDF Redaction in C#: Remove Sensitive Data and Sanitize Documents with IronPDF
C# .NET ile IronPDF'de PDF redaksiyonu, bir belgenin iç yapısından hassas içeriği kalıcı olarak kaldırır, sadece görsel olarak kapatmaz, böylece hiçbir kopyalama, arama veya adli analiz, orijinal veriyi geri getiremez. Bu, metin üzerindeki kara dikdörtgenlerden çok ileride: IronPDF, regex desen eşleştirme ile metin redaksiyonu, imzalar ve görüntüler için bölge tabanlı redaksiyon, meta veri temizleme, gömülü betikleri ortadan kaldırmak için belge temizliği ve güvenlik taraması sağlar, .NET geliştiricilerine HIPAA, GDPR ve PCI DSS uyumlu belge koruma iş akışları için eksiksiz bir araç seti sunar.
Kısa Başlangıç Rehberi
Bu öğretici, C# .NET ile PDF belgelerinden hassas içeriğin kalıcı olarak kaldırılması, metin desenleri, resim bölgeleri, meta veriler ve gömülü betikler konularını kapsar.
- Bu, kimler için: Sağlık, hukuk, finans veya devlet bağlamlarında hassas belgelerle ilgilenen .NET geliştiriciler.
- Ne yapacaksınız: Regex desen eşleştirme (SSN'ler, kredi kartları, e-postalar) ile metin redaksiyonu, imzalar ve fotoğraflar için koordinat tabanlı bölge redaksiyonu, meta veri temizleme, gömülü betikleri sıyırmak için PDF temizliği ve YARA tabanlı güvenlik taraması.
- Nerede çalışır: .NET 10, .NET 8 LTS, .NET Framework 4.6.2+ ve .NET Standard 2.0. Tüm işlemler, dış bağımlılıklar olmadan yerel olarak yürütülür.
- Bu yaklaşımı ne zaman kullanmalısınız: Belgeleri yasal keşif, FOIA talepleri veya dış dağıtım için paylaşmanız gerektiğinde ve kaldırılmış içeriğin gerçekten gitmiş olduğundan emin olmanız gerektiğinde.
- Teknik olarak neden önemlidir: Görsel örtü, orijinal metni PDF'nin içerik akışlarında kurtarılabilir bırakır. IronPDF'in redaksiyonu, karakter verilerini belgenin yapısından siler, böylece kurtarma imkansız hale gelir.
PDF'den hassas metni sadece birkaç satır kodla redakte edin:
-
NuGet Paket Yöneticisi ile https://www.nuget.org/packages/IronPdf yükleyin
PM > Install-Package IronPdf -
Bu kod parçasını kopyalayıp çalıştırın.
using IronPdf; PdfDocument pdf = PdfDocument.FromFile("confidential-report.pdf"); pdf.RedactTextOnAllPages("CONFIDENTIAL"); pdf.SaveAs("redacted-report.pdf"); -
Canlı ortamınızda test etmek için dağıtın
Bugün projenizde IronPDF kullanmaya başlayın ücretsiz deneme ile
IronPDF'nin 30 günlük deneme sürümünü satın aldıktan veya kaydolduktan sonra, uygulamanızın başlangıcında lisans anahtarınızı ekleyin.
IronPdf.License.LicenseKey = "KEY";
IronPdf.License.LicenseKey = "KEY";
Imports IronPdf
IronPdf.License.LicenseKey = "KEY"
!{--0100110001001001010000100101001001000001010100100101100101011111--}
İçindekiler
- Ozet: Hizli Başlangic Rehberi
- PDF Belgelerinden Metin Redaksiyonu
- Desen Eşleştirme ve Otomatik Redaksiyon
- Bölge Tabanlı Redaksiyon
- PDF Meta Verilerinden Hassas Verileri Kaldırma
- .NET'te PDF Temizleme
- Tam İş Akışları
- Sonraki Adımlar
Gerçek Redaksiyon ile Görsel Örtü Arasındaki Fark Nedir?
Gerçek redaksiyon ile görsel örtü arasındaki ayrımı anlamak, hassas belgelerle ilgilenen herkes için kritiktir. Birçok araç ve manuel yöntem, temel verileri fiilen kaldırmadan redaksiyon görünümü yaratır. Bu yanlış güvenlik duygusu, birçok yüksek profilli veri ihlaline ve uyum hatasına neden olmuştur.
Görsel örtü yaklaşımları, tipik olarak hassas içerik üzerine opak şekiller çizer. Metin, PDF yapısında tam olarak sağlam kalır. Belgeyi görüntüleyen biri siyah bir dikdörtgen görür, ancak orijinal karakterler hala dosyanın içerik akışlarında mevcuttur. Sayfadaki tüm metni seçmek, erişilebilirlik araçlarını kullanmak veya ham PDF verilerini incelemek, gizlenmiş olduğu düşünülen her şeyi ortaya çıkarır. Dava dosyaları, redaksiyon yapılmış dosyaların karşı tarafça zahmetsizce unredakte edildiği zamanlar tehlikeye girmiştir. Devlet ajansları, sansürlendikleri görünen ancak tamamen kurtarılabilir sınıflandırılmış bilgileri yanlışlıkla yayınladı.
Gerçek redaksiyon farklı çalışır. IronPDF'in redaksiyon yöntemlerini kullandığınızda, kütüphane, belirtilen metni PDF'nin iç yapısında bulur ve tamamen çıkarır. Karakter verileri, içerik akışlarından silinir. Görsel temsil, tipik olarak siyah bir dikdörtgen olan bir redaksiyon işareti ile değiştirilir, ancak orijinal içerik dosyada artık hiçbir yerde mevcut değildir. Seçim, kopyalama veya adli analiz, kalıcı olarak silinmiş olanı kurtaramaz.
IronPDF, PDF'yi yapısal düzeyde değiştirerek gerçek redaksiyon gerçekleştirir. RedactTextOnAllPages yöntemi ve varyantları sayfa içeriğini arar, eşleşen metni belirler, belge nesne modelinden kaldırır ve isteğe bağlı olarak içeriğin göründüğü yerde görsel bir gösterge çizer. Bu yaklaşım, NIST gibi kuruluşların güvenli belge redaksiyonu için yönergeleri ile uyumludur.
Pratik sonuçları oldukça önemlidir. Belgeleri dışa aktarmanız, dosyaları yasal keşif için göndermeniz, bilgi özgürlüğü taleplerine göre kayıtları yayınlamanız veya kişisel olarak tanımlanabilir bilgileri korurken raporları dağıtmanız gerekiyorsa, sadece gerçek redaksiyon yeterli koruma sağlar. Görsel örtüler, yalnızca belirli bölümlerden dikkati uzaklaştırmak istediğiniz iç taslaklar için yeterli olabilir, ancak gerçek veri koruması için asla güvenilmemelidir. Ek belge güvenlik önlemleri için PDF'leri şifreleme ve dijital imzalar hakkındaki kılavuzlarımızı inceleyin.
How do I Redact PDF Text in C# Across an Entire Document?
En yaygın redaksiyon senaryosu, bir belgede belirli metin örneklerinin tümünü kaldırmayı içerir. Belki bir rapordan bir kişinin adını çıkarmanız, mali tabloların hesap numaralarını kaldırmanız ya da dış dağıtım öncesi dahili referans kodlarını sıyırmanız gerekebilir. IronPDF, bu işlemi RedactTextOnAllPages yöntemiyle kolaylaştırır.
Giriş
İsimler, Sosyal Güvenlik numaraları ve çalışan kimlikleri dahil olmak üzere kişisel bilgiler içeren bir çalışan kayıtları belgesi.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/redact-text-all-pages.cs
using IronPdf;
// Load the source document
PdfDocument pdf = PdfDocument.FromFile("employee-records.pdf");
// Redact an employee name from the entire document
pdf.RedactTextOnAllPages("John Smith");
// Redact a Social Security Number
pdf.RedactTextOnAllPages("123-45-6789");
// Redact an internal employee ID
pdf.RedactTextOnAllPages("EMP-2024-0042");
// Save the cleaned document
pdf.SaveAs("employee-records-redacted.pdf");
Imports IronPdf
' Load the source document
Dim pdf As PdfDocument = PdfDocument.FromFile("employee-records.pdf")
' Redact an employee name from the entire document
pdf.RedactTextOnAllPages("John Smith")
' Redact a Social Security Number
pdf.RedactTextOnAllPages("123-45-6789")
' Redact an internal employee ID
pdf.RedactTextOnAllPages("EMP-2024-0042")
' Save the cleaned document
pdf.SaveAs("employee-records-redacted.pdf")
Bu kod, çalışan bilgilerini içeren bir PDF'yi yükler ve her bir değer için RedactTextOnAllPages çağrısı yaparak üç parça gizli veriyi kaldırır. Her çağrı, belgede her sayfayı arar ve çalışanın adı, Sosyal Güvenlik numarası ve dahili tanımlayıcısı ile eşleşen tüm örnekleri kalıcı olarak kaldırır.
Örnek Çıktı
Varsayılan davranış, belgenin yapısındaki gerçek karakterleri yıldızlarla değiştirirken, redakte edilmiş metnin göründüğü yerlerde siyah dikdörtgenler çizer. Bu, redaksiyonun meydana geldiğini görsel olarak onaylar ve orijinal içeriğin tamamen gitmiş olmasını sağlar.
Daha uzun belgelerle veya birden fazla redaksiyon hedefi ile çalışırken bu çağrıları verimli bir şekilde zincirleyebilirsiniz:
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/redact-text-list.cs
using IronPdf;
using System.Collections.Generic;
// Load the document once
PdfDocument pdf = PdfDocument.FromFile("quarterly-report.pdf");
// Define all terms that need redaction
List<string> sensitiveTerms = new List<string>
{
"Project Titan",
"Sarah Johnson",
"Budget: $4.2M",
"Q3-INTERNAL-2024",
"sarah.johnson@company.com"
};
// Redact each term
foreach (string term in sensitiveTerms)
{
pdf.RedactTextOnAllPages(term);
}
// Save the result
pdf.SaveAs("quarterly-report-public.pdf");
Imports IronPdf
Imports System.Collections.Generic
' Load the document once
Dim pdf As PdfDocument = PdfDocument.FromFile("quarterly-report.pdf")
' Define all terms that need redaction
Dim sensitiveTerms As New List(Of String) From {
"Project Titan",
"Sarah Johnson",
"Budget: $4.2M",
"Q3-INTERNAL-2024",
"sarah.johnson@company.com"
}
' Redact each term
For Each term As String In sensitiveTerms
pdf.RedactTextOnAllPages(term)
Next
' Save the result
pdf.SaveAs("quarterly-report-public.pdf")
Bu desen, kaldırılacak hassas değerlerin bilinen bir listesini bulundurduğunuzda iyi çalışır. Belge bir kez yüklenir, tüm redaksiyonlar hafızada uygulanır ve nihai sonuç kaydedilir. Her terim, bağımsız olarak işlenir, böylece terimler arasındaki kısmi eşleşmeler veya biçim farklılıkları diğer redaksiyonları etkilemez.
Belirli Sayfalardaki Metni Yalnızca Nasıl Redakte Edebilirim?
Bazen redaksiyonların nerede meydana geldiği üzerinde daha hassas kontrol sahibi olmanız gerekir. Bir belgenin, sağlam kalması gereken bilgiler içeren bir kapak sayfası olabilir veya gizli verilerin yalnızca belirli bölümlerde yer aldığını biliyor olabilirsiniz. IronPDF, tek sayfa için RedactTextOnPage ve belirli birden fazla sayfa için hedefleme yapıldığında ise RedactTextOnPages sunar.
Giriş
Müşteri adlarının imza sayfasında ve mali koşulların belgenin çeşitli sayfalarında göründüğü çok sayfalı bir sözleşme demeti.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/redact-specific-pages.cs
using IronPdf;
// Load the document
PdfDocument pdf = PdfDocument.FromFile("contract-bundle.pdf");
// Redact text only on page 1 (index 0)
pdf.RedactTextOnPage(0, "Client Name: Acme Corporation");
// Redact text on pages 3, 5, and 7 (indices 2, 4, 6)
int[] financialPages = { 2, 4, 6 };
pdf.RedactTextOnPages(financialPages, "Payment Terms: Net 30");
// Other pages remain untouched except for the specific redactions applied
pdf.SaveAs("contract-bundle-redacted.pdf");
Imports IronPdf
' Load the document
Dim pdf As PdfDocument = PdfDocument.FromFile("contract-bundle.pdf")
' Redact text only on page 1 (index 0)
pdf.RedactTextOnPage(0, "Client Name: Acme Corporation")
' Redact text on pages 3, 5, and 7 (indices 2, 4, 6)
Dim financialPages As Integer() = {2, 4, 6}
pdf.RedactTextOnPages(financialPages, "Payment Terms: Net 30")
' Other pages remain untouched except for the specific redactions applied
pdf.SaveAs("contract-bundle-redacted.pdf")
Bu kod, tek sayfa için RedactTextOnPage ve belirli birden fazla sayfa için RedactTextOnPages kullanarak hedefli gizleme işlemini gösterir. Müşteri adı yalnızca sayfa 1 (indeks 0) dan kaldırılırken, ödeme koşulları sayfaları 3, 5 ve 7'den (dizinler 2, 4, 6) redakte edilmiştir, diğer tüm sayfalar el değmeden kalır.
Örnek Çıktı
IronPDF'deki sayfa dizinleri sıfır tabanlıdır, yani ilk sayfa indeks 0, ikinci indeks 1 ve bu böyle devam eder. Bu standart programlama gelenekleriyle eşleşir ve çoğu geliştiricinin dizi erişimi hakkında düşünme şekliyle uyumludur.
Belirli sayfaları hedeflemek büyük belgeleri işlerken performansı artırır. Yalnızca birkaç yerde görünen metni taramak yerine yüzlerce sayfayı aramak yerine, redaksiyon motorunu tam arayacak yere yönlendirebilirsiniz. Bu, binlerce belgeyle uğraşabileceğiniz toplu işleme senaryoları için önemlidir. Maksimum verimlilik için asenkron ve çoklu iş parçacığı teknikleri kullanmayı düşünün.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/redact-large-document.cs
using IronPdf;
// Process a large document efficiently
PdfDocument pdf = PdfDocument.FromFile("annual-report-500-pages.pdf");
// We know from document structure that:
// - Executive summary with names is on pages 1-3
// - Financial data is on pages 45-60
// - Appendix with employee info is on pages 480-495
// Redact executive names from summary section
for (int i = 0; i <= 2; i++)
{
pdf.RedactTextOnPage(i, "CEO: Robert Williams");
pdf.RedactTextOnPage(i, "CFO: Maria Garcia");
}
// Redact specific financial figures from the financial section
int[] financialSection = { 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 };
pdf.RedactTextOnPages(financialSection, "Net Revenue: $847M");
// Redact employee identifiers from appendix
for (int i = 479; i <= 494; i++)
{
pdf.RedactTextOnPage(i, "Employee ID:");
}
pdf.SaveAs("annual-report-public-release.pdf");
Imports IronPdf
' Process a large document efficiently
Dim pdf As PdfDocument = PdfDocument.FromFile("annual-report-500-pages.pdf")
' We know from document structure that:
' - Executive summary with names is on pages 1-3
' - Financial data is on pages 45-60
' - Appendix with employee info is on pages 480-495
' Redact executive names from summary section
For i As Integer = 0 To 2
pdf.RedactTextOnPage(i, "CEO: Robert Williams")
pdf.RedactTextOnPage(i, "CFO: Maria Garcia")
Next
' Redact specific financial figures from the financial section
Dim financialSection As Integer() = {44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59}
pdf.RedactTextOnPages(financialSection, "Net Revenue: $847M")
' Redact employee identifiers from appendix
For i As Integer = 479 To 494
pdf.RedactTextOnPage(i, "Employee ID:")
Next
pdf.SaveAs("annual-report-public-release.pdf")
Bu hedefli yaklaşım, 500 sayfalık bir belgenin yalnızca ilgili bölümlerini işler, her bir redaksiyon terimi için her sayfanın taranmasına kıyasla yürütme süresini önemli ölçüde azaltır.
Redakte Edilen İçeriğin Görünümünü Nasıl Özelleştirebilirim?
IronPDF, nihai belgede redaksiyonların nasıl görüneceğini kontrol etmek için birkaç parametre sunar. Büyük/küçük harf duyarlılığını, tam kelime eşleşmesini, görsel dikdörtgenlerin çizilip çizilmeyeceğini ve redakte edilmiş içeriğin yerine hangi metnin ortaya çıkacağını ayarlayabilirsiniz.
Giriş
Gizli terimler de dahil olmak üzere çeşitli sınıflandırma etiketleri, parolalar ve dahili referans kodları içeren, farklı redaksiyon tedavileri gerektiren bir hukuk özeti.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/customize-redaction-appearance.cs
using IronPdf;
// Load the document
PdfDocument pdf = PdfDocument.FromFile("legal-brief.pdf");
// Case-sensitive redaction: only matches exact case
// "CLASSIFIED" will be redacted but "classified" or "Classified" will not
pdf.RedactTextOnAllPages(
"CLASSIFIED",
CaseSensitive: true,
OnlyMatchWholeWords: true,
DrawRectangles: true,
ReplacementText: "[REDACTED]"
);
// Case-insensitive redaction: matches regardless of case
// Will redact "Secret", "SECRET", "secret", etc.
pdf.RedactTextOnAllPages(
"secret",
CaseSensitive: false,
OnlyMatchWholeWords: true,
DrawRectangles: true,
ReplacementText: "*****"
);
// Whole word disabled: matches partial strings too
// Will redact "password", "passwords", "mypassword123", etc.
pdf.RedactTextOnAllPages(
"password",
CaseSensitive: false,
OnlyMatchWholeWords: false,
DrawRectangles: true,
ReplacementText: "XXXXX"
);
// No visual rectangle: text is removed but no black box appears
// Useful when you want seamless removal without obvious redaction marks
pdf.RedactTextOnAllPages(
"internal-reference-code",
CaseSensitive: true,
OnlyMatchWholeWords: true,
DrawRectangles: false,
ReplacementText: ""
);
pdf.SaveAs("legal-brief-redacted.pdf");
Imports IronPdf
' Load the document
Dim pdf As PdfDocument = PdfDocument.FromFile("legal-brief.pdf")
' Case-sensitive redaction: only matches exact case
' "CLASSIFIED" will be redacted but "classified" or "Classified" will not
pdf.RedactTextOnAllPages(
"CLASSIFIED",
CaseSensitive:=True,
OnlyMatchWholeWords:=True,
DrawRectangles:=True,
ReplacementText:="[REDACTED]"
)
' Case-insensitive redaction: matches regardless of case
' Will redact "Secret", "SECRET", "secret", etc.
pdf.RedactTextOnAllPages(
"secret",
CaseSensitive:=False,
OnlyMatchWholeWords:=True,
DrawRectangles:=True,
ReplacementText:="*****"
)
' Whole word disabled: matches partial strings too
' Will redact "password", "passwords", "mypassword123", etc.
pdf.RedactTextOnAllPages(
"password",
CaseSensitive:=False,
OnlyMatchWholeWords:=False,
DrawRectangles:=True,
ReplacementText:="XXXXX"
)
' No visual rectangle: text is removed but no black box appears
' Useful when you want seamless removal without obvious redaction marks
pdf.RedactTextOnAllPages(
"internal-reference-code",
CaseSensitive:=True,
OnlyMatchWholeWords:=True,
DrawRectangles:=False,
ReplacementText:=""
)
pdf.SaveAs("legal-brief-redacted.pdf")
Bu kod, RedactTextOnAllPages isteğe bağlı parametrelerini kullanarak dört farklı gizleme yapılandırmasını gösterir. "[REDACTED]" değişim etiketiyle büyük/küçük harfe duyarlı tam eşleştirmeyi, yıldızlarla büyük/küçük harfe duyarsız eşleştirmeyi, "passwords" gibi varyasyonları yakalamak için kısmi kelime eşleştirmeyi ve içerik silinmesini görünmez hale getirmek için görsel dikdörtgenler olmadan gösterir.
Örnek Çıktı
Parametreler, gereksinimlerinize bağlı olarak farklı amaçlar için kullanılır:
CaseSensitive, eşleştirmenin harflerin büyük/küçük harfini dikkate alıp almadığını belirler. Hukuki belgeler genellikle anlam taşıyan belirli büyük/küçük harf değişikliklerini kullanır, bu yüzden büyük/küçük harfe duyarlı eşleştirme yalnızca tam eşleşmeleri kaldırdığınızdan emin olmanızı sağlar. Büyük/küçük harfin değiştiği genel metni işlerken tüm örnekleri yakalamak için büyük/küçük harfe duyarsız eşleştirme gerektirebilir.
OnlyMatchWholeWords, aramanın tam kelimeleri mi yoksa kısmi dizeleri mi eşleştireceğini kontrol eder. İsimleri redakte ederken, genellikle "Smith"in "Blacksmith" veya "Smithfield"'ın bir parçasını yanlışlıkla redakte etmemesi için tam kelime eşleştirmesi istersiniz. Hesap numarası ön ekleri gibi desenleri redakte ettiğinizde, varyasyonları yakalamak için kısmi eşleştirme gerekli olabilir.
DrawRectangles, içeriğin kaldırıldığı yerde siyah kutuların görünüp görünmeyeceğini belirtir. Çoğu düzenleyici ve hukuki bağlam, içeriğin kasıtlı olarak kaldırıldığını kanıtlamak için görünür redaksiyon işaretleri gerektirir, aksine yanlışlıkla unutulmuş. Dahili iş akışları daha temiz çıktı için görünmez kaldırmayı tercih edebilir.
ReplacementText, redakte edilen içeriğin yerine hangi karakterlerin gözükeceğini tanımlar. Yaygın seçimler yıldızlar, "REDACTED" etiketleri veya boş dizelerdir. Biri redakte edilen alandan seçim veya kopyalama yapmaya çalışırsa, değiştirme metni belge yapısında gözükür.
Hassas Desenleri Bulmak ve Redakte Etmek İçin Düzenli İfadeleri Nasıl Kullanabilirim?
Bilinen metin dizgilerini redakte etmek, kaldırılacak belirli değerlere sahip olduğunuzda işe yarar, ancak birçok gizli veri türü sabit değerler yerine öngörülebilir desenleri takip eder. Sosyal Güvenlik numaraları, kredi kartı numaraları, e-posta adresleri, telefon numaraları ve tarihlerin tümü, düzenli ifadelerle eşleştirilebilecek tanınabilir formatlara sahiptir. Desen tabanlı bir redaksiyon sistemi oluşturmak, PDF içeriğinden her spesifik değeri önceden bilmeden özel bilgileri kaldırmanıza olanak tanır.
IronPDF'in metin çıkarma yetenekleri ile redaksiyon yöntemleri, güçlü desen eşleştirme iş akışlarını mümkün kılar. Metni çıkartın, .NET düzenli ifadelerini kullanarak eşleşmeleri belirleyin ve ardından bulunan her değeri redakte edin.
using IronPdf;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class PatternRedactor
{
// Common patterns for sensitive data
private static readonly Dictionary<string, string> SensitivePatterns = new Dictionary<string, string>
{
// US Social Security Number: 123-45-6789
{ "SSN", @"\b\d{3}-\d{2}-\d{4}\b" },
// Credit Card Numbers: various formats with 13-19 digits
{ "CreditCard", @"\b(?:\d{4}[-\s]?){3}\d{1,4}\b" },
// Email Addresses
{ "Email", @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" },
// US Phone Numbers: (123) 456-7890 or 123-456-7890
{ "Phone", @"\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b" },
// Dates: MM/DD/YYYY or MM-DD-YYYY
{ "Date", @"\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b" },
// IP Addresses
{ "IPAddress", @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b" }
};
public void RedactPatterns(string inputPath, string outputPath, params string[] patternNames)
{
// Load the PDF
PdfDocument pdf = PdfDocument.FromFile(inputPath);
// Extract all text from the document
string fullText = pdf.ExtractAllText();
// Track unique matches to avoid duplicate redaction attempts
HashSet<string> matchesToRedact = new HashSet<string>();
// Find all matches for requested patterns
foreach (string patternName in patternNames)
{
if (SensitivePatterns.TryGetValue(patternName, out string pattern))
{
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(fullText);
foreach (Match match in matches)
{
matchesToRedact.Add(match.Value);
}
}
}
// Redact each unique match
foreach (string sensitiveValue in matchesToRedact)
{
pdf.RedactTextOnAllPages(sensitiveValue);
}
// Save the redacted document
pdf.SaveAs(outputPath);
}
}
// Usage example
class Program
{
static void Main()
{
PatternRedactor redactor = new PatternRedactor();
// Redact SSNs and credit cards from a financial document
redactor.RedactPatterns(
"customer-data.pdf",
"customer-data-safe.pdf",
"SSN", "CreditCard", "Email"
);
}
}
using IronPdf;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class PatternRedactor
{
// Common patterns for sensitive data
private static readonly Dictionary<string, string> SensitivePatterns = new Dictionary<string, string>
{
// US Social Security Number: 123-45-6789
{ "SSN", @"\b\d{3}-\d{2}-\d{4}\b" },
// Credit Card Numbers: various formats with 13-19 digits
{ "CreditCard", @"\b(?:\d{4}[-\s]?){3}\d{1,4}\b" },
// Email Addresses
{ "Email", @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" },
// US Phone Numbers: (123) 456-7890 or 123-456-7890
{ "Phone", @"\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b" },
// Dates: MM/DD/YYYY or MM-DD-YYYY
{ "Date", @"\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b" },
// IP Addresses
{ "IPAddress", @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b" }
};
public void RedactPatterns(string inputPath, string outputPath, params string[] patternNames)
{
// Load the PDF
PdfDocument pdf = PdfDocument.FromFile(inputPath);
// Extract all text from the document
string fullText = pdf.ExtractAllText();
// Track unique matches to avoid duplicate redaction attempts
HashSet<string> matchesToRedact = new HashSet<string>();
// Find all matches for requested patterns
foreach (string patternName in patternNames)
{
if (SensitivePatterns.TryGetValue(patternName, out string pattern))
{
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(fullText);
foreach (Match match in matches)
{
matchesToRedact.Add(match.Value);
}
}
}
// Redact each unique match
foreach (string sensitiveValue in matchesToRedact)
{
pdf.RedactTextOnAllPages(sensitiveValue);
}
// Save the redacted document
pdf.SaveAs(outputPath);
}
}
// Usage example
class Program
{
static void Main()
{
PatternRedactor redactor = new PatternRedactor();
// Redact SSNs and credit cards from a financial document
redactor.RedactPatterns(
"customer-data.pdf",
"customer-data-safe.pdf",
"SSN", "CreditCard", "Email"
);
}
}
Imports IronPdf
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Public Class PatternRedactor
' Common patterns for sensitive data
Private Shared ReadOnly SensitivePatterns As New Dictionary(Of String, String) From {
' US Social Security Number: 123-45-6789
{"SSN", "\b\d{3}-\d{2}-\d{4}\b"},
' Credit Card Numbers: various formats with 13-19 digits
{"CreditCard", "\b(?:\d{4}[-\s]?){3}\d{1,4}\b"},
' Email Addresses
{"Email", "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"},
' US Phone Numbers: (123) 456-7890 or 123-456-7890
{"Phone", "\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b"},
' Dates: MM/DD/YYYY or MM-DD-YYYY
{"Date", "\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b"},
' IP Addresses
{"IPAddress", "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"}
}
Public Sub RedactPatterns(inputPath As String, outputPath As String, ParamArray patternNames As String())
' Load the PDF
Dim pdf As PdfDocument = PdfDocument.FromFile(inputPath)
' Extract all text from the document
Dim fullText As String = pdf.ExtractAllText()
' Track unique matches to avoid duplicate redaction attempts
Dim matchesToRedact As New HashSet(Of String)()
' Find all matches for requested patterns
For Each patternName As String In patternNames
Dim pattern As String = Nothing
If SensitivePatterns.TryGetValue(patternName, pattern) Then
Dim regex As New Regex(pattern, RegexOptions.IgnoreCase)
Dim matches As MatchCollection = regex.Matches(fullText)
For Each match As Match In matches
matchesToRedact.Add(match.Value)
Next
End If
Next
' Redact each unique match
For Each sensitiveValue As String In matchesToRedact
pdf.RedactTextOnAllPages(sensitiveValue)
Next
' Save the redacted document
pdf.SaveAs(outputPath)
End Sub
End Class
' Usage example
Class Program
Shared Sub Main()
Dim redactor As New PatternRedactor()
' Redact SSNs and credit cards from a financial document
redactor.RedactPatterns(
"customer-data.pdf",
"customer-data-safe.pdf",
"SSN", "CreditCard", "Email"
)
End Sub
End Class
Bu şablon tabanlı yaklaşım iyi ölçeklenir çünkü desenleri bir kez tanımlar ve bunları herhangi bir belgeye uygularsınız. Yeni veri türleri eklemek yalnızca sözlüğe yeni düzenli ifade kalıpları eklemeyi gerektirir.
Yeniden Kullanılabilir Hassas Veri Tarayıcısı Nasıl Oluştururum?
Üretim ortamlarında, belgeleri taramanız ve redakte edilip edilmeyeceğine karar vermeden önce hangi gizli bilgilerin var olduğunu rapor etmeniz sıklıkla gerekir. Bu, uyum denetimi ile yardımcı olur ve redaksiyon kararlarının insan tarafından incelenmesine olanak sağlar. Aşağıdaki sınıf, tarama yeteneklerini redaksiyonla birlikte sunar.
using IronPdf;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
public class SensitiveDataMatch
{
public string PatternType { get; set; }
public string Value { get; set; }
public int PageNumber { get; set; }
}
public class ScanResult
{
public string FilePath { get; set; }
public List<SensitiveDataMatch> Matches { get; set; } = new List<SensitiveDataMatch>();
public bool ContainsSensitiveData => Matches.Count > 0;
public Dictionary<string, int> GetSummary()
{
return Matches.GroupBy(m => m.PatternType)
.ToDictionary(g => g.Key, g => g.Count());
}
}
public class DocumentScanner
{
private readonly Dictionary<string, string> _patterns;
public DocumentScanner()
{
_patterns = new Dictionary<string, string>
{
{ "Social Security Number", @"\b\d{3}-\d{2}-\d{4}\b" },
{ "Credit Card", @"\b(?:\d{4}[-\s]?){3}\d{1,4}\b" },
{ "Email Address", @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" },
{ "Phone Number", @"\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b" },
{ "Date of Birth Pattern", @"\b(?:DOB|Date of Birth|Birth Date)[:\s]+\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b" }
};
}
public ScanResult ScanDocument(string filePath)
{
ScanResult result = new ScanResult { FilePath = filePath };
PdfDocument pdf = PdfDocument.FromFile(filePath);
// Scan each page individually to track location
for (int pageIndex = 0; pageIndex < pdf.PageCount; pageIndex++)
{
string pageText = pdf.ExtractTextFromPage(pageIndex);
foreach (var pattern in _patterns)
{
Regex regex = new Regex(pattern.Value, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(pageText);
foreach (Match match in matches)
{
result.Matches.Add(new SensitiveDataMatch
{
PatternType = pattern.Key,
Value = MaskValue(match.Value, pattern.Key),
PageNumber = pageIndex + 1
});
}
}
}
return result;
}
// Partially mask values for safe storage
private string MaskValue(string value, string patternType)
{
if (patternType == "Social Security Number" && value.Length >= 4)
{
return "XXX-XX-" + value.Substring(value.Length - 4);
}
if (patternType == "Credit Card" && value.Length >= 4)
{
return "****-****-****-" + value.Substring(value.Length - 4);
}
if (patternType == "Email Address")
{
int atIndex = value.IndexOf('@');
if (atIndex > 2)
{
return value.Substring(0, 2) + "***" + value.Substring(atIndex);
}
}
return value.Length > 4 ? value.Substring(0, 2) + "***" : "****";
}
public void ScanAndRedact(string inputPath, string outputPath)
{
// First scan to identify sensitive data
ScanResult scanResult = ScanDocument(inputPath);
if (!scanResult.ContainsSensitiveData)
{
return;
}
// Load document for redaction
PdfDocument pdf = PdfDocument.FromFile(inputPath);
// Extract unique actual values (not masked) for redaction
string fullText = pdf.ExtractAllText();
HashSet<string> valuesToRedact = new HashSet<string>();
foreach (var pattern in _patterns)
{
Regex regex = new Regex(pattern.Value, RegexOptions.IgnoreCase);
foreach (Match match in regex.Matches(fullText))
{
valuesToRedact.Add(match.Value);
}
}
// Apply redactions
foreach (string value in valuesToRedact)
{
pdf.RedactTextOnAllPages(value);
}
pdf.SaveAs(outputPath);
}
}
// Usage
class Program
{
static void Main()
{
DocumentScanner scanner = new DocumentScanner();
// Scan only (for audit purposes)
ScanResult result = scanner.ScanDocument("application-form.pdf");
var summary = result.GetSummary();
// Scan and redact in one operation
scanner.ScanAndRedact("application-form.pdf", "application-form-redacted.pdf");
}
}
using IronPdf;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
public class SensitiveDataMatch
{
public string PatternType { get; set; }
public string Value { get; set; }
public int PageNumber { get; set; }
}
public class ScanResult
{
public string FilePath { get; set; }
public List<SensitiveDataMatch> Matches { get; set; } = new List<SensitiveDataMatch>();
public bool ContainsSensitiveData => Matches.Count > 0;
public Dictionary<string, int> GetSummary()
{
return Matches.GroupBy(m => m.PatternType)
.ToDictionary(g => g.Key, g => g.Count());
}
}
public class DocumentScanner
{
private readonly Dictionary<string, string> _patterns;
public DocumentScanner()
{
_patterns = new Dictionary<string, string>
{
{ "Social Security Number", @"\b\d{3}-\d{2}-\d{4}\b" },
{ "Credit Card", @"\b(?:\d{4}[-\s]?){3}\d{1,4}\b" },
{ "Email Address", @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" },
{ "Phone Number", @"\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b" },
{ "Date of Birth Pattern", @"\b(?:DOB|Date of Birth|Birth Date)[:\s]+\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b" }
};
}
public ScanResult ScanDocument(string filePath)
{
ScanResult result = new ScanResult { FilePath = filePath };
PdfDocument pdf = PdfDocument.FromFile(filePath);
// Scan each page individually to track location
for (int pageIndex = 0; pageIndex < pdf.PageCount; pageIndex++)
{
string pageText = pdf.ExtractTextFromPage(pageIndex);
foreach (var pattern in _patterns)
{
Regex regex = new Regex(pattern.Value, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(pageText);
foreach (Match match in matches)
{
result.Matches.Add(new SensitiveDataMatch
{
PatternType = pattern.Key,
Value = MaskValue(match.Value, pattern.Key),
PageNumber = pageIndex + 1
});
}
}
}
return result;
}
// Partially mask values for safe storage
private string MaskValue(string value, string patternType)
{
if (patternType == "Social Security Number" && value.Length >= 4)
{
return "XXX-XX-" + value.Substring(value.Length - 4);
}
if (patternType == "Credit Card" && value.Length >= 4)
{
return "****-****-****-" + value.Substring(value.Length - 4);
}
if (patternType == "Email Address")
{
int atIndex = value.IndexOf('@');
if (atIndex > 2)
{
return value.Substring(0, 2) + "***" + value.Substring(atIndex);
}
}
return value.Length > 4 ? value.Substring(0, 2) + "***" : "****";
}
public void ScanAndRedact(string inputPath, string outputPath)
{
// First scan to identify sensitive data
ScanResult scanResult = ScanDocument(inputPath);
if (!scanResult.ContainsSensitiveData)
{
return;
}
// Load document for redaction
PdfDocument pdf = PdfDocument.FromFile(inputPath);
// Extract unique actual values (not masked) for redaction
string fullText = pdf.ExtractAllText();
HashSet<string> valuesToRedact = new HashSet<string>();
foreach (var pattern in _patterns)
{
Regex regex = new Regex(pattern.Value, RegexOptions.IgnoreCase);
foreach (Match match in regex.Matches(fullText))
{
valuesToRedact.Add(match.Value);
}
}
// Apply redactions
foreach (string value in valuesToRedact)
{
pdf.RedactTextOnAllPages(value);
}
pdf.SaveAs(outputPath);
}
}
// Usage
class Program
{
static void Main()
{
DocumentScanner scanner = new DocumentScanner();
// Scan only (for audit purposes)
ScanResult result = scanner.ScanDocument("application-form.pdf");
var summary = result.GetSummary();
// Scan and redact in one operation
scanner.ScanAndRedact("application-form.pdf", "application-form-redacted.pdf");
}
}
Imports IronPdf
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Imports System.Linq
Public Class SensitiveDataMatch
Public Property PatternType As String
Public Property Value As String
Public Property PageNumber As Integer
End Class
Public Class ScanResult
Public Property FilePath As String
Public Property Matches As List(Of SensitiveDataMatch) = New List(Of SensitiveDataMatch)()
Public ReadOnly Property ContainsSensitiveData As Boolean
Get
Return Matches.Count > 0
End Get
End Property
Public Function GetSummary() As Dictionary(Of String, Integer)
Return Matches.GroupBy(Function(m) m.PatternType) _
.ToDictionary(Function(g) g.Key, Function(g) g.Count())
End Function
End Class
Public Class DocumentScanner
Private ReadOnly _patterns As Dictionary(Of String, String)
Public Sub New()
_patterns = New Dictionary(Of String, String) From {
{"Social Security Number", "\b\d{3}-\d{2}-\d{4}\b"},
{"Credit Card", "\b(?:\d{4}[-\s]?){3}\d{1,4}\b"},
{"Email Address", "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"},
{"Phone Number", "\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b"},
{"Date of Birth Pattern", "\b(?:DOB|Date of Birth|Birth Date)[:\s]+\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b"}
}
End Sub
Public Function ScanDocument(filePath As String) As ScanResult
Dim result As New ScanResult With {.FilePath = filePath}
Dim pdf As PdfDocument = PdfDocument.FromFile(filePath)
' Scan each page individually to track location
For pageIndex As Integer = 0 To pdf.PageCount - 1
Dim pageText As String = pdf.ExtractTextFromPage(pageIndex)
For Each pattern In _patterns
Dim regex As New Regex(pattern.Value, RegexOptions.IgnoreCase)
Dim matches As MatchCollection = regex.Matches(pageText)
For Each match As Match In matches
result.Matches.Add(New SensitiveDataMatch With {
.PatternType = pattern.Key,
.Value = MaskValue(match.Value, pattern.Key),
.PageNumber = pageIndex + 1
})
Next
Next
Next
Return result
End Function
' Partially mask values for safe storage
Private Function MaskValue(value As String, patternType As String) As String
If patternType = "Social Security Number" AndAlso value.Length >= 4 Then
Return "XXX-XX-" & value.Substring(value.Length - 4)
End If
If patternType = "Credit Card" AndAlso value.Length >= 4 Then
Return "****-****-****-" & value.Substring(value.Length - 4)
End If
If patternType = "Email Address" Then
Dim atIndex As Integer = value.IndexOf("@"c)
If atIndex > 2 Then
Return value.Substring(0, 2) & "***" & value.Substring(atIndex)
End If
End If
Return If(value.Length > 4, value.Substring(0, 2) & "***", "****")
End Function
Public Sub ScanAndRedact(inputPath As String, outputPath As String)
' First scan to identify sensitive data
Dim scanResult As ScanResult = ScanDocument(inputPath)
If Not scanResult.ContainsSensitiveData Then
Return
End If
' Load document for redaction
Dim pdf As PdfDocument = PdfDocument.FromFile(inputPath)
' Extract unique actual values (not masked) for redaction
Dim fullText As String = pdf.ExtractAllText()
Dim valuesToRedact As New HashSet(Of String)()
For Each pattern In _patterns
Dim regex As New Regex(pattern.Value, RegexOptions.IgnoreCase)
For Each match As Match In regex.Matches(fullText)
valuesToRedact.Add(match.Value)
Next
Next
' Apply redactions
For Each value As String In valuesToRedact
pdf.RedactTextOnAllPages(value)
Next
pdf.SaveAs(outputPath)
End Sub
End Class
' Usage
Module Program
Sub Main()
Dim scanner As New DocumentScanner()
' Scan only (for audit purposes)
Dim result As ScanResult = scanner.ScanDocument("application-form.pdf")
Dim summary = result.GetSummary()
' Scan and redact in one operation
scanner.ScanAndRedact("application-form.pdf", "application-form-redacted.pdf")
End Sub
End Module
Tarayıcı, herhangi bir değişiklik yapılmadan önce hangi gizli bilgilerin var olduğunu görmek için görünürlük sağlar. Bu, ne bulunduğunu ve neyin çıkarıldığını belgelemeniz gereken uyum iş akışlarını destekler. Maskeleme fonksiyonu, günlük dosyalarının ve raporların kendilerinin veri maruziyetinin kaynağı haline gelmesini engeller.
PDF'te Belirli Bölgeleri veya Alanları Nasıl Redakte Ederim?
Metin redaksiyonu, karakter bazlı içeriği etkili bir şekilde işleme alır, ancak PDF'ler genellikle metin eşleştirmesinin çözemeyeceği hassas bilgileri içerir. İmzalar, fotoğraflar, el yazısı notlar, damgalar ve grafiksel unsurlar farklı bir yaklaşım gerektirir. Bölge bazlı redaksiyon ile koordinatları belirterek dikdörtgen alanları tanımlayabilir ve içlerindeki her şeyi kalıcı olarak bulanıklaştırabilirsiniz.
IronPDF, gizleme bölgelerini tanımlamak için RectangleF yapısını kullanır. Sol üst köşenin X ve Y koordinatlarını ve ardından alanın genişlik ve yüksekliğini belirtirsiniz. Koordinatlar, PDF spesifikasyonunun koordinat sistemine uyan şekilde sayfanın sol alt tarafından, noktalarla ölçülür.
Giriş
Koordinat bazlı bölge hedefleme ile redakte edilmesi gereken el yazısı imzalar ve fotoğraf kimlik kartı içeren imzalı bir anlaşma belgesi.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/redact-region-basic.cs
using IronPdf;
using IronSoftware.Drawing;
// Load a document with signature blocks and photos
PdfDocument pdf = PdfDocument.FromFile("signed-agreement.pdf");
// Define a region for a signature block
// Located 100 points from left, 650 points from bottom
// Width of 200 points, height of 50 points
RectangleF signatureRegion = new RectangleF(100, 650, 200, 50);
// Redact the signature region on all pages
pdf.RedactRegionsOnAllPages(signatureRegion);
// Define a region for a photo ID in the upper right
RectangleF photoRegion = new RectangleF(450, 700, 100, 120);
pdf.RedactRegionsOnAllPages(photoRegion);
// Save the document with regions redacted
pdf.SaveAs("signed-agreement-redacted.pdf");
Imports IronPdf
Imports IronSoftware.Drawing
' Load a document with signature blocks and photos
Dim pdf As PdfDocument = PdfDocument.FromFile("signed-agreement.pdf")
' Define a region for a signature block
' Located 100 points from left, 650 points from bottom
' Width of 200 points, height of 50 points
Dim signatureRegion As New RectangleF(100, 650, 200, 50)
' Redact the signature region on all pages
pdf.RedactRegionsOnAllPages(signatureRegion)
' Define a region for a photo ID in the upper right
Dim photoRegion As New RectangleF(450, 700, 100, 120)
pdf.RedactRegionsOnAllPages(photoRegion)
' Save the document with regions redacted
pdf.SaveAs("signed-agreement-redacted.pdf")
Bu kod, dikdörtgen alanları gizlemek için RectangleF yapılarını kullanır. İmza bölgesi (100, 650) koordinatında 200x50 piksel alana, fotoğraf bölgesi ise (450, 700) koordinatında 100x120 piksel alana sahiptir. RedactRegionsOnAllPages yöntemi bu bölgeler üzerine tüm sayfalarda siyah dikdörtgenler uygular.
Örnek Çıktı
Doğru koordinatları belirlemek genellikle biraz deneme veya ölçüm gerektirir. PDF sayfaları tipik olarak bir noktanın bir inçin 1/72'si olduğu bir koordinasyon sistemi kullanır. Standart bir US Letter sayfası 612 puan genişliğinde ve 792 puan yüksekliktedir. A4 sayfaları yaklaşık olarak 595'e 842 puandır. Koordinatları hareket ettirdikçe gösterebilen PDF görüntüleme araçlarından faydalanabilir veya sayfa boyutlarını programatik olarak çıkarabilirsiniz:
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/redact-region-dimensions.cs
using IronPdf;
using IronSoftware.Drawing;
PdfDocument pdf = PdfDocument.FromFile("form-document.pdf");
// Get dimensions of the first page
var pageInfo = pdf.Pages[0];
// Calculate regions relative to page dimensions
// Redact the bottom quarter of the page where signatures appear
float signatureAreaHeight = (float)(pageInfo.Height / 4);
RectangleF bottomQuarter = new RectangleF(
0, // Start at left edge
0, // Start at bottom
(float)pageInfo.Width, // Full page width
signatureAreaHeight // Quarter of page height
);
pdf.RedactRegionsOnAllPages(bottomQuarter);
// Redact a header area at the top containing letterhead with address
float headerHeight = 100;
RectangleF headerArea = new RectangleF(
0,
(float)(pageInfo.Height - headerHeight), // Position from bottom
(float)pageInfo.Width,
headerHeight
);
pdf.RedactRegionsOnAllPages(headerArea);
pdf.SaveAs("form-document-redacted.pdf");
Imports IronPdf
Imports IronSoftware.Drawing
Dim pdf As PdfDocument = PdfDocument.FromFile("form-document.pdf")
' Get dimensions of the first page
Dim pageInfo = pdf.Pages(0)
' Calculate regions relative to page dimensions
' Redact the bottom quarter of the page where signatures appear
Dim signatureAreaHeight As Single = CSng(pageInfo.Height / 4)
Dim bottomQuarter As New RectangleF(0, 0, CSng(pageInfo.Width), signatureAreaHeight)
pdf.RedactRegionsOnAllPages(bottomQuarter)
' Redact a header area at the top containing letterhead with address
Dim headerHeight As Single = 100
Dim headerArea As New RectangleF(0, CSng(pageInfo.Height - headerHeight), CSng(pageInfo.Width), headerHeight)
pdf.RedactRegionsOnAllPages(headerArea)
pdf.SaveAs("form-document-redacted.pdf")
Farklı Sayfalarda Birden Fazla Bölgeyi Nasıl Redakte Ederim?
Karmaşık belgeler genellikle farklı sayfalarda farklı bölgelerin redakte edilmesini gerektirir. Çok sayfalı bir form, değişken konumlarda imza satırlarına veya farklı sayfalarda fotoğraflar, damgalar veya benzersiz konumlarda diğer grafik unsurlar içerebilir. IronPDF, hedeflenen bölge redaksiyonu için sayfa özel yöntemler içerir.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/redact-multiple-regions.cs
using IronPdf;
using IronSoftware.Drawing;
PdfDocument pdf = PdfDocument.FromFile("multi-page-application.pdf");
// Define page-specific redaction regions
// Page 1: Cover page with applicant photo
RectangleF page1Photo = new RectangleF(450, 600, 120, 150);
pdf.RedactRegionOnPage(0, page1Photo);
// Page 2: Personal information section
RectangleF page2InfoBlock = new RectangleF(50, 400, 250, 200);
pdf.RedactRegionOnPage(1, page2InfoBlock);
// Pages 3-5: Signature lines at the same position
RectangleF signatureLine = new RectangleF(100, 100, 200, 40);
int[] signaturePages = { 2, 3, 4 };
pdf.RedactRegionOnPages(signaturePages, signatureLine);
// Page 6: Multiple regions - notary stamp and witness signature
RectangleF notaryStamp = new RectangleF(400, 150, 150, 150);
RectangleF witnessSignature = new RectangleF(100, 150, 200, 40);
pdf.RedactRegionOnPage(5, notaryStamp);
pdf.RedactRegionOnPage(5, witnessSignature);
pdf.SaveAs("multi-page-application-redacted.pdf");
Imports IronPdf
Imports IronSoftware.Drawing
Dim pdf As PdfDocument = PdfDocument.FromFile("multi-page-application.pdf")
' Define page-specific redaction regions
' Page 1: Cover page with applicant photo
Dim page1Photo As New RectangleF(450, 600, 120, 150)
pdf.RedactRegionOnPage(0, page1Photo)
' Page 2: Personal information section
Dim page2InfoBlock As New RectangleF(50, 400, 250, 200)
pdf.RedactRegionOnPage(1, page2InfoBlock)
' Pages 3-5: Signature lines at the same position
Dim signatureLine As New RectangleF(100, 100, 200, 40)
Dim signaturePages As Integer() = {2, 3, 4}
pdf.RedactRegionOnPages(signaturePages, signatureLine)
' Page 6: Multiple regions - notary stamp and witness signature
Dim notaryStamp As New RectangleF(400, 150, 150, 150)
Dim witnessSignature As New RectangleF(100, 150, 200, 40)
pdf.RedactRegionOnPage(5, notaryStamp)
pdf.RedactRegionOnPage(5, witnessSignature)
pdf.SaveAs("multi-page-application-redacted.pdf")
Tutarlı düzenlere sahip belgeler yeniden kullanılabilir bölge tanımlamalarından faydalanır:
using IronPdf;
using IronSoftware.Drawing;
public class FormRegions
{
// Standard form regions based on common templates
public static RectangleF HeaderLogo => new RectangleF(20, 720, 150, 60);
public static RectangleF SignatureBlock => new RectangleF(72, 72, 200, 50);
public static RectangleF DateField => new RectangleF(400, 72, 120, 20);
public static RectangleF PhotoId => new RectangleF(480, 650, 100, 130);
public static RectangleF AddressBlock => new RectangleF(72, 600, 250, 80);
}
class Program
{
static void Main()
{
PdfDocument pdf = PdfDocument.FromFile("standard-form.pdf");
// Apply standard redactions using predefined regions
pdf.RedactRegionsOnAllPages(FormRegions.SignatureBlock);
pdf.RedactRegionsOnAllPages(FormRegions.DateField);
pdf.RedactRegionOnPage(0, FormRegions.PhotoId);
pdf.SaveAs("standard-form-redacted.pdf");
}
}
using IronPdf;
using IronSoftware.Drawing;
public class FormRegions
{
// Standard form regions based on common templates
public static RectangleF HeaderLogo => new RectangleF(20, 720, 150, 60);
public static RectangleF SignatureBlock => new RectangleF(72, 72, 200, 50);
public static RectangleF DateField => new RectangleF(400, 72, 120, 20);
public static RectangleF PhotoId => new RectangleF(480, 650, 100, 130);
public static RectangleF AddressBlock => new RectangleF(72, 600, 250, 80);
}
class Program
{
static void Main()
{
PdfDocument pdf = PdfDocument.FromFile("standard-form.pdf");
// Apply standard redactions using predefined regions
pdf.RedactRegionsOnAllPages(FormRegions.SignatureBlock);
pdf.RedactRegionsOnAllPages(FormRegions.DateField);
pdf.RedactRegionOnPage(0, FormRegions.PhotoId);
pdf.SaveAs("standard-form-redacted.pdf");
}
}
Imports IronPdf
Imports IronSoftware.Drawing
Public Class FormRegions
' Standard form regions based on common templates
Public Shared ReadOnly Property HeaderLogo As RectangleF
Get
Return New RectangleF(20, 720, 150, 60)
End Get
End Property
Public Shared ReadOnly Property SignatureBlock As RectangleF
Get
Return New RectangleF(72, 72, 200, 50)
End Get
End Property
Public Shared ReadOnly Property DateField As RectangleF
Get
Return New RectangleF(400, 72, 120, 20)
End Get
End Property
Public Shared ReadOnly Property PhotoId As RectangleF
Get
Return New RectangleF(480, 650, 100, 130)
End Get
End Property
Public Shared ReadOnly Property AddressBlock As RectangleF
Get
Return New RectangleF(72, 600, 250, 80)
End Get
End Property
End Class
Module Program
Sub Main()
Dim pdf As PdfDocument = PdfDocument.FromFile("standard-form.pdf")
' Apply standard redactions using predefined regions
pdf.RedactRegionsOnAllPages(FormRegions.SignatureBlock)
pdf.RedactRegionsOnAllPages(FormRegions.DateField)
pdf.RedactRegionOnPage(0, FormRegions.PhotoId)
pdf.SaveAs("standard-form-redacted.pdf")
End Sub
End Module
Gizli Bilgi Açığa Çıkarabilecek Metaveriyi Nasıl Kaldırırım?
PDF metadata, sıklıkla göz ardı edilen bir bilgi sızıntısı kaynağını temsil eder. Her PDF, duyarlı ayrıntıları açığa çıkarabilecek özellikler taşır: yazarın adı ve kullanıcı adı, belgeyi oluşturmak için kullanılan yazılım, oluşturma ve değiştirme zaman damgaları, orijinal dosya adı, revizyon geçmişi ve çeşitli uygulamalar tarafından eklenen özel özellikler. Belgeleri dışa aktarmadan önce bu metadatanın soyulması veya temizlenmesi şarttır. Metadata işlemleri hakkında kapsamlı bir genel bakış için, metadata rehberimize bakın.
IronPDF, mevcut değerleri okumanıza, değiştirmenize veya tamamen kaldırmanıza izin vererek belge meta verilerini MetaData özelliği aracılığıyla ortaya çıkarır.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/view-metadata.cs
using IronPdf;
using System;
// Load a document containing sensitive metadata
PdfDocument pdf = PdfDocument.FromFile("internal-report.pdf");
// Access current metadata properties
string author = pdf.MetaData.Author;
string title = pdf.MetaData.Title;
string subject = pdf.MetaData.Subject;
string keywords = pdf.MetaData.Keywords;
string creator = pdf.MetaData.Creator;
string producer = pdf.MetaData.Producer;
DateTime? creationDate = pdf.MetaData.CreationDate;
DateTime? modifiedDate = pdf.MetaData.ModifiedDate;
// Get all metadata keys including custom properties
var allKeys = pdf.MetaData.Keys();
Imports IronPdf
Imports System
' Load a document containing sensitive metadata
Dim pdf As PdfDocument = PdfDocument.FromFile("internal-report.pdf")
' Access current metadata properties
Dim author As String = pdf.MetaData.Author
Dim title As String = pdf.MetaData.Title
Dim subject As String = pdf.MetaData.Subject
Dim keywords As String = pdf.MetaData.Keywords
Dim creator As String = pdf.MetaData.Creator
Dim producer As String = pdf.MetaData.Producer
Dim creationDate As DateTime? = pdf.MetaData.CreationDate
Dim modifiedDate As DateTime? = pdf.MetaData.ModifiedDate
' Get all metadata keys including custom properties
Dim allKeys = pdf.MetaData.Keys()
Yayın öncesinde duyarlı metaveriyi kaldırmak için:
Giriş
Yazar adları, oluşturulma zaman damgaları ve duyarlı kurumsal bilgileri açığa çıkarabilecek özel özellikler gibi gömülü metadata içeren bir iç memo.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/remove-metadata.cs
using IronPdf;
using System;
PdfDocument pdf = PdfDocument.FromFile("confidential-memo.pdf");
// Replace identifying metadata with generic values
pdf.MetaData.Author = "Organization Name";
pdf.MetaData.Creator = "Document System";
pdf.MetaData.Producer = "";
pdf.MetaData.Title = "Public Document";
pdf.MetaData.Subject = "";
pdf.MetaData.Keywords = "";
// Normalize dates to remove timing information
pdf.MetaData.CreationDate = DateTime.Now;
pdf.MetaData.ModifiedDate = DateTime.Now;
// Remove specific custom metadata keys
pdf.MetaData.RemoveMetaDataKey("OriginalFilename");
pdf.MetaData.RemoveMetaDataKey("LastSavedBy");
pdf.MetaData.RemoveMetaDataKey("Company");
pdf.MetaData.RemoveMetaDataKey("Manager");
// Remove custom properties added by applications
try
{
pdf.MetaData.CustomProperties.Remove("SourcePath");
}
catch { }
pdf.SaveAs("confidential-memo-cleaned.pdf");
Imports IronPdf
Imports System
Dim pdf As PdfDocument = PdfDocument.FromFile("confidential-memo.pdf")
' Replace identifying metadata with generic values
pdf.MetaData.Author = "Organization Name"
pdf.MetaData.Creator = "Document System"
pdf.MetaData.Producer = ""
pdf.MetaData.Title = "Public Document"
pdf.MetaData.Subject = ""
pdf.MetaData.Keywords = ""
' Normalize dates to remove timing information
pdf.MetaData.CreationDate = DateTime.Now
pdf.MetaData.ModifiedDate = DateTime.Now
' Remove specific custom metadata keys
pdf.MetaData.RemoveMetaDataKey("OriginalFilename")
pdf.MetaData.RemoveMetaDataKey("LastSavedBy")
pdf.MetaData.RemoveMetaDataKey("Company")
pdf.MetaData.RemoveMetaDataKey("Manager")
' Remove custom properties added by applications
Try
pdf.MetaData.CustomProperties.Remove("SourcePath")
Catch
End Try
pdf.SaveAs("confidential-memo-cleaned.pdf")
Bu kod, tanımlayıcı metadata alanlarını genel değerlerle değiştirir, zaman damgalarını mevcut tarihe normalleştirir ve uygulamaların eklemiş olabileceği özel metadata anahtarlarını kaldırır. RemoveMetaDataKey yöntemi, iç bilgi açığa çıkarabilecek 'OriginalFilename' ve 'LastSavedBy' gibi belirli özellikleri hedefler.
Örnek Çıktı
Toplu işlemler çapında kapsamlı metadata temizliği sistematik bir yaklaşım gerektirir:
using IronPdf;
using System;
using System.Collections.Generic;
public class MetadataCleaner
{
private readonly string _defaultAuthor;
private readonly string _defaultCreator;
public MetadataCleaner(string organizationName)
{
_defaultAuthor = organizationName;
_defaultCreator = $"{organizationName} Document System";
}
public void CleanMetadata(PdfDocument pdf)
{
// Replace standard metadata fields
pdf.MetaData.Author = _defaultAuthor;
pdf.MetaData.Creator = _defaultCreator;
pdf.MetaData.Producer = "";
pdf.MetaData.Subject = "";
pdf.MetaData.Keywords = "";
// Normalize timestamps
DateTime now = DateTime.Now;
pdf.MetaData.CreationDate = now;
pdf.MetaData.ModifiedDate = now;
// Get all keys and remove potentially sensitive ones
List<string> keysToRemove = new List<string>();
foreach (string key in pdf.MetaData.Keys())
{
// Keep only essential keys
if (!IsEssentialKey(key))
{
keysToRemove.Add(key);
}
}
foreach (string key in keysToRemove)
{
pdf.MetaData.RemoveMetaDataKey(key);
}
}
private bool IsEssentialKey(string key)
{
// Keep only the basic display properties
string[] essentialKeys = { "Title", "Author", "CreationDate", "ModifiedDate" };
foreach (string essential in essentialKeys)
{
if (key.Equals(essential, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
// Usage
class Program
{
static void Main()
{
MetadataCleaner cleaner = new MetadataCleaner("Acme Corporation");
PdfDocument pdf = PdfDocument.FromFile("report.pdf");
cleaner.CleanMetadata(pdf);
pdf.SaveAs("report-clean.pdf");
}
}
using IronPdf;
using System;
using System.Collections.Generic;
public class MetadataCleaner
{
private readonly string _defaultAuthor;
private readonly string _defaultCreator;
public MetadataCleaner(string organizationName)
{
_defaultAuthor = organizationName;
_defaultCreator = $"{organizationName} Document System";
}
public void CleanMetadata(PdfDocument pdf)
{
// Replace standard metadata fields
pdf.MetaData.Author = _defaultAuthor;
pdf.MetaData.Creator = _defaultCreator;
pdf.MetaData.Producer = "";
pdf.MetaData.Subject = "";
pdf.MetaData.Keywords = "";
// Normalize timestamps
DateTime now = DateTime.Now;
pdf.MetaData.CreationDate = now;
pdf.MetaData.ModifiedDate = now;
// Get all keys and remove potentially sensitive ones
List<string> keysToRemove = new List<string>();
foreach (string key in pdf.MetaData.Keys())
{
// Keep only essential keys
if (!IsEssentialKey(key))
{
keysToRemove.Add(key);
}
}
foreach (string key in keysToRemove)
{
pdf.MetaData.RemoveMetaDataKey(key);
}
}
private bool IsEssentialKey(string key)
{
// Keep only the basic display properties
string[] essentialKeys = { "Title", "Author", "CreationDate", "ModifiedDate" };
foreach (string essential in essentialKeys)
{
if (key.Equals(essential, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
// Usage
class Program
{
static void Main()
{
MetadataCleaner cleaner = new MetadataCleaner("Acme Corporation");
PdfDocument pdf = PdfDocument.FromFile("report.pdf");
cleaner.CleanMetadata(pdf);
pdf.SaveAs("report-clean.pdf");
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Public Class MetadataCleaner
Private ReadOnly _defaultAuthor As String
Private ReadOnly _defaultCreator As String
Public Sub New(organizationName As String)
_defaultAuthor = organizationName
_defaultCreator = $"{organizationName} Document System"
End Sub
Public Sub CleanMetadata(pdf As PdfDocument)
' Replace standard metadata fields
pdf.MetaData.Author = _defaultAuthor
pdf.MetaData.Creator = _defaultCreator
pdf.MetaData.Producer = ""
pdf.MetaData.Subject = ""
pdf.MetaData.Keywords = ""
' Normalize timestamps
Dim now As DateTime = DateTime.Now
pdf.MetaData.CreationDate = now
pdf.MetaData.ModifiedDate = now
' Get all keys and remove potentially sensitive ones
Dim keysToRemove As New List(Of String)()
For Each key As String In pdf.MetaData.Keys()
' Keep only essential keys
If Not IsEssentialKey(key) Then
keysToRemove.Add(key)
End If
Next
For Each key As String In keysToRemove
pdf.MetaData.RemoveMetaDataKey(key)
Next
End Sub
Private Function IsEssentialKey(key As String) As Boolean
' Keep only the basic display properties
Dim essentialKeys As String() = {"Title", "Author", "CreationDate", "ModifiedDate"}
For Each essential As String In essentialKeys
If key.Equals(essential, StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Next
Return False
End Function
End Class
' Usage
Class Program
Shared Sub Main()
Dim cleaner As New MetadataCleaner("Acme Corporation")
Dim pdf As PdfDocument = PdfDocument.FromFile("report.pdf")
cleaner.CleanMetadata(pdf)
pdf.SaveAs("report-clean.pdf")
End Sub
End Class
Gömmeli Komut Dosyalarını ve Gizli Tehditleri Kaldırmak İçin PDF Nasıl Temizlenir?
PDF temizliği görünen içerik ve metadata'nın ötesine geçen güvenlik endişelerini ele alır. PDF dosyaları JavaScript kodu, gömülü yürütülebilir dosyalar, dış bağlantıları tetikleyen form eylemleri ve diğer potansiyel olarak zararlı unsurları içerebilir. Bu özellikler, etkileşimli formlar ve multimedya içerikleri gibi meşru amaçlarla vardır, ancak aynı zamanda saldırı vektörleri de yaratır. Bir PDF'i temizlemek, görsel içeriği korurken bu aktif unsurları kaldırır. Temizlik yöntemleri hakkında ek detaylar için, PDF temizleme rehberimize bakın.
IronPDF'nin Cleaner sınıfı, PDF'yi bir görüntü formatına dönüştürüp sonra tekrar çevirerek zarif bir temizlik yöntemi kullanır. Bu süreç, JavaScript, gömülü nesneler, form eylemleri ve açıklamaları ortadan kaldırırken görsel görünümü muhafaza eder. Kütüphane, farklı özelliklere sahip iki temizlik yöntemi sunar.
Giriş
JavaScript, gömülü nesneler veya diğer potansiyel olarak zararlı aktif içerik içerebilecek dış kaynaklı bir PDF belgesi.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/sanitize-pdf.cs
using IronPdf;
// Load a PDF that may contain active content
PdfDocument pdf = PdfDocument.FromFile("received-document.pdf");
// Sanitize using SVG conversion
// Faster processing, results in searchable text, slight layout variations possible
PdfDocument sanitizedSvg = Cleaner.SanitizeWithSvg(pdf);
sanitizedSvg.SaveAs("sanitized-svg.pdf");
// Sanitize using Bitmap conversion
// Slower processing, text becomes image (not searchable), exact visual reproduction
PdfDocument sanitizedBitmap = Cleaner.SanitizeWithBitmap(pdf);
sanitizedBitmap.SaveAs("sanitized-bitmap.pdf");
Imports IronPdf
' Load a PDF that may contain active content
Dim pdf As PdfDocument = PdfDocument.FromFile("received-document.pdf")
' Sanitize using SVG conversion
' Faster processing, results in searchable text, slight layout variations possible
Dim sanitizedSvg As PdfDocument = Cleaner.SanitizeWithSvg(pdf)
sanitizedSvg.SaveAs("sanitized-svg.pdf")
' Sanitize using Bitmap conversion
' Slower processing, text becomes image (not searchable), exact visual reproduction
Dim sanitizedBitmap As PdfDocument = Cleaner.SanitizeWithBitmap(pdf)
sanitizedBitmap.SaveAs("sanitized-bitmap.pdf")
Bu kod, IronPDF'nin Cleaner sınıfı tarafından sağlanan iki temizlik yöntemini gösterir. SanitizeWithSvg, aranabilir metni koruyarak aktif içeriği kaldırırken PDF'yi SVG ara formatına dönüştürür. SanitizeWithBitmap sayfaları önce görüntülere dönüştürür, tam görsel kopyaları üretir ancak metin, aranamaz grafikler olarak oluşturulur.
Örnek Çıktı
SVG yöntemi daha hızlı çalışır ve aranabilir içerik olarak metni muhafaza eder, bu da indekslenmesi veya erişilebilirliği gereken belgeler için uygundur. Bitmap yöntemi tam görsel kopyalar üretir ancak metni görsellere dönüştürür, bu da metin seçimini ve aramayı engeller. Çıktı belgesine olan gereksinimlerinize göre seçim yapın.
Temizleme sırasında çıktı ayarlarını ayarlamak için işleme seçeneklerini de uygulayabilirsiniz:
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/sanitize-with-options.cs
using IronPdf;
// Load the potentially unsafe document
PdfDocument pdf = PdfDocument.FromFile("untrusted-source.pdf");
// Configure rendering options for sanitization
var renderOptions = new ChromePdfRenderOptions
{
MarginTop = 10,
MarginBottom = 10,
MarginLeft = 10,
MarginRight = 10
};
// Sanitize with custom options
PdfDocument sanitized = Cleaner.SanitizeWithSvg(pdf, renderOptions);
sanitized.SaveAs("untrusted-source-safe.pdf");
Imports IronPdf
' Load the potentially unsafe document
Dim pdf As PdfDocument = PdfDocument.FromFile("untrusted-source.pdf")
' Configure rendering options for sanitization
Dim renderOptions As New ChromePdfRenderOptions With {
.MarginTop = 10,
.MarginBottom = 10,
.MarginLeft = 10,
.MarginRight = 10
}
' Sanitize with custom options
Dim sanitized As PdfDocument = Cleaner.SanitizeWithSvg(pdf, renderOptions)
sanitized.SaveAs("untrusted-source-safe.pdf")
Yüksek güvenlikli ortamlar, temizlemeyi diğer koruma önlemleriyle birleştirmeyi sıklıkla gerektirir:
using IronPdf;
using System;
public class SecureDocumentProcessor
{
public PdfDocument ProcessUntrustedDocument(string inputPath)
{
// Load the document
PdfDocument original = PdfDocument.FromFile(inputPath);
// Step 1: Sanitize to remove active content
PdfDocument sanitized = Cleaner.SanitizeWithSvg(original);
// Step 2: Clean metadata
sanitized.MetaData.Author = "Processed Document";
sanitized.MetaData.Creator = "Secure Processor";
sanitized.MetaData.Producer = "";
sanitized.MetaData.CreationDate = DateTime.Now;
sanitized.MetaData.ModifiedDate = DateTime.Now;
// Remove all custom metadata
foreach (string key in sanitized.MetaData.Keys())
{
if (key != "Title" && key != "Author" && key != "CreationDate" && key != "ModifiedDate")
{
sanitized.MetaData.RemoveMetaDataKey(key);
}
}
return sanitized;
}
}
// Usage
class Program
{
static void Main()
{
SecureDocumentProcessor processor = new SecureDocumentProcessor();
PdfDocument safe = processor.ProcessUntrustedDocument("email-attachment.pdf");
safe.SaveAs("email-attachment-safe.pdf");
}
}
using IronPdf;
using System;
public class SecureDocumentProcessor
{
public PdfDocument ProcessUntrustedDocument(string inputPath)
{
// Load the document
PdfDocument original = PdfDocument.FromFile(inputPath);
// Step 1: Sanitize to remove active content
PdfDocument sanitized = Cleaner.SanitizeWithSvg(original);
// Step 2: Clean metadata
sanitized.MetaData.Author = "Processed Document";
sanitized.MetaData.Creator = "Secure Processor";
sanitized.MetaData.Producer = "";
sanitized.MetaData.CreationDate = DateTime.Now;
sanitized.MetaData.ModifiedDate = DateTime.Now;
// Remove all custom metadata
foreach (string key in sanitized.MetaData.Keys())
{
if (key != "Title" && key != "Author" && key != "CreationDate" && key != "ModifiedDate")
{
sanitized.MetaData.RemoveMetaDataKey(key);
}
}
return sanitized;
}
}
// Usage
class Program
{
static void Main()
{
SecureDocumentProcessor processor = new SecureDocumentProcessor();
PdfDocument safe = processor.ProcessUntrustedDocument("email-attachment.pdf");
safe.SaveAs("email-attachment-safe.pdf");
}
}
Imports IronPdf
Imports System
Public Class SecureDocumentProcessor
Public Function ProcessUntrustedDocument(inputPath As String) As PdfDocument
' Load the document
Dim original As PdfDocument = PdfDocument.FromFile(inputPath)
' Step 1: Sanitize to remove active content
Dim sanitized As PdfDocument = Cleaner.SanitizeWithSvg(original)
' Step 2: Clean metadata
sanitized.MetaData.Author = "Processed Document"
sanitized.MetaData.Creator = "Secure Processor"
sanitized.MetaData.Producer = ""
sanitized.MetaData.CreationDate = DateTime.Now
sanitized.MetaData.ModifiedDate = DateTime.Now
' Remove all custom metadata
For Each key As String In sanitized.MetaData.Keys()
If key <> "Title" AndAlso key <> "Author" AndAlso key <> "CreationDate" AndAlso key <> "ModifiedDate" Then
sanitized.MetaData.RemoveMetaDataKey(key)
End If
Next
Return sanitized
End Function
End Class
' Usage
Module Program
Sub Main()
Dim processor As New SecureDocumentProcessor()
Dim safe As PdfDocument = processor.ProcessUntrustedDocument("email-attachment.pdf")
safe.SaveAs("email-attachment-safe.pdf")
End Sub
End Module
Bir PDF'i Güvenlik Açıkları İçin Nasıl Taramalıyım?
Belgeleri işleme ya da temizleme öncesinde, hangi potansiyel tehditleri içerdiğini değerlendirmek isteyebilirsiniz. IronPDF'nin Cleaner.ScanPdf yöntemi, belgeleri kötü amaçlı yazılım analizi ve tehdit algılamada yaygın olarak kullanılan desen tanımları olan YARA kurallarıyla inceler. Tarama, kötü amaçlı PDF dosyalarıyla ilişkili özellikleri tanımlar.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/scan-vulnerabilities.cs
using IronPdf;
// Load the document to scan
PdfDocument pdf = PdfDocument.FromFile("suspicious-document.pdf");
// Scan using default YARA rules
CleanerScanResult scanResult = Cleaner.ScanPdf(pdf);
// Check the scan results
bool threatsDetected = scanResult.IsDetected;
int riskCount = scanResult.Risks.Count;
// Process identified risks
if (scanResult.IsDetected)
{
foreach (var risk in scanResult.Risks)
{
// Handle each identified risk
}
// Sanitize the document before use
PdfDocument sanitized = Cleaner.SanitizeWithSvg(pdf);
sanitized.SaveAs("suspicious-document-safe.pdf");
}
Imports IronPdf
' Load the document to scan
Dim pdf As PdfDocument = PdfDocument.FromFile("suspicious-document.pdf")
' Scan using default YARA rules
Dim scanResult As CleanerScanResult = Cleaner.ScanPdf(pdf)
' Check the scan results
Dim threatsDetected As Boolean = scanResult.IsDetected
Dim riskCount As Integer = scanResult.Risks.Count
' Process identified risks
If scanResult.IsDetected Then
For Each risk In scanResult.Risks
' Handle each identified risk
Next
' Sanitize the document before use
Dim sanitized As PdfDocument = Cleaner.SanitizeWithSvg(pdf)
sanitized.SaveAs("suspicious-document-safe.pdf")
End If
Özel tespit gereksinimleri için özel YARA kural dosyaları sağlayabilirsiniz. Özel tehdit modellerine veya uyum ihtiyaçlarına sahip kuruluşlar, belirli güvenlik açığı kalıplarını hedefleyen kendi kural setlerini sıklıkla muhafaza ederler.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-redaction-csharp/scan-custom-yara.cs
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("incoming-document.pdf");
// Scan with custom YARA rules
string[] customYaraFiles = { "corporate-rules.yar", "industry-specific.yar" };
CleanerScanResult result = Cleaner.ScanPdf(pdf, customYaraFiles);
if (result.IsDetected)
{
// Document triggered custom rules and requires review or sanitization
PdfDocument sanitized = Cleaner.SanitizeWithSvg(pdf);
sanitized.SaveAs("incoming-document-safe.pdf");
}
Imports IronPdf
Dim pdf As PdfDocument = PdfDocument.FromFile("incoming-document.pdf")
' Scan with custom YARA rules
Dim customYaraFiles As String() = {"corporate-rules.yar", "industry-specific.yar"}
Dim result As CleanerScanResult = Cleaner.ScanPdf(pdf, customYaraFiles)
If result.IsDetected Then
' Document triggered custom rules and requires review or sanitization
Dim sanitized As PdfDocument = Cleaner.SanitizeWithSvg(pdf)
sanitized.SaveAs("incoming-document-safe.pdf")
End If
Döküman kabul iş akışlarına taramayı entegre etmek, güvenlik kararlarını otomatikleştirmeye yardımcı olur:
using IronPdf;
using System;
using System.IO;
public enum DocumentSafetyLevel
{
Safe,
Suspicious,
Dangerous
}
public class DocumentSecurityGateway
{
public DocumentSafetyLevel EvaluateDocument(string filePath)
{
PdfDocument pdf = PdfDocument.FromFile(filePath);
CleanerScanResult scan = Cleaner.ScanPdf(pdf);
if (!scan.IsDetected)
{
return DocumentSafetyLevel.Safe;
}
// Evaluate severity based on number of risks
if (scan.Risks.Count > 5)
{
return DocumentSafetyLevel.Dangerous;
}
return DocumentSafetyLevel.Suspicious;
}
public PdfDocument ProcessIncomingDocument(string filePath, string outputDirectory)
{
DocumentSafetyLevel safety = EvaluateDocument(filePath);
string fileName = Path.GetFileName(filePath);
switch (safety)
{
case DocumentSafetyLevel.Safe:
return PdfDocument.FromFile(filePath);
case DocumentSafetyLevel.Suspicious:
PdfDocument suspicious = PdfDocument.FromFile(filePath);
return Cleaner.SanitizeWithSvg(suspicious);
case DocumentSafetyLevel.Dangerous:
throw new SecurityException($"Document {fileName} contains dangerous content");
default:
throw new InvalidOperationException("Unknown safety level");
}
}
}
using IronPdf;
using System;
using System.IO;
public enum DocumentSafetyLevel
{
Safe,
Suspicious,
Dangerous
}
public class DocumentSecurityGateway
{
public DocumentSafetyLevel EvaluateDocument(string filePath)
{
PdfDocument pdf = PdfDocument.FromFile(filePath);
CleanerScanResult scan = Cleaner.ScanPdf(pdf);
if (!scan.IsDetected)
{
return DocumentSafetyLevel.Safe;
}
// Evaluate severity based on number of risks
if (scan.Risks.Count > 5)
{
return DocumentSafetyLevel.Dangerous;
}
return DocumentSafetyLevel.Suspicious;
}
public PdfDocument ProcessIncomingDocument(string filePath, string outputDirectory)
{
DocumentSafetyLevel safety = EvaluateDocument(filePath);
string fileName = Path.GetFileName(filePath);
switch (safety)
{
case DocumentSafetyLevel.Safe:
return PdfDocument.FromFile(filePath);
case DocumentSafetyLevel.Suspicious:
PdfDocument suspicious = PdfDocument.FromFile(filePath);
return Cleaner.SanitizeWithSvg(suspicious);
case DocumentSafetyLevel.Dangerous:
throw new SecurityException($"Document {fileName} contains dangerous content");
default:
throw new InvalidOperationException("Unknown safety level");
}
}
}
Imports IronPdf
Imports System
Imports System.IO
Public Enum DocumentSafetyLevel
Safe
Suspicious
Dangerous
End Enum
Public Class DocumentSecurityGateway
Public Function EvaluateDocument(filePath As String) As DocumentSafetyLevel
Dim pdf As PdfDocument = PdfDocument.FromFile(filePath)
Dim scan As CleanerScanResult = Cleaner.ScanPdf(pdf)
If Not scan.IsDetected Then
Return DocumentSafetyLevel.Safe
End If
' Evaluate severity based on number of risks
If scan.Risks.Count > 5 Then
Return DocumentSafetyLevel.Dangerous
End If
Return DocumentSafetyLevel.Suspicious
End Function
Public Function ProcessIncomingDocument(filePath As String, outputDirectory As String) As PdfDocument
Dim safety As DocumentSafetyLevel = EvaluateDocument(filePath)
Dim fileName As String = Path.GetFileName(filePath)
Select Case safety
Case DocumentSafetyLevel.Safe
Return PdfDocument.FromFile(filePath)
Case DocumentSafetyLevel.Suspicious
Dim suspicious As PdfDocument = PdfDocument.FromFile(filePath)
Return Cleaner.SanitizeWithSvg(suspicious)
Case DocumentSafetyLevel.Dangerous
Throw New SecurityException($"Document {fileName} contains dangerous content")
Case Else
Throw New InvalidOperationException("Unknown safety level")
End Select
End Function
End Class
Tam Bir Redaksiyon ve Temizleme İşleme Çizelgesi Nasıl Oluştururum?
Üretim dökuman işleme, genellikle çeşitli koruma tekniklerini bütünlüklü bir iş akışına entegre etmeyi gerektirir. Tam bir işleme hattı, gelen belgeleri tehditlere karşı tarayabilir, ilk taramayı geçenleri temizleyebilir, metin ve bölge redaksiyonları uygulayabilir, metadata'yı soyabilir ve alınan tüm işlemleri belgeleyen denetim günlüğü üretebilir. Bu örnek, böyle bir entegre yaklaşımı gösterir.
using IronPdf;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
public class DocumentProcessingResult
{
public string OriginalFile { get; set; }
public string OutputFile { get; set; }
public bool WasSanitized { get; set; }
public int TextRedactionsApplied { get; set; }
public int RegionRedactionsApplied { get; set; }
public bool MetadataCleaned { get; set; }
public List<string> SensitiveDataTypesFound { get; set; } = new List<string>();
public DateTime ProcessedAt { get; set; }
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
public class ComprehensiveDocumentProcessor
{
// Sensitive data patterns
private readonly Dictionary<string, string> _sensitivePatterns = new Dictionary<string, string>
{
{ "SSN", @"\b\d{3}-\d{2}-\d{4}\b" },
{ "Credit Card", @"\b(?:\d{4}[-\s]?){3}\d{1,4}\b" },
{ "Email", @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" },
{ "Phone", @"\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b" }
};
// Standard regions to redact (signature areas, photo locations)
private readonly List<RectangleF> _standardRedactionRegions = new List<RectangleF>
{
new RectangleF(72, 72, 200, 50), // Bottom left signature
new RectangleF(350, 72, 200, 50) // Bottom right signature
};
private readonly string _organizationName;
public ComprehensiveDocumentProcessor(string organizationName)
{
_organizationName = organizationName;
}
public DocumentProcessingResult ProcessDocument(
string inputPath,
string outputPath,
bool sanitize = true,
bool redactPatterns = true,
bool redactRegions = true,
bool cleanMetadata = true,
List<string> additionalTermsToRedact = null)
{
var result = new DocumentProcessingResult
{
OriginalFile = inputPath,
OutputFile = outputPath,
ProcessedAt = DateTime.Now
};
try
{
// Load the document
PdfDocument pdf = PdfDocument.FromFile(inputPath);
// Step 1: Security scan
CleanerScanResult scanResult = Cleaner.ScanPdf(pdf);
if (scanResult.IsDetected && scanResult.Risks.Count > 10)
{
throw new SecurityException("Document contains too many security risks to process");
}
// Step 2: Sanitization (if needed or requested)
if (sanitize || scanResult.IsDetected)
{
pdf = Cleaner.SanitizeWithSvg(pdf);
result.WasSanitized = true;
}
// Step 3: Pattern-based text redaction
if (redactPatterns)
{
string fullText = pdf.ExtractAllText();
HashSet<string> valuesToRedact = new HashSet<string>();
foreach (var pattern in _sensitivePatterns)
{
Regex regex = new Regex(pattern.Value, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(fullText);
if (matches.Count > 0)
{
result.SensitiveDataTypesFound.Add($"{pattern.Key} ({matches.Count})");
foreach (Match match in matches)
{
valuesToRedact.Add(match.Value);
}
}
}
// Apply redactions
foreach (string value in valuesToRedact)
{
pdf.RedactTextOnAllPages(value);
result.TextRedactionsApplied++;
}
}
// Step 4: Additional specific terms
if (additionalTermsToRedact != null)
{
foreach (string term in additionalTermsToRedact)
{
pdf.RedactTextOnAllPages(term);
result.TextRedactionsApplied++;
}
}
// Step 5: Region-based redaction
if (redactRegions)
{
foreach (RectangleF region in _standardRedactionRegions)
{
pdf.RedactRegionsOnAllPages(region);
result.RegionRedactionsApplied++;
}
}
// Step 6: Metadata cleaning
if (cleanMetadata)
{
pdf.MetaData.Author = _organizationName;
pdf.MetaData.Creator = $"{_organizationName} Document Processor";
pdf.MetaData.Producer = "";
pdf.MetaData.Subject = "";
pdf.MetaData.Keywords = "";
pdf.MetaData.CreationDate = DateTime.Now;
pdf.MetaData.ModifiedDate = DateTime.Now;
result.MetadataCleaned = true;
}
// Step 7: Save the processed document
pdf.SaveAs(outputPath);
result.Success = true;
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = ex.Message;
}
return result;
}
}
// Usage example
class Program
{
static void Main()
{
var processor = new ComprehensiveDocumentProcessor("Acme Corporation");
// Process a single document with all protections
var result = processor.ProcessDocument(
inputPath: "customer-application.pdf",
outputPath: "customer-application-redacted.pdf",
sanitize: true,
redactPatterns: true,
redactRegions: true,
cleanMetadata: true,
additionalTermsToRedact: new List<string> { "Project Alpha", "Internal Use Only" }
);
// Batch process multiple documents
string[] inputFiles = Directory.GetFiles("incoming", "*.pdf");
foreach (string file in inputFiles)
{
string outputFile = Path.Combine("processed", Path.GetFileName(file));
processor.ProcessDocument(file, outputFile);
}
}
}
using IronPdf;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
public class DocumentProcessingResult
{
public string OriginalFile { get; set; }
public string OutputFile { get; set; }
public bool WasSanitized { get; set; }
public int TextRedactionsApplied { get; set; }
public int RegionRedactionsApplied { get; set; }
public bool MetadataCleaned { get; set; }
public List<string> SensitiveDataTypesFound { get; set; } = new List<string>();
public DateTime ProcessedAt { get; set; }
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
public class ComprehensiveDocumentProcessor
{
// Sensitive data patterns
private readonly Dictionary<string, string> _sensitivePatterns = new Dictionary<string, string>
{
{ "SSN", @"\b\d{3}-\d{2}-\d{4}\b" },
{ "Credit Card", @"\b(?:\d{4}[-\s]?){3}\d{1,4}\b" },
{ "Email", @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" },
{ "Phone", @"\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b" }
};
// Standard regions to redact (signature areas, photo locations)
private readonly List<RectangleF> _standardRedactionRegions = new List<RectangleF>
{
new RectangleF(72, 72, 200, 50), // Bottom left signature
new RectangleF(350, 72, 200, 50) // Bottom right signature
};
private readonly string _organizationName;
public ComprehensiveDocumentProcessor(string organizationName)
{
_organizationName = organizationName;
}
public DocumentProcessingResult ProcessDocument(
string inputPath,
string outputPath,
bool sanitize = true,
bool redactPatterns = true,
bool redactRegions = true,
bool cleanMetadata = true,
List<string> additionalTermsToRedact = null)
{
var result = new DocumentProcessingResult
{
OriginalFile = inputPath,
OutputFile = outputPath,
ProcessedAt = DateTime.Now
};
try
{
// Load the document
PdfDocument pdf = PdfDocument.FromFile(inputPath);
// Step 1: Security scan
CleanerScanResult scanResult = Cleaner.ScanPdf(pdf);
if (scanResult.IsDetected && scanResult.Risks.Count > 10)
{
throw new SecurityException("Document contains too many security risks to process");
}
// Step 2: Sanitization (if needed or requested)
if (sanitize || scanResult.IsDetected)
{
pdf = Cleaner.SanitizeWithSvg(pdf);
result.WasSanitized = true;
}
// Step 3: Pattern-based text redaction
if (redactPatterns)
{
string fullText = pdf.ExtractAllText();
HashSet<string> valuesToRedact = new HashSet<string>();
foreach (var pattern in _sensitivePatterns)
{
Regex regex = new Regex(pattern.Value, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(fullText);
if (matches.Count > 0)
{
result.SensitiveDataTypesFound.Add($"{pattern.Key} ({matches.Count})");
foreach (Match match in matches)
{
valuesToRedact.Add(match.Value);
}
}
}
// Apply redactions
foreach (string value in valuesToRedact)
{
pdf.RedactTextOnAllPages(value);
result.TextRedactionsApplied++;
}
}
// Step 4: Additional specific terms
if (additionalTermsToRedact != null)
{
foreach (string term in additionalTermsToRedact)
{
pdf.RedactTextOnAllPages(term);
result.TextRedactionsApplied++;
}
}
// Step 5: Region-based redaction
if (redactRegions)
{
foreach (RectangleF region in _standardRedactionRegions)
{
pdf.RedactRegionsOnAllPages(region);
result.RegionRedactionsApplied++;
}
}
// Step 6: Metadata cleaning
if (cleanMetadata)
{
pdf.MetaData.Author = _organizationName;
pdf.MetaData.Creator = $"{_organizationName} Document Processor";
pdf.MetaData.Producer = "";
pdf.MetaData.Subject = "";
pdf.MetaData.Keywords = "";
pdf.MetaData.CreationDate = DateTime.Now;
pdf.MetaData.ModifiedDate = DateTime.Now;
result.MetadataCleaned = true;
}
// Step 7: Save the processed document
pdf.SaveAs(outputPath);
result.Success = true;
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = ex.Message;
}
return result;
}
}
// Usage example
class Program
{
static void Main()
{
var processor = new ComprehensiveDocumentProcessor("Acme Corporation");
// Process a single document with all protections
var result = processor.ProcessDocument(
inputPath: "customer-application.pdf",
outputPath: "customer-application-redacted.pdf",
sanitize: true,
redactPatterns: true,
redactRegions: true,
cleanMetadata: true,
additionalTermsToRedact: new List<string> { "Project Alpha", "Internal Use Only" }
);
// Batch process multiple documents
string[] inputFiles = Directory.GetFiles("incoming", "*.pdf");
foreach (string file in inputFiles)
{
string outputFile = Path.Combine("processed", Path.GetFileName(file));
processor.ProcessDocument(file, outputFile);
}
}
}
Imports IronPdf
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Text.RegularExpressions
Public Class DocumentProcessingResult
Public Property OriginalFile As String
Public Property OutputFile As String
Public Property WasSanitized As Boolean
Public Property TextRedactionsApplied As Integer
Public Property RegionRedactionsApplied As Integer
Public Property MetadataCleaned As Boolean
Public Property SensitiveDataTypesFound As List(Of String) = New List(Of String)()
Public Property ProcessedAt As DateTime
Public Property Success As Boolean
Public Property ErrorMessage As String
End Class
Public Class ComprehensiveDocumentProcessor
' Sensitive data patterns
Private ReadOnly _sensitivePatterns As Dictionary(Of String, String) = New Dictionary(Of String, String) From {
{"SSN", "\b\d{3}-\d{2}-\d{4}\b"},
{"Credit Card", "\b(?:\d{4}[-\s]?){3}\d{1,4}\b"},
{"Email", "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"},
{"Phone", "\b(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]?\d{4}\b"}
}
' Standard regions to redact (signature areas, photo locations)
Private ReadOnly _standardRedactionRegions As List(Of RectangleF) = New List(Of RectangleF) From {
New RectangleF(72, 72, 200, 50), ' Bottom left signature
New RectangleF(350, 72, 200, 50) ' Bottom right signature
}
Private ReadOnly _organizationName As String
Public Sub New(organizationName As String)
_organizationName = organizationName
End Sub
Public Function ProcessDocument(
inputPath As String,
outputPath As String,
Optional sanitize As Boolean = True,
Optional redactPatterns As Boolean = True,
Optional redactRegions As Boolean = True,
Optional cleanMetadata As Boolean = True,
Optional additionalTermsToRedact As List(Of String) = Nothing) As DocumentProcessingResult
Dim result As New DocumentProcessingResult With {
.OriginalFile = inputPath,
.OutputFile = outputPath,
.ProcessedAt = DateTime.Now
}
Try
' Load the document
Dim pdf As PdfDocument = PdfDocument.FromFile(inputPath)
' Step 1: Security scan
Dim scanResult As CleanerScanResult = Cleaner.ScanPdf(pdf)
If scanResult.IsDetected AndAlso scanResult.Risks.Count > 10 Then
Throw New SecurityException("Document contains too many security risks to process")
End If
' Step 2: Sanitization (if needed or requested)
If sanitize OrElse scanResult.IsDetected Then
pdf = Cleaner.SanitizeWithSvg(pdf)
result.WasSanitized = True
End If
' Step 3: Pattern-based text redaction
If redactPatterns Then
Dim fullText As String = pdf.ExtractAllText()
Dim valuesToRedact As New HashSet(Of String)()
For Each pattern In _sensitivePatterns
Dim regex As New Regex(pattern.Value, RegexOptions.IgnoreCase)
Dim matches As MatchCollection = regex.Matches(fullText)
If matches.Count > 0 Then
result.SensitiveDataTypesFound.Add($"{pattern.Key} ({matches.Count})")
For Each match As Match In matches
valuesToRedact.Add(match.Value)
Next
End If
Next
' Apply redactions
For Each value As String In valuesToRedact
pdf.RedactTextOnAllPages(value)
result.TextRedactionsApplied += 1
Next
End If
' Step 4: Additional specific terms
If additionalTermsToRedact IsNot Nothing Then
For Each term As String In additionalTermsToRedact
pdf.RedactTextOnAllPages(term)
result.TextRedactionsApplied += 1
Next
End If
' Step 5: Region-based redaction
If redactRegions Then
For Each region As RectangleF In _standardRedactionRegions
pdf.RedactRegionsOnAllPages(region)
result.RegionRedactionsApplied += 1
Next
End If
' Step 6: Metadata cleaning
If cleanMetadata Then
pdf.MetaData.Author = _organizationName
pdf.MetaData.Creator = $"{_organizationName} Document Processor"
pdf.MetaData.Producer = ""
pdf.MetaData.Subject = ""
pdf.MetaData.Keywords = ""
pdf.MetaData.CreationDate = DateTime.Now
pdf.MetaData.ModifiedDate = DateTime.Now
result.MetadataCleaned = True
End If
' Step 7: Save the processed document
pdf.SaveAs(outputPath)
result.Success = True
Catch ex As Exception
result.Success = False
result.ErrorMessage = ex.Message
End Try
Return result
End Function
End Class
' Usage example
Class Program
Shared Sub Main()
Dim processor As New ComprehensiveDocumentProcessor("Acme Corporation")
' Process a single document with all protections
Dim result = processor.ProcessDocument(
inputPath:="customer-application.pdf",
outputPath:="customer-application-redacted.pdf",
sanitize:=True,
redactPatterns:=True,
redactRegions:=True,
cleanMetadata:=True,
additionalTermsToRedact:=New List(Of String) From {"Project Alpha", "Internal Use Only"}
)
' Batch process multiple documents
Dim inputFiles As String() = Directory.GetFiles("incoming", "*.pdf")
For Each file As String In inputFiles
Dim outputFile As String = Path.Combine("processed", Path.GetFileName(file))
processor.ProcessDocument(file, outputFile)
Next
End Sub
End Class
Giriş
SSN'leri, kredi kartı numaralarını, e-posta adreslerini ve imza bloklarını içeren çoklu tipte hassas veri içeren bir müşteri başvuru formu, kapsamlı bir koruma gerektirir.
Örnek Çıktı
Bu kapsamlı işleyici, bu kılavuzda ele alınan tüm teknikleri tek bir yapılandırılabilir sınıfta birleştirir. Tehditleri tarar, gerektiğinde temizler, hassas kalıpları bulur ve redakte eder, bölge redaksiyonları uygular, metadata'yı temizler ve detaylı raporlar üretir. Özel gereksinimlerinize uygun olarak hassasiyet kalıplarını, redaksiyon bölgelerini ve işlem tercihlerini ayarlayabilirsiniz.
Sonraki Adımlar
PDF belgelerinde hassas bilgileri korumak yüzeysel önlemlerden fazlasını gerektirir. Gerçek redaksiyon, içeriği belge yapısından kalıcı olarak ortadan kaldırır. Desene dayalı eşleştirme Sosyal Güvenlik numaraları, kredi kartı bilgileri ve e-posta adresleri gibi verilerin keşfini ve kaldırılmasını otomatikleştirir. Bölge-tabanlı redaksiyon, metin eşleştirmenin çözemeyeceği imzalar, fotoğraflar ve diğer grafik unsurları işler. Metadata temizliği, yazarları, zaman damgalarını veya iç dosya yollarını açığa çıkarabilecek gizli bilgileri ortadan kaldırır. Temizleme, güvenlik riskleri taşıyan yerleşik komut dosyalarını ve aktif içeriği kaldırır.
IronPDF, bu yeteneklerin tümünü, C# ve .NET geliştirme uygulamalarıyla doğal bir şekilde bütünleşen tutarlı ve iyi tasarlanmış bir API aracılığıyla sunar. Bu kılavuzda gösterilen yöntemler, tekli belgeleri ele alır veya binlerce dosyayı toplu işleme ölçeğinde ele alır. İster sağlık verileri için uyum iş akışları oluşturuyor olun, ister keşif için yasal belgeler hazırlıyor olun, ya da sadece şirket içi raporların güvenli bir şekilde dışa paylaşılabilmesini sağlıyor olun, bu teknikler sorumlu döküman işlemenin temelini oluşturur. Kapsamlı güvenlik kapsaması için, redaksiyonu şifre koruma ve izinlerle ve dijital imzalarla birleştirin.
Yapmaya hazır mısınız? IronPDF İndir ve ücretsiz deneme ile deneyin. Kütüphane, ücretsiz bir geliştirme lisansı içerir, böylece üretim lisansına geçmeden önce, redaksiyon, metin ayıklama ve temizleme yeteneklerini tam olarak değerlendirebilirsiniz. Uygulama ya da uyum iş akışları hakkında sorularınız varsa, mühendislik destek ekibimize ulaşın.
Sıkça Sorulan Sorular
PDF sansürleme nedir?
PDF sansürleme, bir PDF belgesinden hassas bilgilerin kalıcı olarak kaldırılması işlemi anlamına gelir. Bu, gizlilik veya uyum nedenleriyle gizlenmesi gereken metin, görüntü ve meta verileri içerebilir.
C# kullanarak bir PDF'de bilgileri nasıl sansürleyebilirim?
IronPDF kullanarak C# dilinde bir PDF belgesindeki bilgileri sansürleyebilirsiniz. PDF belgelerinden metin, görüntü ve meta verileri kalıcı olarak kaldırmanıza veya gizlemenize olanak tanır; böylece gizlilik ve uyumluluk standartlarını karşılamalarını sağlar.
Uyumluluk için PDF sansürlemesi neden önemlidir?
PDF sansürleme, HIPAA, GDPR ve PCI DSS gibi standartlarla uyumluluk için çok önemlidir; çünkü hassas verileri güvence altına alır ve gizli bilgilere yetkisiz erişimi engeller.
IronPDF, bir PDF'nin tüm bölgelerini sansürleyebilir mi?
Evet, IronPDF bir PDF'nin tüm bölgelerini sansürleyebilir. Bu, güvenlik amaçları için belgede gizlenmesi veya kaldırılması gereken belirli alanları tanımlamanıza olanak tanır.
IronPDF kullanılarak hangi veri türleri sansürlenebilir?
IronPDF, metin, görüntü ve meta verileri dahil olmak üzere çeşitli veri türlerini PDF belgelerinden sansürleyebilir; bu da kapsamlı veri mahremiyeti ve güvenliği sağlar.
IronPDF, belgeleri temizlemeyi destekliyor mu?
Evet, IronPDF belgeleri temizlemeyi destekler; bu da gizli verileri veya görünmeyen ancak gizliliği tehdit edebilecek meta verileri temizlemek üzere bir PDF belgesinin düzenlenmesini içerir.
IronPDF ile PDF sansürlemesi otomatikleştirilebilir mi?
Evet, IronPDF, PDF sansürleme süreçlerini C# dilinde otomatikleştirmenize olanak tanır; bu da hassas veri kaldırımı gerektiren büyük hacimli belgeleri yönetmeyi kolaylaştırır.
IronPDF, sansürlemenin kalıcılığını nasıl sağlar?
IronPDF, seçilen metin ve görüntüleri belgede sadece karartmak yerine kalıcı olarak kaldırarak sansürlemenin kalıcılığını sağlar; bu da geri alınamayacakları veya görüntülenemeyecekleri anlamına gelir.
IronPDF, bir PDF'teki meta verileri düzenleyebilir mi?
Evet, IronPDF bir PDF belgesindeki meta verileri düzenleyebilir ve gizli veya arka plan verileri dahil olmak üzere tüm hassas verilerin tamamen kaldırıldığından emin olur.
IronPDF'yi PDF düzenlemesi için kullanmanın faydaları nelerdir?
IronPDF'yi PDF düzenlemesi için kullanmak, veri koruma düzenlemelerine uyum sağlama, belge güvenliğini artırma ve hassas bilgileri yönetmek için verimli ve otomatik bir süreç sunma gibi faydalar sağlar.

