diff --git a/pdf/arabic/net/digital-signatures/_index.md b/pdf/arabic/net/digital-signatures/_index.md index 49e8b487d7..7b01185588 100644 --- a/pdf/arabic/net/digital-signatures/_index.md +++ b/pdf/arabic/net/digital-signatures/_index.md @@ -18,10 +18,8 @@ ## البرامج التعليمية المتاحة ### [التوقيعات الرقمية في ملفات PDF باستخدام Aspose.PDF لـ .NET: دليل شامل](./digital-signature-aspose-pdf-net-tutorial/) -تعرّف على كيفية تطبيق التوقيعات الرقمية في ملفات PDF باستخدام Aspose.PDF لـ .NET. يغطي هذا الدليل الإعداد، وعمليات التوقيع، وإدارة ظهور التوقيعات. ### [التوقيع رقميًا على ملف PDF بمظهر مخصص باستخدام Aspose.PDF لـ .NET: دليل خطوة بخطوة](./digitally-sign-pdf-custom-appearance-aspose-pdf-net/) -تعرّف على كيفية التوقيع الرقمي على ملف PDF بمظهر مخصص باستخدام Aspose.PDF لـ .NET. يغطي هذا الدليل إعداد التوقيعات الرقمية وتخصيصها وتطبيقاتها العملية في مستنداتك. ### [استخراج معلومات التوقيع الرقمي من ملفات PDF باستخدام Aspose.PDF](./extract-digital-signature-info-from-pdfs-aspose-pdf/) برنامج تعليمي لبرمجة Aspose.PDF Net @@ -59,6 +57,9 @@ ### [التحقق من توقيع PDF باستخدام Aspose – تحويل PDF إلى HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) تعرّف على كيفية التحقق من توقيع PDF وتحويله إلى HTML باستخدام Aspose. +### [التحقق من توقيع PDF وإدراج قائمة توقيعات PDF باستخدام Aspose.PDF – دليل شامل](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +دليل كامل يوضح كيفية التحقق من توقيع PDF واستخراج جميع التوقيعات المضمنة باستخدام Aspose.PDF في .NET. + ## موارد إضافية - [توثيق Aspose.PDF للشبكة](https://docs.aspose.com/pdf/net/) diff --git a/pdf/arabic/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/arabic/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..d361221412 --- /dev/null +++ b/pdf/arabic/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: تحقق من صحة توقيع PDF وقائمة توقيعات PDF باستخدام Aspose.PDF في C#. كود + خطوة بخطوة، المشكلات الشائعة، وأفضل الممارسات للتعامل الآمن مع المستندات. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: ar +lastmod: 2026-07-26 +og_description: تحقق من صحة توقيع PDF وقم بإدراج توقيعات PDF باستخدام Aspose.PDF. + اتبع هذا الدليل العملي لتأمين ملفات PDF في C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: التحقق من توقيع PDF وقائمة توقيعات PDF – دليل Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: التحقق من توقيع PDF وإدراج توقيعات PDF باستخدام Aspose.PDF – دليل كامل +url: /ar/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحقق من توقيع PDF وقائمة توقيعات PDF باستخدام Aspose.PDF – دليل كامل + +هل تساءلت يومًا كيف **validate PDF signature** في تطبيق .NET دون أن تشعر بالإحباط؟ لست وحدك. سواء كنت تبني منصة توقيع إلكتروني أو تحتاج فقط إلى التأكد من أن العقد المستلم لم يتم العبث به، فإن القدرة على **list PDF signatures** والتحقق من كل منها هي مهارة أساسية. + +في هذا الدرس سنستعرض مثالًا قابلاً للتنفيذ بالكامل يقوم بتحميل ملف PDF موقّع، ويعدّ كل توقيع مدمج، ويتحقق مما إذا كان أي منها قد تم اختراقه، ثم يطبع نتيجة واضحة إلى وحدة التحكم. لا مراجع غامضة—فقط الكود الذي يمكنك نسخه‑لصقه، بالإضافة إلى “السبب” وراء كل خطوة. + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من وجود ما يلي: + +- **Aspose.PDF for .NET** الإصدار 25.3 أو أحدث (خاصية `IsCompromised` ظهرت في 25.3). +- بيئة تطوير .NET (Visual Studio 2022، Rider، أو سطر أوامر `dotnet`). +- ملف PDF موقّع يمكنك اختبارّه (يمكنك إنشاء واحد باستخدام Adobe Acrobat أو أي أداة توقيع إلكتروني). + +إذا كان أيٌ من هذه مفقودًا، قم بتثبيت حزمة NuGet أولاً: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **نصيحة احترافية:** استهدف .NET 6 أو أحدث للحصول على أفضل أداء ودعم طويل الأمد. + +## الخطوة 1: تحميل مستند PDF + +أول شيء تحتاج إلى القيام به هو فتح ملف PDF. فئة `Document` في Aspose.PDF تتعامل مع كل شيء من التحليل إلى العرض. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*لماذا هذا مهم:* تحميل الملف يُنشئ تمثيلًا في الذاكرة يتيح لك استعلام التوقيعات دون الحاجة إلى الوصول إلى نظام الملفات مرة أخرى. كما أنه يتحقق من بنية PDF مبكرًا، لذا ستحصل على استثناء فورًا إذا كان الملف تالفًا. + +## الخطوة 2: **List PDF Signatures** – تعداد جميع التوقيعات المدمجة + +يمكن أن يحتوي PDF موقّع على عدة توقيعات (تخيل عقدًا متعدد الصفحات حيث يوقع كل طرف صفحة مختلفة). Aspose.PDF يوفّرها عبر مجموعة `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*ما تراه:* الحلقة تطبع تفاصيل **list PDF signatures** مثل اسم الموقّع، السبب، الموقع، والطابع الزمني. هذا مفيد لسجلات التدقيق أو عروض واجهة المستخدم. + +## الخطوة 3: **Validate PDF Signature** – التحقق من الاختراق + +الآن يأتي الجزء الحاسم من الأمان: التأكد من أن لا أحد من التوقيعات قد تم تعديلها بعد التوقيع. بدءًا من الإصدار 25.3، توفر Aspose.PDF العلامة `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*لماذا يجب عليك استخدام `IsCompromised`*: التحقق التقليدي يقتصر فقط على سلسلة التشفير (صلاحية الشهادة، الإلغاء، إلخ). `IsCompromised` يضيف طبقة إضافية باكتشاف أي تغييرات بعد التوقيع على المستند—وهو بالضبط ما تحتاجه عندما **validate PDF signature** ضد العبث. + +## الخطوة 4: معالجة نتائج التحقق + +اعتمادًا على النتيجة، قد ترغب في اتخاذ إجراءات مختلفة. إليك نمطًا سريعًا يمكنك تعديله: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*ملاحظة حالة حافة:* إذا كان PDF يحتوي على توقيع **مُعتمد** (التوقيع الأول الذي يقفل المستند)، فإن أي تعديل لاحق يمكن أن يبطل الملف بالكامل، حتى وإن بدت التوقيعات اللاحقة سليمة. اعتبر أي قيمة `true` من `IsCompromised` إشارة تحذيرية. + +## مثال عملي كامل + +بدمج كل ما سبق، إليك برنامجًا واحدًا مكتملًا يمكنك تجميعه وتشغيله: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**الناتج المتوقع** (مع وجود توقيع صالح واحد وآخر مُتَلاعب به): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## المشكلات الشائعة وكيفية تجنّبها + +| المشكلة | لماذا يحدث | الحل | +|---------|------------|------| +| **Missing Aspose.PDF version** | تم تقديم `IsCompromised` في 25.3. الحزم القديمة تُجمّع لكنها تُطلق `MissingMethodException`. | تأكد من أن مرجع NuGet الخاص بك هو `>= 25.3`. | +| **Null `SignatureInfo`** | بعض ملفات PDF تحتوي على فتحات توقيع فارغة لا تزال تظهر في المجموعة. | احرص على التحقق بـ `if (signatureInfo != null)` قبل التحقق. | +| **Performance hit on large PDFs** | التحقق من كل توقيع يقرأ الملف بالكامل في كل مرة. | خزن `PdfSignatureValidator` في ذاكرة مؤقتة أو عالج التوقيعات دفعةً إذا كنت تحتاج فقط إلى ملخص منطقي. | +| **Certificate revocation not checked** | `IsCompromised` يخبرك فقط عن تغييرات المستند، وليس عن حالة الشهادة. | استخدم `PdfSignatureValidator.Validate()` بالإضافة إلى `IsCompromised` لإجراء فحوصات PKI كاملة. | + +## توسيع الحل + +إذا كنت تحتاج إلى **list PDF signatures** في واجهة مستخدم، ما عليك سوى تمرير كائنات `SignatureInfo` إلى شبكة بيانات. هل تريد تخزين نتائج التحقق في قاعدة بيانات؟ قم بتسلسل القيمة المنطقية `isCompromised` مع اسم الموقّع والطابع الزمني. + +مواضيع ذات صلة قد ترغب في استكشافها لاحقًا: + +- **Validate PDF signature against a trusted root CA** (استخدم `validator.Validate()`). +- **Extract embedded certificate details** (`validator.Certificate`). +- **Create digital signatures** مع Aspose.PDF (`PdfSignatureBuilder`). + +## الخلاصة + +أصبح لديك الآن طريقة عملية من البداية إلى النهاية **validate PDF signature** و **list PDF signatures** باستخدام Aspose.PDF for .NET. يوضح الكود بالضبط كيفية تحميل المستند، تعداد كل توقيع، فحص علامة `IsCompromised`، والتصرف بناءً على النتيجة—كل ذلك بصيغة صديقة لوحدة التحكم. + +جرّبها مع ملفات PDF الموقّعة الخاصة بك، واختبر توقيعات متعددة، ودمج المنطق في خط أنابيب معالجة المستندات الأكبر لديك. المستندات الآمنة لا تكون قوية إلا بقدر التحقق الذي تجريه، لذا حافظ على الفحوصات مشددة والسجلات دقيقة. + +هل لديك أسئلة أو ترغب في مشاركة حالة استخدام مميزة؟ اترك تعليقًا أدناه أو تواصل معي على GitHub. برمجة سعيدة! + +![تحقق من توقيع PDF](/images/validate-pdf-signature.png "لقطة شاشة لتطبيق C# في وحدة التحكم يتحقق من توقيع PDF باستخدام Aspose.PDF") + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تُبنى على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [How to Verify PDF – Validate PDF Signature with Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [How to Extract PDF Signature Information Using Aspose.PDF .NET: A Step-by-Step Guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [How to Extract Images from PDF Signature Fields using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/arabic/net/programming-with-operators/_index.md b/pdf/arabic/net/programming-with-operators/_index.md index 43ac049085..5d37d711ad 100644 --- a/pdf/arabic/net/programming-with-operators/_index.md +++ b/pdf/arabic/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ | [ارسم XForm على الصفحة](./draw-xform-on-page/) | تعلم كيفية رسم XForms في PDF باستخدام Aspose.PDF لـ .NET مع هذا الدليل الشامل خطوة بخطوة. | | [مشغلات PDF](./pdf-operators/) دليل خطوة بخطوة لاستخدام مُشغّلات PDF مع Aspose.PDF لـ .NET. أضف صورة إلى صفحة PDF وحدد موقعها. | [إزالة الكائنات الرسومية في ملف PDF](./remove-graphics-objects/) تعرّف على كيفية إزالة الكائنات الرسومية من ملف PDF باستخدام Aspose.PDF لـ .NET في هذا الدليل التفصيلي. بسّط مهام معالجة ملفات PDF. +| [إنشاء قاموس PDF فارغ في C# – دليل Aspose.Pdf الكامل](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | تعلم كيفية إنشاء قاموس PDF فارغ باستخدام Aspose.PDF لـ .NET في C# من خلال دليل شامل خطوة بخطوة. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/arabic/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/arabic/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..6081dce3ff --- /dev/null +++ b/pdf/arabic/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: إنشاء قاموس PDF فارغ باستخدام Aspose.Pdf في C#. تعلم خطوة بخطوة كيفية + إضافة حالة رسومية إلى قاموس ExtGState للتلاعب بملفات PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: ar +lastmod: 2026-07-26 +og_description: إنشاء قاموس PDF فارغ باستخدام Aspose.Pdf للغة C#. اتبع هذا الدليل + العملي لتعديل حالات الرسومات في ملفات PDF الخاصة بك. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: إنشاء قاموس PDF فارغ في C# – دليل Aspose.Pdf الكامل +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: إنشاء قاموس PDF فارغ في C# – دليل Aspose.Pdf الكامل +url: /ar/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء قاموس PDF فارغ في C# – دليل Aspose.Pdf الكامل + +هل تساءلت يومًا كيف **create empty PDF dictionary** عند تعديل حالة رسومات PDF؟ لست وحدك — يواجه العديد من المطورين هذه المشكلة عند محاولة ضبط الشفافية أو أوضاع الدمج برمجيًا. في هذا الدرس سنستعرض حلاً عمليًا باستخدام Aspose.Pdf لـ C#، موضحين بالضبط كيفية إدخال حالة رسومات جديدة في قاموس *ExtGState* لملف PDF موجود. + +سنتناول كل ما تحتاجه: تحميل ملف PDF، الوصول إلى قاموس الموارد الخاص به، بناء **CosPdfDictionary** جديد، وأخيرًا حفظ التغييرات. في النهاية ستحصل على نمط قابل لإعادة الاستخدام لأي تعديلات على *PDF graphics state* قد تحتاجها. + +--- + +## ما ستتعلمه + +- كيفية إنشاء كائنات **create empty PDF dictionary** باستخدام API منخفض المستوى لـ Aspose.Pdf. +- دور **ExtGState dictionary** في التحكم في شفافية الخط/الملء وأوضاع الدمج. +- نصائح عملية لتعامل مع ملفات PDF باستخدام C#، بما في ذلك معالجة الحالات الحدية عندما يكون القاموس مفقودًا. +- عينة شفرة كاملة قابلة للتنفيذ يمكنك نسخها ولصقها في مشروعك. + +### المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يعمل أيضًا مع .NET Framework 4.6+). +- نسخة مرخصة من **Aspose.Pdf for .NET** (الإصدار التجريبي المجاني يعمل للاختبار). +- إلمام أساسي بـ C# ومفاهيم PDF مثل الموارد وحالات الرسومات. + +إذا كان أي من ذلك غير مألوف لك، لا تقلق — يمكنك تثبيت Aspose.Pdf عبر NuGet (`Install-Package Aspose.Pdf`) والبقية مجرد C# عادي. + +--- + +## الخطوة 1 – تحميل مستند PDF + +أولًا، تحتاج إلى كائن `Document` يمثل الملف الذي تريد تحريره. تغليفه داخل كتلة `using` يضمن التخلص السليم. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*لماذا هذا مهم*: فتح الملف يمنحك الوصول إلى كائنات COS الداخلية (Canonical Object Structure)، حيث توجد **CosPdfDictionary**. بدون كائن المستند، لا يمكنك الوصول إلى قواميس الموارد التي تحتوي على مدخلات **ExtGState**. + +--- + +## الخطوة 2 – الوصول إلى قاموس موارد الصفحة الأولى + +صفحات PDF تخزن مواردها (الخطوط، الصور، حالات الرسومات، إلخ) في قاموس مخصص. سنختار الصفحة الأولى للبساطة، لكن نفس المنطق ينطبق على أي فهرس صفحة. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*نصيحة احترافية*: إذا كان ملف PDF يحتوي على صفحات متعددة بمجموعات موارد مختلفة، كرّر هذا الجزء لكل صفحة تحتاج إلى تعديلها. فئة `DictionaryEditor` هي غلاف مريح يتيح لك التعامل مع قاموس COS كـ .NET `Dictionary`. + +--- + +## الخطوة 3 – استرجاع أو تهيئة قاموس ExtGState + +قاموس **ExtGState** يحتوي على كائنات حالة رسومات مسماة (`GS0`, `GS1`, …). بعض ملفات PDF تحتويه بالفعل؛ البعض الآخر لا. سنسترجعه بأمان، وننشئ واحدًا فارغًا جديدًا إذا لزم الأمر. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*لماذا نفعل ذلك*: محاولة إضافة حالة رسومات إلى **ExtGState dictionary** غير موجود سيؤدي إلى استثناء. هذا الفحص الوقائي يجعل الكود قويًا لأي ملف PDF مدخل. + +--- + +## الخطوة 4 – بناء حالة رسومات جديدة باستخدام CosPdfDictionary + +الآن يأتي جوهر الدرس: **إنشاء قاموس PDF فارغ** يحدد حالة رسومات مخصصة. سنحدد شفافية الخط (`CA`)، شفافية التعبئة (`ca`)، ووضع الدمج (`BM`). يمكنك إضافة المزيد من المدخلات لاحقًا — هذه مجرد مجموعة ابتدائية. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*شرح*: +- `CA` و `ca` هما مفاتيح PDF قياسية تتحكم في شفافية الخط والملء على التوالي. +- `BM` يحدد وضع الدمج؛ “Normal” هو الافتراضي لكن يمكنك استخدام “Multiply”، “Screen”، إلخ، حسب احتياجات التصميم. +- باستخدام `CosPdfDictionary.CreateEmptyDictionary`، نحن **create empty PDF dictionary** كائنات نملأها لاحقًا بأزواج المفتاح/القيمة. + +--- + +## الخطوة 5 – إدراج حالة الرسومات الجديدة في ExtGState + +مع جاهزية حالة الرسومات، نضيفها ببساطة إلى **ExtGState dictionary** تحت اسم فريد (مثلاً `GS0`). إذا كنت تخطط لإضافة حالات متعددة، فقط زد اللاحقة. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*نصيحة*: قبل الإضافة، قد ترغب في التحقق مما إذا كان `GS0` موجودًا بالفعل لتجنب الكتابة فوقه. شرط سريع `if (!extGState.ContainsKey("GS0"))` ينجز المهمة. + +--- + +## الخطوة 6 – حفظ ملف PDF المعدل + +جميع التغييرات موجودة في الذاكرة حتى تقوم بحفظها. اختر مسار الإخراج المناسب لسير عملك. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*النتيجة*: افتح `output.pdf` في أي عارض PDF، ثم افحص موارد الصفحة (مثلاً باستخدام أداة فحص PDF). سترى مدخلاً جديدًا تحت **ExtGState** يسمى `GS0` مع المعلمات التي حددناها. + +--- + +## مثال كامل يعمل + +بجمع كل شيء معًا، إليك البرنامج الكامل جاهز للنسخ واللصق: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**الناتج المتوقع**: سيظهر `output.pdf` بنفس مظهر الملف الأصلي، لكن أي محتوى يشير لاحقًا إلى `GS0` (مثلاً عبر عامل `gs` في تدفق المحتوى) سيتبنى الشفافية ووضع الدمج المحددين. إذا لم يكن لديك مثل هذا المرجع بعد، يمكنك إضافته يدويًا أو عبر واجهات برمجة التطبيقات عالية المستوى لـ Aspose. + +--- + +## الأسئلة المتكررة والحالات الحدية + +| السؤال | الجواب | +|----------|--------| +| *ماذا لو كان ملف PDF يحتوي بالفعل على مدخل `ExtGState` باسم `GS0`؟* | تحقق من `extGState.ContainsKey("GS0")` قبل الإضافة. إذا كان موجودًا، إما أن تكتب فوقه عمدًا (`extGState["GS0"] = newGraphicsState`) أو تختار اسمًا جديدًا مثل `GS1`. | +| *هل يمكنني إضافة المزيد من المعلمات، مثل عرض الخط (`LW`) أو نمط الشرط (`D`)?* | بالطبع. فقط قم بتمديد مصفوفة `parameters` بإضافة مدخلات `KeyValuePair` إضافية. | +| *هل هذا النهج متوافق مع ملفات PDF المشفرة؟* | نعم، طالما أنك تزود كلمة المرور الصحيحة عند إنشاء كائن `Document` (`new Document(path, password)`). | +| *هل أحتاج إلى إغلاق المستند يدويًا؟* | عبارة `using` تعتني بالتخلص من الكائن، مما يضمن أيضًا تفريغ أي تغييرات معلقة. | +| *كيف يختلف هذا عن استخدام الفئة عالية المستوى `Graphics`؟* | واجهة برمجة التطبيقات عالية المستوى تُجرد القواميس الداخلية، وهو أمر ممتاز للمهام البسيطة. ومع ذلك، عندما تحتاج إلى تحكم دقيق في حالات الرسومات — مثل أوضاع الدمج المخصصة — يجب عليك العمل مع **CosPdfDictionary** منخفض المستوى، أي كائنات **create empty PDF dictionary** مباشرة. | + +--- + +## الخلاصة + +لقد أظهرنا للتو كيفية **create empty PDF dictionary** كائنات باستخدام Aspose.Pdf، وإدخال حالة رسومات مخصصة في **ExtGState dictionary**، وحفظ الملف المعدل — كل ذلك بلغة C# نظيفة ومألوفة. يتيح هذا النمط تحكمًا دقيقًا في الشفافية، أوضاع الدمج، وأي معلمات أخرى لحالة الرسومات معرفة في مواصفات PDF. + +من هنا قد ترغب في: + +- تطبيق حالة الرسومات الجديدة على محتوى الصفحة الحالي باستخدام عامل `gs`. +- بناء مكتبة من حالات الرسومات القابلة لإعادة الاستخدام للعلامة التجارية أو العلامات المائية. +- + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شفرة كاملة تعمل مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات إضافية في الـ API واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء خطوط متقطعة في ملفات PDF باستخدام Aspose.PDF لـ .NET: دليل خطوة بخطوة](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [إنشاء وتعبئة المستطيلات في ملفات PDF باستخدام Aspose.PDF لـ .NET: دليل خطوة بخطوة](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/chinese/net/digital-signatures/_index.md b/pdf/chinese/net/digital-signatures/_index.md index 40a1290a4f..c626ad8318 100644 --- a/pdf/chinese/net/digital-signatures/_index.md +++ b/pdf/chinese/net/digital-signatures/_index.md @@ -58,9 +58,13 @@ Aspose.PDF Net 代码教程 ### [在 C# 中验证 PDF 签名 – 验证数字签名 PDF 的完整指南](./verify-pdf-signature-in-c-complete-guide-to-validate-digital/) 提供在 C# 环境下使用 Aspose.PDF 验证 PDF 数字签名的完整步骤和代码示例。 + ### [加载 PDF 文档 C# – 转换为 PDF/X‑4 并列出签名](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) 演示如何使用 Aspose.PDF for .NET 加载 PDF 文档,转换为 PDF/X‑4 并列出其中的数字签名。 +### [使用 Aspose.PDF 验证 PDF 签名并列出 PDF 签名 – 完整指南](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +本完整指南演示如何使用 Aspose.PDF 验证 PDF 签名并列出文档中的所有签名,提供详细的 C# 示例代码。 + ### [使用 Aspose 验证 PDF 签名并将 PDF 转换为 HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) 了解如何使用 Aspose 验证 PDF 签名并将 PDF 转换为 HTML,以实现文档的安全展示。 diff --git a/pdf/chinese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/chinese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..ef1298e340 --- /dev/null +++ b/pdf/chinese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-07-26 +description: 使用 Aspose.PDF 在 C# 中验证 PDF 签名并列出 PDF 签名。逐步代码、常见陷阱以及安全文档处理的最佳实践。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: zh +lastmod: 2026-07-26 +og_description: 使用 Aspose.PDF 验证 PDF 签名并列出 PDF 签名。遵循本实用指南,在 C# 中保护 PDF。 +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: 验证 PDF 签名并列出 PDF 签名 – Aspose.PDF 使用指南 +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: 使用 Aspose.PDF 验证 PDF 签名并列出 PDF 签名 – 完整指南 +url: /zh/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.PDF 验证 PDF 签名并列出 PDF 签名 – 完整指南 + +有没有想过如何在 .NET 应用中 **validate PDF signature** 而不抓狂?你并不是唯一的。无论是构建电子签名平台,还是仅仅需要确保收到的合同未被篡改,能够 **list PDF signatures** 并验证每个签名都是必备技能。 + +在本教程中,我们将逐步演示一个完整可运行的示例,加载已签名的 PDF,枚举所有嵌入的签名,检查是否有被篡改的签名,并将清晰的结果打印到控制台。没有模糊的引用——只有可以复制粘贴的代码,以及每一步背后的“原因”。 + +## 前提条件 + +- **Aspose.PDF for .NET** version 25.3 或更高(`IsCompromised` 属性在 25.3 中出现)。 +- .NET 开发环境(Visual Studio 2022、Rider 或 `dotnet` CLI)。 +- 可用于测试的已签名 PDF 文件(可使用 Adobe Acrobat 或任何电子签名工具创建)。 + +如果缺少上述任何项,请先安装 NuGet 包: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** 目标 .NET 6 或更高,以获得最佳性能和长期支持。 + +## 步骤 1:加载 PDF 文档 + +首先需要做的事情是打开 PDF 文件。Aspose.PDF 的 `Document` 类负责从解析到渲染的所有工作。 + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*为什么重要:* 加载文件会创建一个内存中的表示,使您能够在不再次访问文件系统的情况下查询签名。它还会提前验证 PDF 结构,如果文件损坏会立即抛出异常。 + +## 步骤 2:**List PDF Signatures** – 枚举所有嵌入的签名 + +已签名的 PDF 可以包含多个签名(比如多页合同,每一方在不同页面签名)。Aspose.PDF 通过 `Signatures` 集合公开这些签名。 + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*您看到的内容:* 循环打印 **list PDF signatures** 的详细信息,如签名者姓名、原因、位置和时间戳。这对于审计日志或 UI 显示非常有用。 + +## 步骤 3:**Validate PDF Signature** – 检查是否被篡改 + +现在进入安全关键环节:确认签名后没有任何签名被篡改。从 25.3 版本开始,Aspose.PDF 提供了 `PdfSignatureValidator.IsCompromised` 标志。 + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*为什么要使用 `IsCompromised`*:传统验证仅检查加密链(证书有效性、吊销等)。`IsCompromised` 通过检测文档签名后的任何更改,增加了一层保护——这正是您在 **validate PDF signature** 时防止篡改所需的。 + +## 步骤 4:处理验证结果 + +根据结果,您可能需要采取不同的操作。以下是一个可供适配的快速模式: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*边缘情况说明:* 如果 PDF 包含 **certified** 签名(锁定文档的第一个签名),后续的修改会使整个文件失效,即使后面的签名看起来正常。任何来自 `IsCompromised` 为 `true` 的情况都应视为红色警示。 + +## 完整工作示例 + +将所有内容整合在一起,下面是一个可编译运行的完整自包含程序: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**预期输出**(假设有一个正常签名和一个被篡改的签名): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## 常见陷阱及规避方法 + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **缺少 Aspose.PDF 版本** | `IsCompromised` 在 25.3 中引入。旧版本的包可以编译但会抛出 `MissingMethodException`。 | 确保您的 NuGet 引用为 `>= 25.3`。 | +| **空的 `SignatureInfo`** | 某些 PDF 有空的签名槽位,但仍会出现在集合中。 | 在验证前使用 `if (signatureInfo != null)` 进行检查。 | +| **大 PDF 的性能影响** | 验证每个签名时会每次读取整个文件。 | 如果只需要布尔摘要,可缓存 `PdfSignatureValidator` 或批量处理签名。 | +| **未检查证书吊销** | `IsCompromised` 只告知文档是否被更改,不涉及证书状态。 | 结合使用 `PdfSignatureValidator.Validate()` 与 `IsCompromised` 进行完整的 PKI 检查。 | + +## 扩展方案 + +如果需要在 UI 中 **list PDF signatures**,只需将 `SignatureInfo` 对象填充到数据网格中。想将验证结果存入数据库?将布尔值 `isCompromised` 与签名者姓名和时间戳一起序列化。 + +您接下来可以探索的其他相关主题: + +- [如何验证 PDF – 使用 Aspose 验证 PDF 签名](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [如何使用 Aspose.PDF .NET: 提取 PDF 签名信息:一步步指南](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [如何使用 Aspose.PDF for .NET: 从 PDF 签名字段提取图像:一步步指南](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} + +![验证 PDF 签名](/images/validate-pdf-signature.png "使用 Aspose.PDF 验证 PDF 签名的 C# 控制台应用截图") \ No newline at end of file diff --git a/pdf/chinese/net/programming-with-operators/_index.md b/pdf/chinese/net/programming-with-operators/_index.md index 30ebbdeb45..b19b249c80 100644 --- a/pdf/chinese/net/programming-with-operators/_index.md +++ b/pdf/chinese/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Aspose.PDF for .NET 的“使用运算符编程”教程将指导您了解 PDF | [在页面上绘制 XForm](./draw-xform-on-page/) | 通过这份全面的分步指南了解如何使用 Aspose.PDF for .NET 在 PDF 中绘制 XForms。| | [PDF 运算符](./pdf-operators/) 使用 Aspose.PDF for .NET 的 PDF 操作符的分步指南。将图像添加到 PDF 页面并指定其位置。| | [删除 PDF 文件中的图形对象](./remove-graphics-objects/) 在本分步指南中学习如何使用 Aspose.PDF for .NET 从 PDF 文件中删除图形对象。简化您的 PDF 操作任务。| +| [在 C# 中创建空 PDF 字典 – 完整 Aspose.Pdf 指南](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) 本完整指南展示如何使用 Aspose.PDF for .NET 在 C# 中创建空的 PDF 字典。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/chinese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/chinese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..115384e7c4 --- /dev/null +++ b/pdf/chinese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-26 +description: 使用 Aspose.Pdf 在 C# 中创建空的 PDF 字典。一步一步学习如何向 ExtGState 字典添加图形状态,以进行 PDF + 操作。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: zh +lastmod: 2026-07-26 +og_description: 使用 Aspose.Pdf for C# 创建空的 PDF 字典。请按照本实用指南修改 PDF 中的图形状态。 +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: 在 C# 中创建空 PDF 字典 – 完整 Aspose.Pdf 教程 +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: 在 C# 中创建空 PDF 字典 – 完整 Aspose.Pdf 指南 +url: /zh/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建空 PDF 字典 – 完整 Aspose.Pdf 指南 + +是否曾经想过在调整 PDF 的图形状态时 **创建空 PDF 字典** 条目?你并不孤单——许多开发者在尝试以编程方式调整不透明度或混合模式时都会遇到这个问题。在本教程中,我们将通过 Aspose.Pdf for C# 演示一个具体的解决方案,展示如何将新的图形状态注入现有 PDF 的 *ExtGState* 字典。 + +我们将覆盖所有必需的步骤:加载 PDF、访问资源字典、构建全新的 **CosPdfDictionary**,以及最终保存更改。完成后,你将拥有一个可复用的模式,用于任何 *PDF 图形状态* 的微调。 + +--- + +## 你将学到的内容 + +- 如何使用 Aspose.Pdf 的底层 API **创建空 PDF 字典** 对象。 +- **ExtGState 字典** 在控制描边/填充不透明度和混合模式中的作用。 +- C# PDF 操作的实用技巧,包括字典缺失时的边界情况处理。 +- 一个完整、可直接运行的代码示例,复制粘贴即可使用。 + +### 前置条件 + +- .NET 6.0 或更高(代码同样适用于 .NET Framework 4.6+)。 +- 已授权的 **Aspose.Pdf for .NET**(免费试用版可用于测试)。 +- 对 C# 和 PDF 概念(如资源和图形状态)有基本了解。 + +如果上述内容对你来说陌生,请不要慌张——你可以通过 NuGet 安装 Aspose.Pdf (`Install-Package Aspose.Pdf`),其余部分仅是普通的 C# 代码。 + +--- + +## 第一步 – 加载 PDF 文档 + +首先,需要一个表示待编辑文件的 `Document` 对象。将其放在 `using` 块中可以确保正确释放资源。 + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*为什么重要*:打开文件后,你才能访问内部的 COS(Canonical Object Structure)对象,**CosPdfDictionary** 就位于其中。没有 `Document` 对象,就无法触及保存 **ExtGState** 条目的资源字典。 + +--- + +## 第二步 – 访问第一页的资源字典 + +PDF 页面将其资源(字体、图像、图形状态等)存放在专用字典中。这里我们为简化起见只取第一页,其他页同理。 + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*小技巧*:如果你的 PDF 有多页且每页资源不同,请为每个需要修改的页面重复此代码块。`DictionaryEditor` 类是一个便利的包装器,让你可以像操作 .NET `Dictionary` 那样处理 COS 字典。 + +--- + +## 第三步 – 获取或初始化 ExtGState 字典 + +**ExtGState 字典** 保存命名的图形状态对象(`GS0`、`GS1` …)。有些 PDF 已经包含它,有些则没有。我们将安全地获取它,必要时创建一个新的空字典。 + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*这样做的原因*:向不存在的 **ExtGState 字典** 添加图形状态会抛出异常。此防御性检查使代码对任何输入 PDF 都保持稳健。 + +--- + +## 第四步 – 使用 CosPdfDictionary 构建新的图形状态 + +现在进入教程的核心:**创建空 PDF 字典**,定义自定义图形状态。我们将设置描边不透明度(`CA`)、填充不透明度(`ca`)以及混合模式(`BM`)。后续可以自行添加更多条目——这只是一个入门示例。 + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*解释*: +- `CA` 和 `ca` 是标准 PDF 键,分别控制描边和填充的不透明度。 +- `BM` 用于选择混合模式;默认是 “Normal”,你也可以使用 “Multiply”、 “Screen”等,具体取决于设计需求。 +- 通过 `CosPdfDictionary.CreateEmptyDictionary`,我们 **创建空 PDF 字典** 对象,随后再填充键/值对。 + +--- + +## 第五步 – 将新图形状态插入 ExtGState + +图形状态准备好后,只需将其以唯一名称(例如 `GS0`)加入 **ExtGState 字典**。如果需要添加多个状态,只需递增后缀即可。 + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*提示*:添加前最好检查 `GS0` 是否已经存在,以免覆盖。使用 `if (!extGState.ContainsKey("GS0"))` 判断即可。 + +--- + +## 第六步 – 保存修改后的 PDF + +所有更改都只在内存中,直到你将其持久化。请选择一个符合工作流的输出路径。 + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*结果*:在任意 PDF 查看器中打开 `output.pdf`,然后使用 PDF 检查工具查看页面资源。你会看到 **ExtGState** 下新增了名为 `GS0` 的条目,且包含我们定义的参数。 + +--- + +## 完整可运行示例 + +将所有步骤整合在一起,下面是完整的、可直接复制粘贴的程序: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**预期输出**:`output.pdf` 的渲染效果与原文件完全相同,但任何后续引用 `GS0`(例如在内容流中使用 `gs` 操作符)的内容都会采用我们定义的不透明度和混合模式。如果当前还没有此类引用,你可以手动添加,或通过 Aspose 的高级 API 实现。 + +--- + +## 常见问题与边界情况 + +| 问题 | 答案 | +|----------|--------| +| *如果 PDF 已经有名为 `GS0` 的 ExtGState 条目怎么办?* | 在添加前使用 `extGState.ContainsKey("GS0")` 检查。若已存在,可有意覆盖(`extGState["GS0"] = newGraphicsState`)或改用新名称如 `GS1`。 | +| *我可以添加更多参数,例如线宽 (`LW`) 或虚线模式 (`D`) 吗?* | 当然可以。只需在 `parameters` 数组中再加入相应的 `KeyValuePair` 条目。 | +| *此方法能兼容加密的 PDF 吗?* | 可以,只要在构造 `Document` 时提供正确的密码(`new Document(path, password)`)。 | +| *我需要手动关闭文档吗?* | `using` 语句会自动处理释放,同时也会刷新任何未写入的更改。 | +| *这与使用高级的 `Graphics` 类有什么区别?* | 高级 API 会抽象底层字典,适合简单任务。但当你需要对图形状态进行细粒度控制(如自定义混合模式)时,必须直接操作底层 **CosPdfDictionary**,即 **创建空 PDF 字典** 对象。 | + +--- + +## 结论 + +我们已经演示了如何使用 Aspose.Pdf **创建空 PDF 字典**,将自定义图形状态注入 **ExtGState 字典**,并保存修改后的文件——全部采用简洁、符合 C# 习惯的代码。这一模式为你提供了对不透明度、混合模式以及 PDF 规范中其他图形状态参数的精确控制。 + +接下来你可以: + +- 使用 `gs` 操作符将新图形状态应用到已有页面内容。 +- 构建可复用的图形状态库,用于品牌化或水印。 +- + +## 接下来你应该学习什么? + +以下教程与本指南紧密相关,进一步扩展了本篇所示技术。每篇资源都包含完整的可运行代码示例以及逐步解释,帮助你掌握更多 API 功能并在项目中探索替代实现方案。 + +- [使用 Aspose.PDF for .NET 在 PDF 中创建虚线 – 步骤指南](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [使用 Aspose.PDF for .NET 在 PDF 中创建并填充矩形 – 步骤指南](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/czech/net/digital-signatures/_index.md b/pdf/czech/net/digital-signatures/_index.md index 8b518b22ce..3b593acb7b 100644 --- a/pdf/czech/net/digital-signatures/_index.md +++ b/pdf/czech/net/digital-signatures/_index.md @@ -56,12 +56,16 @@ Naučte se, jak ověřovat digitální podpisy v souborech PDF pomocí Aspose.PD ### [Ověření podpisu PDF v C# – Kompletní průvodce validací digitálního podpisu PDF](./verify-pdf-signature-in-c-complete-guide-to-validate-digital/) Naučte se, jak ověřit digitální podpis PDF pomocí C# s Aspose.PDF pro .NET. Kompletní průvodce krok za krokem. + ### [Načtení PDF dokumentu C# – Konverze na PDF/X‑4 a výpis podpisů](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) Naučte se načíst PDF v C#, převést jej na PDF/X‑4 a získat seznam digitálních podpisů. ### [Ověření podpisu PDF pomocí Aspose – převod PDF na HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Naučte se, jak ověřit podpis PDF a převést PDF dokument do HTML pomocí Aspose.PDF pro .NET. +### [Ověření podpisu PDF a výpis podpisů PDF s Aspose.PDF – Kompletní průvodce](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Naučte se, jak ověřit podpis PDF a získat seznam podpisů pomocí Aspose.PDF v .NET. + ## Další zdroje - [Aspose.PDF pro síťovou dokumentaci](https://docs.aspose.com/pdf/net/) diff --git a/pdf/czech/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/czech/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..11d27a0135 --- /dev/null +++ b/pdf/czech/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-26 +description: Ověřte podpis PDF a vypište podpisy PDF pomocí Aspose.PDF v C#. Krok + za krokem kód, úskalí a osvědčené postupy pro bezpečnou manipulaci s dokumenty. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: cs +lastmod: 2026-07-26 +og_description: Ověřte podpis PDF a zobrazte seznam podpisů PDF pomocí Aspose.PDF. + Postupujte podle tohoto praktického průvodce k zabezpečení PDF v C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Ověřit PDF podpis a vypsat PDF podpisy – Aspose.PDF návod +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Ověření PDF podpisu a výpis PDF podpisů s Aspose.PDF – Kompletní průvodce +url: /cs/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ověření PDF podpisu a výpis PDF podpisů pomocí Aspose.PDF – Kompletní průvodce + +Vždy jste se zamýšleli, jak **ověřit PDF podpis** v .NET aplikaci, aniž byste si trhali vlasy? Nejste v tom sami. Ať už budujete platformu pro elektronické podepisování nebo jen potřebujete zajistit, že přijatá smlouva nebyla pozměněna, schopnost **vypisovat PDF podpisy** a ověřovat každý z nich je nezbytná dovednost. + +V tomto tutoriálu projdeme plně spustitelným příkladem, který načte podepsaný PDF, vyjmenuje všechny vložené podpisy, zkontroluje, zda některý z nich nebyl kompromitován, a vypíše jasný výsledek do konzole. Žádné vágní odkazy – jen kód, který můžete zkopírovat a vložit, plus „proč“ za každým krokem. + +## Požadavky + +- **Aspose.PDF for .NET** verze 25.3 nebo novější (vlastnost `IsCompromised` se objevila ve verzi 25.3). +- Vývojové prostředí .NET (Visual Studio 2022, Rider nebo `dotnet` CLI). +- Podepsaný PDF soubor, který můžete použít k testování (můžete jej vytvořit v Adobe Acrobat nebo jakémkoli nástroji pro elektronické podepisování). + +Pokud některý z těchto požadavků chybí, nejprve nainstalujte NuGet balíček: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Tip:** Cílová verze .NET 6 nebo novější pro nejlepší výkon a dlouhodobou podporu. + +## Krok 1: Načtení PDF dokumentu + +Prvním krokem je otevřít PDF soubor. Třída `Document` z Aspose.PDF se stará o vše od parsování po renderování. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Proč je to důležité:* Načtení souboru vytvoří paměťovou reprezentaci, která vám umožní dotazovat se na podpisy, aniž byste znovu přistupovali k souborovému systému. Také brzy ověří strukturu PDF, takže při poškozeném souboru okamžitě získáte výjimku. + +## Krok 2: **List PDF Signatures** – Vyjmenování všech vložených podpisů + +Podepsaný PDF může obsahovat více podpisů (např. vícestránková smlouva, kde každá strana podepisuje jinou stránku). Aspose.PDF je zpřístupňuje prostřednictvím kolekce `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Co vidíte:* Smyčka vypisuje podrobnosti **list PDF signatures**, jako je jméno podepisujícího, důvod, místo a časové razítko. To je užitečné pro auditní logy nebo zobrazení v UI. + +## Krok 3: **Validate PDF Signature** – Kontrola kompromitace + +Nyní přichází bezpečnostně kritická část: potvrzení, že žádný z podpisů nebyl po podepsání změněn. Od verze 25.3 poskytuje Aspose.PDF příznak `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Proč používat `IsCompromised`*: Tradiční validace kontroluje jen kryptografický řetězec (platnost certifikátu, revokaci atd.). `IsCompromised` přidává další vrstvu tím, že detekuje jakékoli změny v dokumentu po podpisu – přesně to, co potřebujete při **validate PDF signature** pro detekci manipulace. + +## Krok 4: Zpracování výsledků validace + +V závislosti na výsledku můžete chtít provést různé akce. Zde je rychlý vzor, který můžete upravit: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Poznámka k okrajovému případu:* Pokud PDF obsahuje **certifikovaný** podpis (první podpis, který zamkne dokument), pozdější úprava může neplatnost celého souboru, i když následné podpisy vypadají v pořádku. Vždy považujte jakýkoli `true` z `IsCompromised` za červenou vlajku. + +## Kompletní funkční příklad + +Po spojení všech částí zde máte jednorázový, samostatný program, který můžete zkompilovat a spustit: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Očekávaný výstup** (při předpokladu jednoho dobrého podpisu a jednoho poškozeného): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Časté úskalí a jak se jim vyhnout + +| Úskalí | Proč se to děje | Řešení | +|---------|----------------|-----| +| **Chybějící verze Aspose.PDF** | `IsCompromised` byla zavedena ve verzi 25.3. Starší balíčky se zkompilují, ale vyvolají `MissingMethodException`. | Ujistěte se, že vaše NuGet reference je `>= 25.3`. | +| **Null `SignatureInfo`** | Některé PDF mají prázdné sloty podpisů, které se stále objevují v kolekci. | Ověřte pomocí `if (signatureInfo != null)` před validací. | +| **Výkonnostní dopad u velkých PDF** | Validace každého podpisu načítá celý soubor pokaždé. | Uložte `PdfSignatureValidator` do cache nebo zpracovávejte podpisy dávkově, pokud potřebujete jen boolean souhrn. | +| **Není kontrolována revokace certifikátu** | `IsCompromised` informuje jen o změnách dokumentu, ne o stavu certifikátu. | Použijte `PdfSignatureValidator.Validate()` kromě `IsCompromised` pro kompletní PKI kontrolu. | + +## Rozšíření řešení + +Pokud potřebujete **list PDF signatures** v UI, jednoduše předáte objekty `SignatureInfo` do datové mřížky. Chcete uložit výsledky validace do databáze? Serializujte boolean `isCompromised` spolu s jménem podepisujícího a časovým razítkem. + +Další související témata, která můžete prozkoumat: + +- **Validate PDF signature against a trusted root CA** (použijte `validator.Validate()`). +- **Extract embedded certificate details** (`validator.Certificate`). +- **Create digital signatures** s Aspose.PDF (`PdfSignatureBuilder`). + +## Závěr + +Nyní máte praktickou, end‑to‑end metodu pro **validate PDF signature** a **list PDF signatures** pomocí Aspose.PDF pro .NET. Kód přesně ukazuje, jak načíst dokument, vyjmenovat každý podpis, zkontrolovat příznak `IsCompromised` a reagovat na výsledek – vše v přehledném, konzolovém formátu. + +Vyzkoušejte to s vlastními podepsanými PDF, experimentujte s více podpisy a integrujte logiku do vašeho většího pipeline pro zpracování dokumentů. Zabezpečené PDF jsou tak silné, jak silná je vámi provedená validace, proto udržujte kontroly přísné a logy podrobné. + +Máte otázky nebo chcete sdílet zajímavý případ použití? Zanechte komentář níže nebo mě kontaktujte na GitHubu. Šťastné kódování! + +![Ověřit PDF podpis](/images/validate-pdf-signature.png "Snímek obrazovky C# konzolové aplikace ověřující PDF podpis pomocí Aspose.PDF") + + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Jak ověřit PDF – Ověřit PDF podpis s Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Jak extrahovat informace o PDF podpisu pomocí Aspose.PDF .NET: Průvodce krok za krokem](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Jak extrahovat obrázky z PDF polí podpisu pomocí Aspose.PDF pro .NET: Průvodce krok za krokem](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/czech/net/programming-with-operators/_index.md b/pdf/czech/net/programming-with-operators/_index.md index 8d98f67cb7..f3fdd1f905 100644 --- a/pdf/czech/net/programming-with-operators/_index.md +++ b/pdf/czech/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Výukové programy „Programování s operátory“ v Aspose.PDF pro .NET vás | [Kreslení XFormu na stránce](./draw-xform-on-page/) | Naučte se, jak kreslit XForms v PDF pomocí Aspose.PDF pro .NET s tímto komplexním podrobným návodem. | | [Operátory PDF](./pdf-operators/) | Podrobný návod k používání operátorů PDF s Aspose.PDF pro .NET. Přidání obrázku na stránku PDF a zadání jeho pozice. | | [Odstranění grafických objektů v souboru PDF](./remove-graphics-objects/) V tomto podrobném návodu se naučte, jak odstranit grafické objekty ze souboru PDF pomocí nástroje Aspose.PDF pro .NET. Zjednodušte si manipulaci s PDF soubory. | +| [Vytvoření prázdného PDF slovníku v C# – Kompletní průvodce Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Naučte se, jak vytvořit prázdný PDF slovník v C# pomocí Aspose.Pdf. Kompletní návod krok za krokem. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/czech/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/czech/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..d91e990734 --- /dev/null +++ b/pdf/czech/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: Vytvořte prázdný PDF slovník pomocí Aspose.Pdf v C#. Naučte se krok za + krokem, jak přidat grafický stav do slovníku ExtGState pro manipulaci s PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: cs +lastmod: 2026-07-26 +og_description: Vytvořte prázdný PDF slovník pomocí Aspose.Pdf pro C#. Postupujte + podle tohoto praktického návodu k úpravě grafických stavů ve vašich PDF. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Vytvořte prázdný PDF slovník v C# – Kompletní tutoriál Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Vytvořte prázdný PDF slovník v C# – kompletní průvodce Aspose.Pdf +url: /cs/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření prázdného PDF slovníku v C# – Kompletní průvodce Aspose.Pdf + +Už jste se někdy zamýšleli, jak **vytvořit prázdné PDF slovníkové** položky při úpravě grafického stavu PDF? Nejste v tom sami – mnoho vývojářů narazí na tento problém, když se snaží programově nastavit neprůhlednost nebo režimy prolnutí. V tomto tutoriálu vás provedeme konkrétním řešením pomocí Aspose.Pdf pro C#, kde ukážeme, jak vložit nový grafický stav do slovníku *ExtGState* existujícího PDF. + +Probereme vše, co potřebujete: načtení PDF, přístup k jeho slovníku zdrojů, vytvoření nového **CosPdfDictionary** a nakonec uložení změn. Na konci budete mít znovupoužitelný vzor pro jakékoli úpravy *PDF grafického stavu*, které budete potřebovat. + +--- + +## Co se naučíte + +- Jak **vytvořit prázdný PDF slovník** pomocí nízkoúrovňového API Aspose.Pdf. +- Jakou roli hraje **ExtGState slovník** při řízení neprůhlednosti tahů/výplní a režimů prolnutí. +- Praktické tipy pro manipulaci s PDF v C#, včetně ošetření okrajových případů, kdy slovník chybí. +- Kompletní, spustitelný ukázkový kód, který můžete zkopírovat a vložit do svého projektu. + +### Předpoklady + +- .NET 6.0 nebo novější (kód funguje také s .NET Framework 4.6+). +- Licencovaná kopie **Aspose.Pdf for .NET** (pro testování stačí zkušební verze). +- Základní znalost C# a PDF konceptů, jako jsou zdroje a grafické stavy. + +Pokud vám některý z těchto bodů není známý, nepanikařte – Aspose.Pdf můžete nainstalovat přes NuGet (`Install-Package Aspose.Pdf`) a zbytek je jen čisté C#. + +--- + +## Krok 1 – Načtení PDF dokumentu + +Nejprve potřebujete objekt `Document`, který představuje soubor, který chcete upravit. Zabalení do bloku `using` zaručuje správné uvolnění prostředků. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Proč je to důležité*: Otevřením souboru získáte přístup k vnitřním COS (Canonical Object Structure) objektům, kde žije **CosPdfDictionary**. Bez objektu dokumentu se k slovníkům zdrojů, které obsahují položky **ExtGState**, nedostanete. + +--- + +## Krok 2 – Přístup ke slovníku zdrojů první stránky + +PDF stránky ukládají své zdroje (písma, obrázky, grafické stavy atd.) do samostatného slovníku. Pro jednoduchost si vezmeme první stránku, ale stejná logika platí pro libovolný index stránky. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Tip*: Pokud má vaše PDF více stránek s různými sadami zdrojů, opakujte tento blok pro každou stránku, kterou potřebujete upravit. Třída `DictionaryEditor` je pohodlný obal, který vám umožní zacházet se slovníkem COS jako s .NET `Dictionary`. + +--- + +## Krok 3 – Načtení nebo inicializace ExtGState slovníku + +**ExtGState slovník** obsahuje pojmenované objekty grafického stavu (`GS0`, `GS1`, …). Některá PDF jej již obsahují; jiná ne. Bezpečně ho načteme a v případě potřeby vytvoříme nový prázdný. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Proč to děláme*: Pokus o přidání grafického stavu do neexistujícího **ExtGState slovníku** by vyvolal výjimku. Tato obranná kontrola dělá kód odolným vůči libovolnému vstupnímu PDF. + +--- + +## Krok 4 – Vytvoření nového grafického stavu pomocí CosPdfDictionary + +Nyní přichází jádro tutoriálu: **vytvoření prázdného PDF slovníku**, který definuje vlastní grafický stav. Nastavíme neprůhlednost tahu (`CA`), neprůhlednost výplně (`ca`) a režim prolnutí (`BM`). Později můžete přidat další položky – toto je jen úvodní sada. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Vysvětlení*: +- `CA` a `ca` jsou standardní PDF klíče řídící neprůhlednost tahu a výplně. +- `BM` vybírá režim prolnutí; „Normal“ je výchozí, ale můžete použít „Multiply“, „Screen“ a další podle potřeb designu. +- Použitím `CosPdfDictionary.CreateEmptyDictionary` **vytváříme prázdné PDF slovníky**, do nichž později vložíme páry klíč/hodnota. + +--- + +## Krok 5 – Vložení nového grafického stavu do ExtGState + +Jakmile je grafický stav připraven, jednoduše jej přidáme do **ExtGState slovníku** pod jedinečným názvem (např. `GS0`). Pokud plánujete přidat více stavů, stačí zvýšit příponu. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tip*: Před přidáním můžete zkontrolovat, zda `GS0` již neexistuje, abyste předešli přepsání. Rychlá podmínka `if (!extGState.ContainsKey("GS0"))` to zařídí. + +--- + +## Krok 6 – Uložení upraveného PDF + +Všechny změny jsou v paměti, dokud je neuložíte. Zvolte výstupní cestu, která dává smysl vašemu workflow. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Výsledek*: Otevřete `output.pdf` v libovolném prohlížeči PDF a prozkoumejte zdroje stránky (např. pomocí nástroje pro inspekci PDF). Uvidíte novou položku pod **ExtGState** s názvem `GS0` a parametry, které jsme definovali. + +--- + +## Kompletní funkční příklad + +Spojením všech částí získáte kompletní program připravený ke zkopírování a vložení: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Očekávaný výstup**: `output.pdf` bude vypadat přesně jako originál, ale jakýkoli obsah, který později odkazuje na `GS0` (např. pomocí operátoru `gs` v obsahovém proudu), použije definovanou neprůhlednost a režim prolnutí. Pokud takový odkaz zatím nemáte, můžete jej přidat ručně nebo pomocí vyšší úrovně API Aspose. + +--- + +## Často kladené otázky a okrajové případy + +| Otázka | Odpověď | +|----------|--------| +| *Co když PDF už má položku `ExtGState` pojmenovanou `GS0`?* | Před přidáním zkontrolujte `extGState.ContainsKey("GS0")`. Pokud existuje, buď ji úmyslně přepište (`extGState["GS0"] = newGraphicsState`) nebo zvolte nový název, např. `GS1`. | +| *Mohu přidat další parametry, jako šířku čáry (`LW`) nebo vzor čárkování (`D`)?* | Rozhodně. Stačí rozšířit pole `parameters` o další položky `KeyValuePair`. | +| *Je tento přístup kompatibilní s šifrovanými PDF?* | Ano, pokud při vytváření `Document` zadáte správné heslo (`new Document(path, password)`). | +| *Musím dokument zavřít ručně?* | `using` blok se postará o uvolnění prostředků, což také provede flush všech neuložených změn. | +| *Jaký je rozdíl oproti použití vysoké úrovně třídy `Graphics`?* | Vysoká úroveň API abstrahuje podkladové slovníky, což je skvělé pro jednoduché úkoly. Když však potřebujete jemnou kontrolu nad grafickými stavy – např. vlastní režimy prolnutí – musíte pracovat s nízkoúrovňovým **CosPdfDictionary**, tedy **vytvořit prázdný PDF slovník** přímo. | + +--- + +## Závěr + +Ukázali jsme, jak **vytvořit prázdný PDF slovník** pomocí Aspose.Pdf, vložit vlastní grafický stav do **ExtGState slovníku** a uložit upravený soubor – vše v čistém, idiomatickém C#. Tento vzor vám poskytne přesnou kontrolu nad neprůhledností, režimy prolnutí a dalšími parametry grafického stavu definovanými specifikací PDF. + +Od sem můžete: + +- Použít nový grafický stav na existující obsah stránky pomocí operátoru `gs`. +- Vytvořit knihovnu znovupoužitelných grafických stavů pro branding nebo vodoznaky. +- + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční kódové příklady s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Jak vytvořit čárkované čáry v PDF pomocí Aspose.PDF pro .NET: krok za krokem](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Vytvořit a vyplnit obdélníky v PDF pomocí Aspose.PDF pro .NET: krok za krokem](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/dutch/net/digital-signatures/_index.md b/pdf/dutch/net/digital-signatures/_index.md index 0f4ee34736..c473d77d9f 100644 --- a/pdf/dutch/net/digital-signatures/_index.md +++ b/pdf/dutch/net/digital-signatures/_index.md @@ -62,6 +62,9 @@ Leer hoe u een PDF-document laadt, converteert naar PDF/X‑4 en de aanwezige ha ### [PDF-handtekening valideren met Aspose – PDF naar HTML converteren](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Leer hoe u een PDF-handtekening valideert en het document naar HTML converteert met Aspose.PDF voor .NET. +### [PDF-handtekening valideren en PDF-handtekeningen weergeven met Aspose.PDF – Complete gids](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Leer hoe u PDF-handtekeningen valideert en een lijst van alle handtekeningen in een PDF weergeeft met Aspose.PDF in .NET. + ## Aanvullende bronnen - [Aspose.PDF voor Netdocumentatie](https://docs.aspose.com/pdf/net/) diff --git a/pdf/dutch/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/dutch/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..7addb36f39 --- /dev/null +++ b/pdf/dutch/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-07-26 +description: Valideer PDF-handtekening en lijst PDF-handtekeningen met Aspose.PDF + in C#. Stapsgewijze code, valkuilen en best practices voor veilige documentafhandeling. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: nl +lastmod: 2026-07-26 +og_description: Valideer een PDF-handtekening en lijst PDF-handtekeningen met Aspose.PDF. + Volg deze praktische gids om PDF's te beveiligen in C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: PDF-handtekening valideren & PDF-handtekeningen weergeven – Aspose.PDF How‑to +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: PDF-handtekening valideren en PDF-handtekeningen weergeven met Aspose.PDF – + Complete gids +url: /nl/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF-handtekening valideren en PDF-handtekeningen weergeven met Aspose.PDF – Complete gids + +Heb je je ooit afgevraagd hoe je **PDF-handtekening kunt valideren** in een .NET‑applicatie zonder je haar uit te trekken? Je bent niet de enige. Of je nu een e‑sign platform bouwt of gewoon wilt controleren of een ontvangen contract niet is gemanipuleerd, het kunnen **lijst PDF-handtekeningen** en elke handtekening verifiëren is een onmisbare vaardigheid. + +In deze tutorial lopen we stap voor stap door een volledig uitvoerbaar voorbeeld dat een ondertekende PDF laadt, elke ingebedde handtekening opsomt, controleert of een van hen is gecompromitteerd, en een duidelijk resultaat naar de console print. Geen vage verwijzingen—alleen de code die je kunt copy‑pasten, plus de “waarom” achter elke stap. + +## Vereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +- **Aspose.PDF for .NET** versie 25.3 of nieuwer (de `IsCompromised`‑eigenschap verscheen in 25.3). +- Een .NET‑ontwikkelomgeving (Visual Studio 2022, Rider, of de `dotnet`‑CLI). +- Een ondertekende PDF‑file om mee te testen (je kunt er één maken met Adobe Acrobat of een e‑handtekening‑tool). + +Als een van deze ontbreekt, installeer dan eerst het NuGet‑pakket: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** Target .NET 6 of later voor de beste prestaties en langdurige ondersteuning. + +## Stap 1: Laad het PDF‑document + +Het allereerste wat je moet doen is het PDF‑bestand openen. Aspose.PDF’s `Document`‑klasse regelt alles van parsing tot rendering. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Waarom dit belangrijk is:* Het laden van het bestand creëert een in‑memory representatie waarmee je handtekeningen kunt opvragen zonder opnieuw het bestandssysteem aan te raken. Het valideert ook vroegtijdig de PDF‑structuur, zodat je meteen een uitzondering krijgt als het bestand corrupt is. + +## Stap 2: **Lijst PDF-handtekeningen** – Enumerateer alle ingebedde handtekeningen + +Een ondertekende PDF kan meerdere handtekeningen bevatten (denk aan een meer‑pagina contract waarbij elke partij een andere pagina ondertekent). Aspose.PDF maakt ze beschikbaar via de `Signatures`‑collectie. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Wat je ziet:* De lus print de **list PDF signatures**‑details zoals de naam van de ondertekenaar, reden, locatie en tijdstempel. Handig voor audit‑logs of UI‑weergaven. + +## Stap 3: **PDF-handtekening valideren** – Controleer op compromittering + +Nu volgt het beveiligingskritieke deel: bevestigen dat geen van de handtekeningen is gewijzigd na ondertekening. Vanaf versie 25.3 biedt Aspose.PDF de `PdfSignatureValidator.IsCompromised`‑vlag. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Waarom je `IsCompromised` moet gebruiken*: Traditionele validatie controleert alleen de cryptografische keten (certificaatgeldigheid, intrekking, enz.). `IsCompromised` voegt een extra laag toe door eventuele wijzigingen na ondertekening van het document te detecteren—precies wat je nodig hebt wanneer je **PDF-handtekening valideert** op manipulatie. + +## Stap 4: Afhandelen van validatieresultaten + +Afhankelijk van het resultaat wil je mogelijk verschillende acties ondernemen. Hier is een snel patroon dat je kunt aanpassen: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Opmerking over randgevallen:* Als een PDF een **gecertificeerde** handtekening bevat (de eerste handtekening die het document vergrendelt), kan een latere wijziging het hele bestand ongeldig maken, zelfs als latere handtekeningen op het eerste gezicht in orde lijken. Beschouw elke `true` van `IsCompromised` altijd als een rode vlag. + +## Volledig werkend voorbeeld + +Alles samengevoegd, hier is een enkel, zelf‑containend programma dat je kunt compileren en uitvoeren: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Verwachte output** (ervan uitgaande dat er één goede handtekening en één gemanipuleerde is): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +| Valkuil | Waarom het gebeurt | Oplossing | +|---------|--------------------|-----------| +| **Ontbrekende Aspose.PDF‑versie** | `IsCompromised` werd geïntroduceerd in 25.3. Oudere pakketten compileren maar geven `MissingMethodException`. | Zorg dat je NuGet‑referentie `>= 25.3` is. | +| **Null `SignatureInfo`** | Sommige PDF’s hebben lege handtekening‑slots die toch in de collectie verschijnen. | Bescherm met `if (signatureInfo != null)` vóór validatie. | +| **Prestatie‑impact bij grote PDF’s** | Elke handtekening valideren leest het hele bestand telkens opnieuw. | Cache de `PdfSignatureValidator` of verwerk handtekeningen in batches als je alleen een boolean‑samenvatting nodig hebt. | +| **Certificaatintrekking niet gecontroleerd** | `IsCompromised` vertelt alleen over documentwijzigingen, niet over certificaatstatus. | Gebruik `PdfSignatureValidator.Validate()` naast `IsCompromised` voor volledige PKI‑controles. | + +## De oplossing uitbreiden + +Als je **list PDF signatures** in een UI wilt weergeven, voed dan simpelweg de `SignatureInfo`‑objecten in een datagrid. Wil je validatieresultaten opslaan in een database? Serialiseer de boolean `isCompromised` samen met de naam van de ondertekenaar en de tijdstempel. + +Andere gerelateerde onderwerpen die je kunt verkennen: + +- **PDF-handtekening valideren tegen een vertrouwde root‑CA** (gebruik `validator.Validate()`). +- **Ingebedde certificaatdetails extraheren** (`validator.Certificate`). +- **Digitale handtekeningen maken** met Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusie + +Je beschikt nu over een praktische, end‑to‑end methode om **PDF-handtekening te valideren** en **PDF-handtekeningen te lijst** met Aspose.PDF voor .NET. De code laat precies zien hoe je een document laadt, elke handtekening opsomt, de `IsCompromised`‑vlag controleert, en actie onderneemt op basis van het resultaat—alles in een duidelijke, console‑vriendelijke opmaak. + +Probeer het met je eigen ondertekende PDF’s, experimenteer met meerdere handtekeningen, en integreer de logica in je grotere documentverwerkings‑pipeline. Beveiligde PDF’s zijn alleen zo sterk als de validatie die je uitvoert, dus houd de controles streng en de logs grondig. + +Vragen of een cool use‑case om te delen? Laat een reactie achter of ping me op GitHub. Veel plezier met coderen! + +![PDF-handtekening valideren](/images/validate-pdf-signature.png "Schermafbeelding van een C# console‑app die een PDF‑handtekening valideert met Aspose.PDF") + + +## Wat moet je hierna leren? + + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat complete werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe PDF te verifiëren – PDF-handtekening valideren met Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Hoe PDF-handtekening‑informatie extraheren met Aspose.PDF .NET: Een stapsgewijze handleiding](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Hoe afbeeldingen uit PDF‑handtekeningvelden extraheren met Aspose.PDF voor .NET: Een stapsgewijze handleiding](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/dutch/net/programming-with-operators/_index.md b/pdf/dutch/net/programming-with-operators/_index.md index a58af1c622..bacc3eb2f5 100644 --- a/pdf/dutch/net/programming-with-operators/_index.md +++ b/pdf/dutch/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ De tutorials "Programmeren met operatoren" van Aspose.PDF voor .NET begeleiden u | [XForm op pagina tekenen](./draw-xform-on-page/) | Leer hoe u XForms in PDF kunt tekenen met Aspose.PDF voor .NET met deze uitgebreide stapsgewijze handleiding. | | [PDF-operatoren](./pdf-operators/) | Stapsgewijze handleiding voor het gebruik van PDF-operatoren met Aspose.PDF voor .NET. Voeg een afbeelding toe aan een PDF-pagina en geef de positie ervan op. | | [Grafische objecten uit een PDF-bestand verwijderen](./remove-graphics-objects/) Leer in deze stapsgewijze handleiding hoe u grafische objecten uit een PDF-bestand verwijdert met Aspose.PDF voor .NET. Vereenvoudig uw PDF-bewerkingstaken. | +| [Leeg PDF-woordenboek maken in C# – Complete Aspose.Pdf-gids](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Leer hoe u een leeg PDF-woordenboek maakt met Aspose.PDF voor .NET in C#. Volledige stapsgewijze handleiding. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/dutch/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/dutch/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..4eb55fe019 --- /dev/null +++ b/pdf/dutch/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: Maak een leeg PDF‑woordenboek met Aspose.Pdf in C#. Leer stap voor stap + hoe je een grafische toestand toevoegt aan het ExtGState‑woordenboek voor PDF‑manipulatie. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: nl +lastmod: 2026-07-26 +og_description: Maak een leeg PDF-woordenboek met Aspose.Pdf voor C#. Volg deze praktische + gids om grafische toestanden in uw PDF's te wijzigen. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Maak een leeg PDF-woordenboek in C# – Volledige Aspose.Pdf‑tutorial +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Leeg PDF‑woordenboek maken in C# – Complete Aspose.Pdf‑gids +url: /nl/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak lege PDF-dictionary in C# – Complete Aspose.Pdf-gids + +Heb je je ooit afgevraagd hoe je **leeg PDF-dictionary**‑items kunt maken bij het aanpassen van de grafische toestand van een PDF? Je bent niet de enige—veel ontwikkelaars lopen tegen dit probleem aan wanneer ze de dekking of mengmodi programmatisch proberen aan te passen. In deze tutorial lopen we een concrete oplossing door met Aspose.Pdf voor C#, waarbij we precies laten zien hoe je een nieuwe grafische toestand in de *ExtGState*-dictionary van een bestaande PDF kunt injecteren. + +We behandelen alles wat je nodig hebt: een PDF laden, de resource‑dictionary benaderen, een nieuwe **CosPdfDictionary** bouwen en uiteindelijk de wijzigingen opslaan. Aan het einde heb je een herbruikbaar patroon voor elke *PDF‑grafische‑toestand*‑aanpassing die je nodig hebt. + +--- + +## Wat je zult leren + +- Hoe je **leeg PDF-dictionary**‑objecten maakt met de low‑level API van Aspose.Pdf. +- De rol van de **ExtGState‑dictionary** bij het regelen van lijn-/vullingsdekking en mengmodi. +- Praktische tips voor C# PDF-manipulatie, inclusief het afhandelen van randgevallen wanneer de dictionary ontbreekt. +- Een compleet, uitvoerbaar code‑voorbeeld dat je kunt kopiëren‑en‑plakken in je project. + +### Vereisten + +- .NET 6.0 of later (de code werkt ook met .NET Framework 4.6+). +- Een gelicentieerde kopie van **Aspose.Pdf for .NET** (de gratis proefversie werkt voor testen). +- Basiskennis van C# en PDF-concepten zoals resources en grafische toestanden. + +Als een van deze je onbekend voorkomt, geen paniek—je kunt Aspose.Pdf installeren via NuGet (`Install-Package Aspose.Pdf`) en de rest is gewoon C#. + +--- + +## Stap 1 – Laad het PDF‑document + +Allereerst heb je een `Document`‑object nodig dat het bestand vertegenwoordigt dat je wilt bewerken. Het omhullen met een `using`‑blok garandeert een correcte vrijgave. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Waarom dit belangrijk is*: Het openen van het bestand geeft je toegang tot de interne COS‑objecten (Canonical Object Structure), waar de **CosPdfDictionary** zich bevindt. Zonder het document‑object kun je de resource‑dictionaries die de **ExtGState**‑items bevatten niet bereiken. + +--- + +## Stap 2 – Benader de resource‑dictionary van de eerste pagina + +PDF‑pagina's slaan hun resources (lettertypen, afbeeldingen, grafische toestanden, enz.) op in een speciale dictionary. We halen de eerste pagina op voor de eenvoud, maar dezelfde logica geldt voor elke paginanaam. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Pro‑tip*: Als je PDF meerdere pagina's heeft met verschillende resource‑sets, herhaal dit blok voor elke pagina die je moet aanpassen. De `DictionaryEditor`‑klasse is een handige wrapper die je de COS‑dictionary laat behandelen als een .NET `Dictionary`. + +--- + +## Stap 3 – Haal de ExtGState‑dictionary op of initialiseert deze + +De **ExtGState‑dictionary** bevat benoemde grafische‑toestand‑objecten (`GS0`, `GS1`, …). Sommige PDF's bevatten deze al; andere niet. We halen hem veilig op en maken een nieuwe lege aan indien nodig. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Waarom we dit doen*: Proberen een grafische toestand toe te voegen aan een niet‑bestaande **ExtGState‑dictionary** zou een uitzondering veroorzaken. Deze defensieve controle maakt de code robuust voor elke invoer‑PDF. + +--- + +## Stap 4 – Bouw een nieuwe grafische toestand met CosPdfDictionary + +Nu volgt het hart van de tutorial: **een lege PDF-dictionary** maken die een aangepaste grafische toestand definieert. We stellen lijn‑dekking (`CA`), vullings‑dekking (`ca`) en mengmodus (`BM`) in. Je kunt later meer items toevoegen—dit is slechts een startset. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Uitleg*: +- `CA` en `ca` zijn standaard PDF‑sleutels die respectievelijk lijn‑ en vullingsdekking regelen. +- `BM` selecteert de mengmodus; “Normal” is de standaard, maar je kunt “Multiply”, “Screen”, enz. gebruiken, afhankelijk van je ontwerpbehoeften. +- Door `CosPdfDictionary.CreateEmptyDictionary` te gebruiken, **maken we leeg PDF-dictionary**‑objecten die we later vullen met sleutel/waarde‑paren. + +--- + +## Stap 5 – Voeg de nieuwe grafische toestand toe aan ExtGState + +Met de grafische toestand klaar, voegen we deze simpelweg toe aan de **ExtGState‑dictionary** onder een unieke naam (bijv. `GS0`). Als je meerdere toestanden wilt toevoegen, verhoog je gewoon de suffix. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tip*: Voordat je toevoegt, wil je misschien controleren of `GS0` al bestaat om overschrijven te voorkomen. Een snelle `if (!extGState.ContainsKey("GS0"))`‑guard lost het op. + +--- + +## Stap 6 – Sla de aangepaste PDF op + +Alle wijzigingen blijven in het geheugen totdat je ze opslaat. Kies een uitvoerpad dat logisch is voor je workflow. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Resultaat*: Open `output.pdf` in een PDF‑viewer en inspecteer vervolgens de pagin resources (bijv. met een PDF‑inspectietool). Je zult een nieuw item onder **ExtGState** zien genaamd `GS0` met de parameters die we hebben gedefinieerd. + +--- + +## Volledig werkend voorbeeld + +Alles samengevoegd, hier is het complete, kant‑klaar‑om‑te‑kopiëren‑en‑plakken programma: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Verwachte output**: De `output.pdf` wordt exact als het origineel weergegeven, maar elke inhoud die later `GS0` aanroept (bijvoorbeeld via de `gs`‑operator in een content‑stream) zal de gedefinieerde dekking en mengmodus overnemen. Als je nog geen dergelijke referentie hebt, kun je er handmatig een toevoegen of via de hoger‑niveau API's van Aspose. + +--- + +## Veelgestelde vragen & randgevallen + +| Vraag | Antwoord | +|-------|----------| +| *Wat als de PDF al een `ExtGState`‑item heeft met de naam `GS0`?* | Controleer `extGState.ContainsKey("GS0")` voordat je toevoegt. Als het bestaat, kun je het bewust overschrijven (`extGState["GS0"] = newGraphicsState`) of een nieuwe naam kiezen zoals `GS1`. | +| *Kan ik meer parameters toevoegen, zoals lijndikte (`LW`) of stippellijnpatroon (`D`)?* | Zeker. Voeg gewoon extra `KeyValuePair`‑items toe aan de `parameters`‑array. | +| *Is deze aanpak compatibel met versleutelde PDF's?* | Ja, zolang je het juiste wachtwoord opgeeft bij het aanmaken van het `Document` (`new Document(path, password)`). | +| *Moet ik het document handmatig sluiten?* | De `using`‑statement zorgt voor de vrijgave, wat ook eventuele wachtende wijzigingen doorvoert. | +| *Hoe verschilt dit van het gebruik van de high‑level `Graphics`‑klasse?* | De high‑level API abstraheert de onderliggende dictionaries, wat handig is voor eenvoudige taken. Wanneer je echter fijnmazige controle over grafische toestanden nodig hebt—zoals aangepaste mengmodi—moet je werken met de low‑level **CosPdfDictionary**, d.w.z. direct **leeg PDF-dictionary**‑objecten maken. | + +--- + +## Conclusie + +We hebben zojuist laten zien hoe je **leeg PDF-dictionary**‑objecten maakt met Aspose.Pdf, een aangepaste grafische toestand injecteert in de **ExtGState‑dictionary**, en het aangepaste bestand opslaat—alles in nette, idiomatische C#. Dit patroon biedt precieze controle over dekking, mengmodi en andere grafische‑toestand‑parameters die in de PDF‑specificatie zijn gedefinieerd. + +Vanaf hier kun je: + +- De nieuwe grafische toestand toepassen op bestaande paginainhoud met de `gs`‑operator. +- Een bibliotheek van herbruikbare grafische toestanden bouwen voor branding of watermerken. +- + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe je gestippelde lijnen maakt in PDF's met Aspose.PDF voor .NET: Een stapsgewijze gids](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Rechthoeken maken & vullen in PDF's met Aspose.PDF voor .NET: Een stapsgewijze gids](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/english/net/digital-signatures/_index.md b/pdf/english/net/digital-signatures/_index.md index 76758a05ac..e7a5df0aa8 100644 --- a/pdf/english/net/digital-signatures/_index.md +++ b/pdf/english/net/digital-signatures/_index.md @@ -59,6 +59,9 @@ Learn how to load a PDF in C#, convert it to PDF/X‑4 format, and list its digi ### [Validate PDF Signature with Aspose – Convert PDF to HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Learn how to validate a PDF signature using Aspose and convert the PDF to HTML in a single workflow. +### [Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete Guide](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Learn how to validate a PDF signature and enumerate all signatures in a PDF using Aspose.PDF for .NET. Step‑by‑step guide with C# code. + ## Additional Resources - [Aspose.PDF for Net Documentation](https://docs.aspose.com/pdf/net/) diff --git a/pdf/english/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/english/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..391b116da8 --- /dev/null +++ b/pdf/english/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-07-26 +description: Validate PDF signature and list PDF signatures using Aspose.PDF in C#. + Step‑by‑step code, pitfalls, and best practices for secure document handling. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: en +lastmod: 2026-07-26 +og_description: Validate PDF signature and list PDF signatures with Aspose.PDF. Follow + this practical guide to secure PDFs in C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Validate PDF Signature & List PDF Signatures – Aspose.PDF How‑to +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete Guide +url: /net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete Guide + +Ever wondered how to **validate PDF signature** in a .NET app without pulling your hair out? You're not the only one. Whether you're building an e‑sign platform or just need to make sure a received contract hasn't been tampered with, being able to **list PDF signatures** and verify each one is a must‑have skill. + +In this tutorial we’ll walk through a fully runnable example that loads a signed PDF, enumerates every embedded signature, checks if any of them have been compromised, and prints a clear result to the console. No vague references—just the code you can copy‑paste, plus the “why” behind each step. + +## Prerequisites + +Before we dive in, make sure you have: + +- **Aspose.PDF for .NET** version 25.3 or newer (the `IsCompromised` property appeared in 25.3). +- A .NET development environment (Visual Studio 2022, Rider, or the `dotnet` CLI). +- A signed PDF file you can test with (you can create one with Adobe Acrobat or any e‑signature tool). + +If any of these are missing, install the NuGet package first: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** Target .NET 6 or later to get the best performance and long‑term support. + +## Step 1: Load the PDF Document + +The very first thing you need to do is open the PDF file. Aspose.PDF’s `Document` class handles everything from parsing to rendering. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Why this matters:* Loading the file creates an in‑memory representation that lets you query signatures without touching the file system again. It also validates the PDF structure early, so you’ll get an exception right away if the file is corrupt. + +## Step 2: **List PDF Signatures** – Enumerate All Embedded Signatures + +A signed PDF can contain multiple signatures (think of a multi‑page contract where each party signs a different page). Aspose.PDF exposes them through the `Signatures` collection. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*What you’re seeing:* The loop prints the **list PDF signatures** details such as the signer’s name, reason, location, and timestamp. This is handy for audit logs or UI displays. + +## Step 3: **Validate PDF Signature** – Check for Compromise + +Now comes the security‑critical part: confirming that none of the signatures have been altered after signing. Starting with version 25.3, Aspose.PDF provides the `PdfSignatureValidator.IsCompromised` flag. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Why you should use `IsCompromised`*: Traditional validation checks only the cryptographic chain (certificate validity, revocation, etc.). `IsCompromised` adds an extra layer by detecting any post‑signing changes to the document—exactly what you need when you **validate PDF signature** for tampering. + +## Step 4: Handling Validation Outcomes + +Depending on the result, you might want to take different actions. Here’s a quick pattern you can adapt: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Edge case note:* If a PDF contains a **certified** signature (the first signature that locks the document), a later modification can invalidate the whole file, even if subsequent signatures appear fine. Always treat any `true` from `IsCompromised` as a red flag. + +## Full Working Example + +Putting everything together, here’s a single, self‑contained program you can compile and run: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Expected output** (assuming one good signature and one tampered one): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Common Pitfalls & How to Avoid Them + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Missing Aspose.PDF version** | `IsCompromised` was introduced in 25.3. Older packages compile but throw `MissingMethodException`. | Ensure your NuGet reference is `>= 25.3`. | +| **Null `SignatureInfo`** | Some PDFs have empty signature slots that still appear in the collection. | Guard with `if (signatureInfo != null)` before validation. | +| **Performance hit on large PDFs** | Validating every signature reads the whole file each time. | Cache the `PdfSignatureValidator` or batch‑process signatures if you only need a boolean summary. | +| **Certificate revocation not checked** | `IsCompromised` only tells you about document changes, not certificate status. | Use `PdfSignatureValidator.Validate()` in addition to `IsCompromised` for full PKI checks. | + +## Extending the Solution + +If you need to **list PDF signatures** in a UI, simply feed the `SignatureInfo` objects into a data grid. Want to store validation results in a database? Serialize the boolean `isCompromised` together with the signer’s name and timestamp. + +Other related topics you might explore next: + +- **Validate PDF signature against a trusted root CA** (use `validator.Validate()`). +- **Extract embedded certificate details** (`validator.Certificate`). +- **Create digital signatures** with Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusion + +You now have a hands‑on, end‑to‑end method to **validate PDF signature** and **list PDF signatures** using Aspose.PDF for .NET. The code shows exactly how to load a document, enumerate each signature, check the `IsCompromised` flag, and act on the result—all in a clear, console‑friendly format. + +Give it a try with your own signed PDFs, experiment with multiple signatures, and integrate the logic into your larger document‑processing pipeline. Secure PDFs are only as strong as the validation you perform, so keep the checks tight and the logs thorough. + +Got questions or want to share a cool use case? Drop a comment below or ping me on GitHub. Happy coding! + +![Validate PDF Signature](/images/validate-pdf-signature.png "Screenshot of a C# console app validating a PDF signature with Aspose.PDF") + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Verify PDF – Validate PDF Signature with Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [How to Extract PDF Signature Information Using Aspose.PDF .NET: A Step-by-Step Guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [How to Extract Images from PDF Signature Fields using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/english/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/og-image.png b/pdf/english/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/og-image.png new file mode 100644 index 0000000000..6a97e6aba1 Binary files /dev/null and b/pdf/english/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/og-image.png differ diff --git a/pdf/english/net/programming-with-operators/_index.md b/pdf/english/net/programming-with-operators/_index.md index 96ad036346..3854db7972 100644 --- a/pdf/english/net/programming-with-operators/_index.md +++ b/pdf/english/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Aspose.PDF for .NET's "Programming with Operators" tutorials guide you through t | [Draw XForm On Page](./draw-xform-on-page/) | earn how to draw XForms in PDF using Aspose.PDF for .NET with this comprehensive step-by-step guide. | | [PDF Operators](./pdf-operators/) | Step-by-step guide to using PDF operators with Aspose.PDF for .NET. Add an image to a PDF page and specify its position. | | [Remove Graphics Objects In PDF File](./remove-graphics-objects/) | Learn how to remove graphics objects from a PDF file using Aspose.PDF for .NET in this step-by-step guide. Simplify your PDF manipulation tasks. | +| [Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Step-by-step guide to creating an empty PDF dictionary in C# using Aspose.PDF for .NET. | {{< /blocks/products/pf/tutorial-page-section >}} @@ -30,4 +31,4 @@ Aspose.PDF for .NET's "Programming with Operators" tutorials guide you through t {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/english/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/english/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..f9b5865f43 --- /dev/null +++ b/pdf/english/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: en +lastmod: 2026-07-26 +og_description: Create empty PDF dictionary using Aspose.Pdf for C#. Follow this hands‑on + guide to modify graphics states in your PDFs. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Create Empty PDF Dictionary in C# – Full Aspose.Pdf Tutorial +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide +url: /net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + +Ever wondered how to **create empty PDF dictionary** entries when tweaking a PDF’s graphics state? You’re not alone—many developers hit this snag while trying to adjust opacity or blend modes programmatically. In this tutorial we’ll walk through a concrete solution using Aspose.Pdf for C#, showing exactly how to inject a new graphics state into the *ExtGState* dictionary of an existing PDF. + +We’ll cover everything you need: loading a PDF, accessing its resource dictionary, building a fresh **CosPdfDictionary**, and finally persisting the changes. By the end you’ll have a reusable pattern for any *PDF graphics state* tweaks you might need. + +--- + +## What You’ll Learn + +- How to **create empty PDF dictionary** objects with Aspose.Pdf’s low‑level API. +- The role of the **ExtGState dictionary** in controlling stroke/fill opacity and blend modes. +- Practical tips for C# PDF manipulation, including edge‑case handling when the dictionary is missing. +- A complete, runnable code sample you can copy‑paste into your project. + +### Prerequisites + +- .NET 6.0 or later (the code works with .NET Framework 4.6+ as well). +- A licensed copy of **Aspose.Pdf for .NET** (the free trial works for testing). +- Basic familiarity with C# and PDF concepts such as resources and graphics states. + +If any of those sound unfamiliar, don’t panic—you can install Aspose.Pdf via NuGet (`Install-Package Aspose.Pdf`) and the rest is just plain C#. + +--- + +## Step 1 – Load the PDF Document + +First things first, you need a `Document` object that represents the file you want to edit. Wrapping it in a `using` block guarantees proper disposal. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Why this matters*: Opening the file gives you access to the internal COS (Canonical Object Structure) objects, which is where the **CosPdfDictionary** lives. Without the document object, you can’t reach the resource dictionaries that hold the **ExtGState** entries. + +--- + +## Step 2 – Access the First Page’s Resource Dictionary + +PDF pages store their resources (fonts, images, graphics states, etc.) in a dedicated dictionary. We’ll pull the first page for simplicity, but the same logic applies to any page index. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Pro tip*: If your PDF has multiple pages with different resource sets, repeat this block for each page you need to modify. The `DictionaryEditor` class is a convenient wrapper that lets you treat the COS dictionary like a .NET `Dictionary`. + +--- + +## Step 3 – Retrieve or Initialise the ExtGState Dictionary + +The **ExtGState dictionary** holds named graphics state objects (`GS0`, `GS1`, …). Some PDFs already contain it; others don’t. We’ll safely fetch it, creating a new empty one if necessary. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Why we do this*: Attempting to add a graphics state to a non‑existent **ExtGState dictionary** would throw an exception. This defensive check makes the code robust for any input PDF. + +--- + +## Step 4 – Build a New Graphics State with CosPdfDictionary + +Now comes the heart of the tutorial: **creating an empty PDF dictionary** that defines a custom graphics state. We’ll set stroke opacity (`CA`), fill opacity (`ca`), and blend mode (`BM`). You can add more entries later—this is just a starter set. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Explanation*: +- `CA` and `ca` are standard PDF keys controlling stroke and fill opacity, respectively. +- `BM` selects the blend mode; “Normal” is the default but you could use “Multiply”, “Screen”, etc., depending on your design needs. +- By using `CosPdfDictionary.CreateEmptyDictionary`, we **create empty PDF dictionary** objects that we later fill with key/value pairs. + +--- + +## Step 5 – Insert the New Graphics State into ExtGState + +With the graphics state ready, we simply add it to the **ExtGState dictionary** under a unique name (e.g., `GS0`). If you plan to add multiple states, just increment the suffix. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tip*: Before adding, you might want to check whether `GS0` already exists to avoid overwriting. A quick `if (!extGState.ContainsKey("GS0"))` guard does the trick. + +--- + +## Step 6 – Save the Modified PDF + +All changes are in memory until you persist them. Choose an output path that makes sense for your workflow. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Result*: Open `output.pdf` in any PDF viewer, then inspect the page resources (e.g., with a PDF inspector tool). You’ll see a new entry under **ExtGState** called `GS0` with the parameters we defined. + +--- + +## Full Working Example + +Putting everything together, here’s the complete, copy‑and‑paste‑ready program: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Expected output**: The `output.pdf` will render exactly like the original, but any content that later references `GS0` (for example via the `gs` operator in a content stream) will adopt the defined opacity and blend mode. If you don’t yet have such a reference, you can add one manually or through Aspose’s higher‑level APIs. + +--- + +## Frequently Asked Questions & Edge Cases + +| Question | Answer | +|----------|--------| +| *What if the PDF already has an `ExtGState` entry named `GS0`?* | Check `extGState.ContainsKey("GS0")` before adding. If it exists, either overwrite deliberately (`extGState["GS0"] = newGraphicsState`) or choose a new name like `GS1`. | +| *Can I add more parameters, like line width (`LW`) or dash pattern (`D`)?* | Absolutely. Just extend the `parameters` array with additional `KeyValuePair` entries. | +| *Is this approach compatible with encrypted PDFs?* | Yes, as long as you provide the correct password when constructing the `Document` (`new Document(path, password)`). | +| *Do I need to close the document manually?* | The `using` statement takes care of disposal, which also flushes any pending changes. | +| *How does this differ from using the high‑level `Graphics` class?* | The high‑level API abstracts away the underlying dictionaries, which is great for simple tasks. However, when you need fine‑grained control over graphics states—like custom blend modes—you must work with the low‑level **CosPdfDictionary**, i.e., **create empty PDF dictionary** objects directly. | + +--- + +## Conclusion + +We’ve just demonstrated how to **create empty PDF dictionary** objects with Aspose.Pdf, inject a custom graphics state into the **ExtGState dictionary**, and save the modified file—all in clean, idiomatic C#. This pattern unlocks precise control over opacity, blend modes, and any other graphics‑state parameters defined by the PDF spec. + +From here you might: + +- Apply the new graphics state to existing page content using the `gs` operator. +- Build a library of reusable graphics states for branding or watermarking. +- + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/english/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/og-image.png b/pdf/english/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/og-image.png new file mode 100644 index 0000000000..eb631d5e71 Binary files /dev/null and b/pdf/english/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/og-image.png differ diff --git a/pdf/french/net/digital-signatures/_index.md b/pdf/french/net/digital-signatures/_index.md index 8e465d0557..dea10d13ee 100644 --- a/pdf/french/net/digital-signatures/_index.md +++ b/pdf/french/net/digital-signatures/_index.md @@ -59,6 +59,9 @@ Apprenez à charger un PDF, le convertir au format PDF/X‑4 et à répertorier ### [Valider la signature PDF avec Aspose – Convertir le PDF en HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Découvrez comment valider une signature PDF et convertir le document en HTML avec Aspose.PDF pour .NET. +### [Valider la signature PDF et lister les signatures PDF avec Aspose.PDF – Guide complet](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Apprenez à valider une signature PDF et à répertorier toutes les signatures présentes à l'aide d'Aspose.PDF pour .NET. + ## Ressources supplémentaires - [Aspose.PDF pour la documentation réseau](https://docs.aspose.com/pdf/net/) diff --git a/pdf/french/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/french/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..ea86fa1451 --- /dev/null +++ b/pdf/french/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Valider la signature PDF et lister les signatures PDF à l'aide d'Aspose.PDF + en C#. Code étape par étape, pièges et meilleures pratiques pour une gestion sécurisée + des documents. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: fr +lastmod: 2026-07-26 +og_description: Validez la signature PDF et répertoriez les signatures PDF avec Aspose.PDF. + Suivez ce guide pratique pour sécuriser les PDF en C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Valider la signature PDF et lister les signatures PDF – Guide Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Valider la signature PDF et lister les signatures PDF avec Aspose.PDF – Guide + complet +url: /fr/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Valider la signature PDF et lister les signatures PDF avec Aspose.PDF – Guide complet + +Vous vous êtes déjà demandé comment **valider la signature PDF** dans une application .NET sans vous arracher les cheveux ? Vous n'êtes pas le seul. Que vous construisiez une plateforme de signature électronique ou que vous ayez simplement besoin de vous assurer qu'un contrat reçu n'a pas été altéré, pouvoir **lister les signatures PDF** et vérifier chacune d'elles est une compétence indispensable. + +Dans ce tutoriel, nous parcourrons un exemple entièrement exécutable qui charge un PDF signé, énumère chaque signature intégrée, vérifie si l'une d'elles a été compromise, et affiche un résultat clair dans la console. Pas de références vagues — juste le code que vous pouvez copier‑coller, ainsi que le « pourquoi » de chaque étape. + +## Prérequis + +- **Aspose.PDF for .NET** version 25.3 ou plus récente (la propriété `IsCompromised` est apparue dans la version 25.3). +- Un environnement de développement .NET (Visual Studio 2022, Rider ou le CLI `dotnet`). +- Un fichier PDF signé que vous pouvez tester (vous pouvez en créer un avec Adobe Acrobat ou tout outil de signature électronique). + +Si l'un de ces éléments manque, installez d'abord le package NuGet : + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Astuce :** Ciblez .NET 6 ou une version ultérieure pour obtenir les meilleures performances et un support à long terme. + +## Étape 1 : Charger le document PDF + +La toute première chose à faire est d'ouvrir le fichier PDF. La classe `Document` d’Aspose.PDF gère tout, du parsing au rendu. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Pourquoi c’est important :* Charger le fichier crée une représentation en mémoire qui vous permet d’interroger les signatures sans toucher de nouveau au système de fichiers. Cela valide également la structure du PDF dès le départ, de sorte que vous obtenez immédiatement une exception si le fichier est corrompu. + +## Étape 2 : **Lister les signatures PDF** – Énumérer toutes les signatures intégrées + +Un PDF signé peut contenir plusieurs signatures (pensez à un contrat multi‑pages où chaque partie signe une page différente). Aspose.PDF les expose via la collection `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Ce que vous voyez :* La boucle affiche les détails des **signatures PDF listées**, tels que le nom du signataire, le motif, le lieu et l'horodatage. C’est pratique pour les journaux d’audit ou les affichages UI. + +## Étape 3 : **Valider la signature PDF** – Vérifier la compromission + +Voici la partie critique en matière de sécurité : confirmer qu'aucune des signatures n’a été modifiée après la signature. À partir de la version 25.3, Aspose.PDF fournit le drapeau `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Pourquoi vous devriez utiliser `IsCompromised`* : la validation traditionnelle ne vérifie que la chaîne cryptographique (validité du certificat, révocation, etc.). `IsCompromised` ajoute une couche supplémentaire en détectant toute modification post‑signature du document—exactement ce dont vous avez besoin lorsque vous **validez la signature PDF** pour détecter une falsification. + +## Étape 4 : Gestion des résultats de validation + +Selon le résultat, vous voudrez peut‑être prendre différentes actions. Voici un modèle rapide que vous pouvez adapter : + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Note de cas limite :* Si un PDF contient une signature **certifiée** (la première signature qui verrouille le document), une modification ultérieure peut invalider l’ensemble du fichier, même si les signatures suivantes semblent correctes. Traitez toujours tout `true` provenant de `IsCompromised` comme un signal d’alarme. + +## Exemple complet fonctionnel + +En assemblant le tout, voici un programme unique et autonome que vous pouvez compiler et exécuter : + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Sortie attendue** (en supposant une signature correcte et une autre altérée) : + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Pièges courants & comment les éviter + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Version Aspose.PDF manquante** | `IsCompromised` a été introduit dans la version 25.3. Les packages plus anciens compilent mais lèvent `MissingMethodException`. | Assurez‑vous que votre référence NuGet est `>= 25.3`. | +| **Null `SignatureInfo`** | Certains PDFs contiennent des emplacements de signature vides qui apparaissent toujours dans la collection. | Protégez avec `if (signatureInfo != null)` avant la validation. | +| **Impact de performance sur les gros PDFs** | Valider chaque signature lit le fichier complet à chaque fois. | Mettez en cache le `PdfSignatureValidator` ou traitez les signatures par lots si vous avez seulement besoin d’un résumé booléen. | +| **Révocation du certificat non vérifiée** | `IsCompromised` indique uniquement les modifications du document, pas l’état du certificat. | Utilisez `PdfSignatureValidator.Validate()` en plus de `IsCompromised` pour des vérifications PKI complètes. | + +## Étendre la solution + +Si vous devez **lister les signatures PDF** dans une interface, alimentez simplement les objets `SignatureInfo` dans une grille de données. Vous voulez stocker les résultats de validation dans une base de données ? Sérialisez le booléen `isCompromised` avec le nom du signataire et l’horodatage. + +Autres sujets connexes que vous pourriez explorer ensuite : + +- **Valider la signature PDF contre une autorité racine de confiance** (utilisez `validator.Validate()`). +- **Extraire les détails du certificat intégré** (`validator.Certificate`). +- **Créer des signatures numériques** avec Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusion + +Vous disposez maintenant d’une méthode pratique, de bout en bout, pour **valider la signature PDF** et **lister les signatures PDF** en utilisant Aspose.PDF pour .NET. Le code montre exactement comment charger un document, énumérer chaque signature, vérifier le drapeau `IsCompromised` et agir en fonction du résultat—le tout dans un format clair et adapté à la console. + +Essayez-le avec vos propres PDFs signés, expérimentez avec plusieurs signatures, et intégrez la logique dans votre pipeline de traitement de documents plus vaste. Les PDFs sécurisés ne sont aussi forts que la validation que vous effectuez, alors maintenez les contrôles stricts et les journaux complets. + +Des questions ou envie de partager un cas d’utilisation intéressant ? Laissez un commentaire ci‑dessous ou contactez‑moi sur GitHub. Bon codage ! + +![Valider la signature PDF](/images/validate-pdf-signature.png "Capture d’écran d’une application console C# validant une signature PDF avec Aspose.PDF") + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités supplémentaires de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Comment vérifier un PDF – Valider la signature PDF avec Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Comment extraire les informations de signature PDF avec Aspose.PDF .NET : Guide étape par étape](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Comment extraire les images des champs de signature PDF avec Aspose.PDF pour .NET : Guide étape par étape](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/french/net/programming-with-operators/_index.md b/pdf/french/net/programming-with-operators/_index.md index 3b71167812..959031939c 100644 --- a/pdf/french/net/programming-with-operators/_index.md +++ b/pdf/french/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ Les tutoriels « Programmation avec opérateurs » d'Aspose.PDF pour .NET vous | --- | --- | | [Dessiner XForm sur la page](./draw-xform-on-page/) | Apprenez à dessiner des XForms au format PDF à l'aide d'Aspose.PDF pour .NET avec ce guide complet étape par étape. | | [Opérateurs PDF](./pdf-operators/) | Guide étape par étape pour utiliser les opérateurs PDF avec Aspose.PDF pour .NET. Ajoutez une image à une page PDF et spécifiez sa position. | -| [Supprimer les objets graphiques dans un fichier PDF](./remove-graphics-objects/) Découvrez comment supprimer des objets graphiques d'un fichier PDF avec Aspose.PDF pour .NET dans ce guide étape par étape. Simplifiez vos manipulations PDF. | +| [Supprimer les objets graphiques dans un fichier PDF](./remove-graphics-objects/) | Découvrez comment supprimer des objets graphiques d'un fichier PDF avec Aspose.PDF pour .NET dans ce guide étape par étape. Simplifiez vos manipulations PDF. | +| [Créer un dictionnaire PDF vide en C# – Guide complet Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Apprenez à créer un dictionnaire PDF vide en C# avec Aspose.PDF pour .NET grâce à ce guide complet. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/french/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/french/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..144f8462a7 --- /dev/null +++ b/pdf/french/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-26 +description: Créer un dictionnaire PDF vide avec Aspose.Pdf en C#. Apprenez étape + par étape comment ajouter un état graphique au dictionnaire ExtGState pour la manipulation + de PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: fr +lastmod: 2026-07-26 +og_description: Créez un dictionnaire PDF vide avec Aspose.Pdf pour C#. Suivez ce + guide pratique pour modifier les états graphiques de vos PDF. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Créer un dictionnaire PDF vide en C# – Tutoriel complet Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Créer un dictionnaire PDF vide en C# – Guide complet d'Aspose.Pdf +url: /fr/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un dictionnaire PDF vide en C# – Guide complet Aspose.Pdf + +Vous êtes-vous déjà demandé comment **créer des entrées de dictionnaire PDF vides** lorsqu’on ajuste l’état graphique d’un PDF ? Vous n’êtes pas seul — de nombreux développeurs rencontrent ce problème en essayant de modifier l’opacité ou les modes de fusion de façon programmatique. Dans ce tutoriel, nous allons parcourir une solution concrète avec Aspose.Pdf pour C#, en montrant exactement comment injecter un nouvel état graphique dans le dictionnaire *ExtGState* d’un PDF existant. + +Nous couvrirons tout ce dont vous avez besoin : charger un PDF, accéder à son dictionnaire de ressources, construire un nouveau **CosPdfDictionary**, puis persister les modifications. À la fin, vous disposerez d’un modèle réutilisable pour tout ajustement d’*état graphique PDF* dont vous pourriez avoir besoin. + +--- + +## Ce que vous allez apprendre + +- Comment **créer des objets dictionnaire PDF vides** avec l’API bas‑niveau d’Aspose.Pdf. +- Le rôle du **dictionnaire ExtGState** dans le contrôle de l’opacité du trait/remplissage et des modes de fusion. +- Astuces pratiques pour la manipulation de PDF en C#, y compris la gestion des cas limites lorsque le dictionnaire est absent. +- Un exemple de code complet, exécutable, que vous pouvez copier‑coller dans votre projet. + +### Prérequis + +- .NET 6.0 ou ultérieur (le code fonctionne également avec .NET Framework 4.6+). +- Une copie sous licence de **Aspose.Pdf for .NET** (l’essai gratuit suffit pour les tests). +- Une connaissance de base du C# et des concepts PDF tels que les ressources et les états graphiques. + +Si l’un de ces points vous semble inconnu, ne paniquez pas — vous pouvez installer Aspose.Pdf via NuGet (`Install-Package Aspose.Pdf`) et le reste n’est que du C# pur. + +--- + +## Étape 1 – Charger le document PDF + +Tout d’abord, vous avez besoin d’un objet `Document` qui représente le fichier que vous souhaitez modifier. Le placer dans un bloc `using` garantit une libération correcte des ressources. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Pourquoi c’est important* : L’ouverture du fichier vous donne accès aux objets COS (Canonical Object Structure) internes, où réside le **CosPdfDictionary**. Sans l’objet document, vous ne pouvez pas atteindre les dictionnaires de ressources contenant les entrées **ExtGState**. + +--- + +## Étape 2 – Accéder au dictionnaire de ressources de la première page + +Les pages PDF stockent leurs ressources (polices, images, états graphiques, etc.) dans un dictionnaire dédié. Nous prendrons la première page pour simplifier, mais la même logique s’applique à n’importe quel indice de page. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Astuce pro* : Si votre PDF possède plusieurs pages avec des ensembles de ressources différents, répétez ce bloc pour chaque page que vous devez modifier. La classe `DictionaryEditor` est un wrapper pratique qui vous permet de traiter le dictionnaire COS comme un `Dictionary` .NET. + +--- + +## Étape 3 – Récupérer ou initialiser le dictionnaire ExtGState + +Le **dictionnaire ExtGState** contient les objets d’état graphique nommés (`GS0`, `GS1`, …). Certains PDF le contiennent déjà ; d’autres non. Nous le récupérerons en toute sécurité, en créant un nouveau dictionnaire vide si nécessaire. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Pourquoi nous faisons cela* : Tenter d’ajouter un état graphique à un **dictionnaire ExtGState** inexistant déclencherait une exception. Cette vérification défensive rend le code robuste pour n’importe quel PDF d’entrée. + +--- + +## Étape 4 – Construire un nouvel état graphique avec CosPdfDictionary + +Voici le cœur du tutoriel : **créer un dictionnaire PDF vide** qui définit un état graphique personnalisé. Nous définirons l’opacité du trait (`CA`), l’opacité du remplissage (`ca`) et le mode de fusion (`BM`). Vous pourrez ajouter d’autres entrées plus tard — c’est juste un jeu de départ. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Explication* : +- `CA` et `ca` sont des clés PDF standard contrôlant respectivement l’opacité du trait et du remplissage. +- `BM` sélectionne le mode de fusion ; “Normal” est la valeur par défaut mais vous pouvez utiliser “Multiply”, “Screen”, etc., selon vos besoins de conception. +- En utilisant `CosPdfDictionary.CreateEmptyDictionary`, nous **créons des objets dictionnaire PDF vides** que nous remplissons ensuite avec des paires clé/valeur. + +--- + +## Étape 5 – Insérer le nouvel état graphique dans ExtGState + +Une fois l’état graphique prêt, il suffit de l’ajouter au **dictionnaire ExtGState** sous un nom unique (par ex., `GS0`). Si vous prévoyez d’ajouter plusieurs états, incrémentez simplement le suffixe. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Conseil* : Avant d’ajouter, vous pouvez vérifier si `GS0` existe déjà afin d’éviter d’écraser. Une simple garde `if (!extGState.ContainsKey("GS0"))` fait l’affaire. + +--- + +## Étape 6 – Enregistrer le PDF modifié + +Toutes les modifications restent en mémoire jusqu’à ce que vous les persistiez. Choisissez un chemin de sortie qui a du sens dans votre flux de travail. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Résultat* : Ouvrez `output.pdf` avec n’importe quel lecteur PDF, puis inspectez les ressources de la page (par ex., avec un outil d’inspection PDF). Vous verrez une nouvelle entrée sous **ExtGState** nommée `GS0` avec les paramètres que nous avons définis. + +--- + +## Exemple complet fonctionnel + +En rassemblant le tout, voici le programme complet, prêt à être copié‑collé : + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Sortie attendue** : Le `output.pdf` s’affichera exactement comme l’original, mais tout contenu qui référencera ultérieurement `GS0` (par exemple via l’opérateur `gs` dans un flux de contenu) adoptera l’opacité et le mode de fusion définis. Si vous n’avez pas encore une telle référence, vous pouvez en ajouter une manuellement ou via les API de haut niveau d’Aspose. + +--- + +## Questions fréquentes & cas particuliers + +| Question | Réponse | +|----------|---------| +| *Que faire si le PDF possède déjà une entrée `ExtGState` nommée `GS0` ?* | Vérifiez `extGState.ContainsKey("GS0")` avant d’ajouter. Si elle existe, soit l’écraser délibérément (`extGState["GS0"] = newGraphicsState`), soit choisir un nouveau nom comme `GS1`. | +| *Puis‑je ajouter d’autres paramètres, comme la largeur de ligne (`LW`) ou le motif de tirets (`D`)?* | Absolument. Il suffit d’étendre le tableau `parameters` avec des paires `KeyValuePair` supplémentaires. | +| *Cette approche fonctionne‑t‑elle avec les PDF chiffrés ?* | Oui, tant que vous fournissez le mot de passe correct lors de la construction du `Document` (`new Document(path, password)`). | +| *Dois‑je fermer le document manuellement ?* | L’instruction `using` se charge de la libération, ce qui vide également les changements en attente. | +| *En quoi cela diffère‑t‑il de l’utilisation de la classe haut‑niveau `Graphics` ?* | L’API haut‑niveau masque les dictionnaires sous‑jacents, ce qui est pratique pour les tâches simples. Cependant, lorsque vous avez besoin d’un contrôle fin sur les états graphiques—comme des modes de fusion personnalisés—vous devez travailler avec le **CosPdfDictionary** bas‑niveau, c’est‑à‑dire **créer des objets dictionnaire PDF vides** directement. | + +--- + +## Conclusion + +Nous venons de démontrer comment **créer des objets dictionnaire PDF vides** avec Aspose.Pdf, injecter un état graphique personnalisé dans le **dictionnaire ExtGState**, puis enregistrer le fichier modifié—le tout en C# propre et idiomatique. Ce modèle offre un contrôle précis sur l’opacité, les modes de fusion et tout autre paramètre d’état graphique défini par la spécification PDF. + +À partir d’ici, vous pouvez : + +- Appliquer le nouvel état graphique au contenu de page existant à l’aide de l’opérateur `gs`. +- Construire une bibliothèque d’états graphiques réutilisables pour le branding ou le filigrane. +- + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques présentées dans ce guide. Chaque ressource comprend des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et explorer des approches alternatives dans vos propres projets. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/german/net/digital-signatures/_index.md b/pdf/german/net/digital-signatures/_index.md index 951813a4f2..b6918c1ba5 100644 --- a/pdf/german/net/digital-signatures/_index.md +++ b/pdf/german/net/digital-signatures/_index.md @@ -58,12 +58,16 @@ Erfahren Sie, wie Sie mit Aspose.PDF für .NET PDF-Signaturen in C# überprüfen ### [So überprüfen Sie PDF – PDF-Signatur mit Aspose validieren](./how-to-verify-pdf-validate-pdf-signature-with-aspose/) Erfahren Sie, wie Sie mit Aspose PDF die Signatur einer PDF-Datei prüfen und validieren. + ### [PDF-Dokument laden in C# – Konvertieren zu PDF/X‑4 und Signaturen auflisten](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) Laden Sie ein PDF in C#, konvertieren Sie es zu PDF/X‑4 und listen Sie vorhandene Signaturen auf. ### [PDF-Signatur validieren mit Aspose – PDF in HTML konvertieren](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Erfahren Sie, wie Sie PDF‑Signaturen mit Aspose validieren und das PDF anschließend in HTML konvertieren. +### [PDF-Signatur validieren und PDF-Signaturen auflisten mit Aspose.PDF – Komplettanleitung](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Erfahren Sie, wie Sie mit Aspose.PDF für .NET PDF‑Signaturen prüfen und alle vorhandenen Signaturen im Dokument auflisten. + ## Weitere Ressourcen - [Aspose.PDF für Net-Dokumentation](https://docs.aspose.com/pdf/net/) diff --git a/pdf/german/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/german/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..d2449c46b3 --- /dev/null +++ b/pdf/german/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: PDF-Signatur validieren und PDF‑Signaturen mit Aspose.PDF in C# auflisten. + Schritt‑für‑Schritt‑Code, Fallstricke und bewährte Methoden für die sichere Dokumentenverarbeitung. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: de +lastmod: 2026-07-26 +og_description: Validieren Sie die PDF‑Signatur und listen Sie PDF‑Signaturen mit + Aspose.PDF auf. Folgen Sie diesem praktischen Leitfaden, um PDFs in C# zu sichern. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: PDF-Signatur validieren & PDF‑Signaturen auflisten – Aspose.PDF Anleitung +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: PDF-Signatur validieren und PDF‑Signaturen auflisten mit Aspose.PDF – Komplettanleitung +url: /de/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF‑Signatur validieren und PDF‑Signaturen mit Aspose.PDF auflisten – Komplettanleitung + +Haben Sie sich jemals gefragt, wie man **PDF‑Signatur validiert** in einer .NET‑App, ohne sich die Haare zu raufen? Sie sind nicht allein. Egal, ob Sie eine E‑Sign‑Plattform bauen oder einfach sicherstellen müssen, dass ein empfangener Vertrag nicht manipuliert wurde, die Fähigkeit, **PDF‑Signaturen auflisten** und jede zu überprüfen, ist eine unverzichtbare Fähigkeit. + +In diesem Tutorial führen wir Sie durch ein vollständig ausführbares Beispiel, das ein signiertes PDF lädt, jede eingebettete Signatur aufzählt, prüft, ob eine davon kompromittiert wurde, und ein klares Ergebnis in der Konsole ausgibt. Keine vagen Verweise – nur der Code, den Sie kopieren‑und‑einfügen können, plus das „Warum“ hinter jedem Schritt. + +## Voraussetzungen + +- **Aspose.PDF for .NET** Version 25.3 oder neuer (die `IsCompromised`‑Eigenschaft erschien in 25.3). +- Eine .NET‑Entwicklungsumgebung (Visual Studio 2022, Rider oder die `dotnet`‑CLI). +- Eine signierte PDF‑Datei, mit der Sie testen können (Sie können eine mit Adobe Acrobat oder einem beliebigen E‑Signature‑Tool erstellen). + +Wenn einer dieser Punkte fehlt, installieren Sie zuerst das NuGet‑Paket: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro‑Tipp:** Ziel .NET 6 oder höher, um die beste Leistung und langfristige Unterstützung zu erhalten. + +## Schritt 1: PDF‑Dokument laden + +Das allererste, was Sie tun müssen, ist die PDF‑Datei zu öffnen. Die `Document`‑Klasse von Aspose.PDF übernimmt alles von der Analyse bis zur Darstellung. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Warum das wichtig ist:* Das Laden der Datei erstellt eine In‑Memory‑Repräsentation, die es Ihnen ermöglicht, Signaturen abzufragen, ohne das Dateisystem erneut zu berühren. Außerdem wird die PDF‑Struktur frühzeitig validiert, sodass Sie sofort eine Ausnahme erhalten, wenn die Datei beschädigt ist. + +## Schritt 2: **PDF‑Signaturen auflisten** – Alle eingebetteten Signaturen enumerieren + +Ein signiertes PDF kann mehrere Signaturen enthalten (denken Sie an einen mehrseitigen Vertrag, bei dem jede Partei eine andere Seite unterschreibt). Aspose.PDF stellt sie über die `Signatures`‑Sammlung bereit. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Was Sie sehen:* Die Schleife gibt die Details der **PDF‑Signaturen auflisten** aus, wie den Namen des Unterzeichners, Grund, Ort und Zeitstempel. Das ist praktisch für Audit‑Logs oder UI‑Darstellungen. + +## Schritt 3: **PDF‑Signatur validieren** – Auf Kompromittierung prüfen + +Jetzt kommt der sicherheitskritische Teil: Bestätigung, dass keine der Signaturen nach dem Signieren verändert wurde. Ab Version 25.3 stellt Aspose.PDF das Flag `PdfSignatureValidator.IsCompromised` bereit. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Warum Sie `IsCompromised` verwenden sollten*: Traditionelle Validierung prüft nur die kryptografische Kette (Zertifikatsgültigkeit, Widerruf usw.). `IsCompromised` fügt eine zusätzliche Ebene hinzu, indem es alle nachträglichen Änderungen am Dokument erkennt – genau das, was Sie benötigen, wenn Sie **PDF‑Signatur validieren** auf Manipulation. + +## Schritt 4: Behandlung von Validierungsergebnissen + +Abhängig vom Ergebnis möchten Sie möglicherweise unterschiedliche Aktionen ausführen. Hier ist ein kurzes Muster, das Sie anpassen können: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Hinweis zum Sonderfall:* Wenn ein PDF eine **zertifizierte** Signatur enthält (die erste Signatur, die das Dokument sperrt), kann eine spätere Änderung die gesamte Datei ungültig machen, selbst wenn nachfolgende Signaturen in Ordnung zu sein scheinen. Behandeln Sie jedes `true` von `IsCompromised` immer als Warnsignal. + +## Vollständiges funktionierendes Beispiel + +Wenn wir alles zusammenfügen, erhalten Sie ein einzelnes, eigenständiges Programm, das Sie kompilieren und ausführen können: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Erwartete Ausgabe** (angenommen, eine gültige Signatur und eine manipulierte): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Häufige Fallstricke & wie man sie vermeidet + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| **Fehlende Aspose.PDF‑Version** | `IsCompromised` wurde in 25.3 eingeführt. Ältere Pakete lassen sich kompilieren, werfen aber `MissingMethodException`. | Stellen Sie sicher, dass Ihre NuGet‑Referenz `>= 25.3` ist. | +| **Null `SignatureInfo`** | Einige PDFs haben leere Signatur‑Slots, die dennoch in der Sammlung erscheinen. | Schützen Sie mit `if (signatureInfo != null)` vor der Validierung. | +| **Leistungsprobleme bei großen PDFs** | Die Validierung jeder Signatur liest jedes Mal die gesamte Datei. | Cache den `PdfSignatureValidator` oder verarbeite Signaturen stapelweise, wenn Sie nur eine boolesche Zusammenfassung benötigen. | +| **Zertifikatswiderruf nicht geprüft** | `IsCompromised` gibt nur Auskunft über Dokumentänderungen, nicht über den Zertifikatstatus. | Verwenden Sie `PdfSignatureValidator.Validate()` zusätzlich zu `IsCompromised` für vollständige PKI‑Prüfungen. | + +## Lösung erweitern + +Wenn Sie **PDF‑Signaturen auflisten** in einer UI benötigen, geben Sie die `SignatureInfo`‑Objekte einfach an ein Data‑Grid weiter. Möchten Sie Validierungsergebnisse in einer Datenbank speichern? Serialisieren Sie das boolesche `isCompromised` zusammen mit dem Namen des Unterzeichners und dem Zeitstempel. + +Weitere verwandte Themen, die Sie als Nächstes erkunden können: + +- **PDF‑Signatur gegen eine vertrauenswürdige Root‑CA validieren** (verwenden Sie `validator.Validate()`). +- **Eingebettete Zertifikatsdetails extrahieren** (`validator.Certificate`). +- **Digitale Signaturen erstellen** mit Aspose.PDF (`PdfSignatureBuilder`). + +## Fazit + +Sie haben jetzt eine praxisnahe, durchgängige Methode, um **PDF‑Signatur zu validieren** und **PDF‑Signaturen aufzulisten** mit Aspose.PDF für .NET. Der Code zeigt genau, wie ein Dokument geladen, jede Signatur enumeriert, das `IsCompromised`‑Flag geprüft und basierend auf dem Ergebnis gehandelt wird – alles in einem klaren, konsolenfreundlichen Format. + +Probieren Sie es mit Ihren eigenen signierten PDFs aus, experimentieren Sie mit mehreren Signaturen und integrieren Sie die Logik in Ihre größere Dokumentverarbeitungspipeline. Sichere PDFs sind nur so stark wie die von Ihnen durchgeführte Validierung, also halten Sie die Prüfungen streng und die Protokolle umfassend. + +Haben Sie Fragen oder möchten Sie einen interessanten Anwendungsfall teilen? Hinterlassen Sie unten einen Kommentar oder melden Sie sich bei mir auf GitHub. Viel Spaß beim Programmieren! + +![PDF‑Signatur validieren](/images/validate-pdf-signature.png "Screenshot einer C#‑Konsolenanwendung, die eine PDF‑Signatur mit Aspose.PDF validiert") + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man PDF überprüft – PDF‑Signatur mit Aspose validieren](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Wie man PDF‑Signaturinformationen mit Aspose.PDF .NET extrahiert: Eine Schritt‑für‑Schritt‑Anleitung](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Wie man Bilder aus PDF‑Signaturfeldern mit Aspose.PDF für .NET extrahiert: Eine Schritt‑für‑Schritt‑Anleitung](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/german/net/programming-with-operators/_index.md b/pdf/german/net/programming-with-operators/_index.md index 4969bb117c..b62a2c5a53 100644 --- a/pdf/german/net/programming-with-operators/_index.md +++ b/pdf/german/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Die Tutorials „Programmieren mit Operatoren“ von Aspose.PDF für .NET führe | [XForm auf der Seite zeichnen](./draw-xform-on-page/) | Lernen Sie mit dieser umfassenden Schritt-für-Schritt-Anleitung, wie Sie mit Aspose.PDF für .NET XForms in PDF zeichnen. | | [PDF-Operatoren](./pdf-operators/) | Schritt-für-Schritt-Anleitung zur Verwendung von PDF-Operatoren mit Aspose.PDF für .NET. Fügen Sie einer PDF-Seite ein Bild hinzu und geben Sie seine Position an. | | [Grafikobjekte in PDF-Datei entfernen](./remove-graphics-objects/) Erfahren Sie in dieser Schritt-für-Schritt-Anleitung, wie Sie mit Aspose.PDF für .NET Grafikobjekte aus einer PDF-Datei entfernen. Vereinfachen Sie Ihre PDF-Bearbeitungsaufgaben. | +| [Leeres PDF-Wörterbuch in C# erstellen – Vollständige Aspose.Pdf-Anleitung](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Erfahren Sie, wie Sie mit Aspose.PDF für .NET ein leeres PDF-Wörterbuch in C# erstellen und nutzen. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/german/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/german/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..f3ed7321a1 --- /dev/null +++ b/pdf/german/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-07-26 +description: Erstellen Sie ein leeres PDF‑Wörterbuch mit Aspose.Pdf in C#. Lernen + Sie Schritt für Schritt, wie Sie einen Grafikzustand zum ExtGState‑Wörterbuch für + die PDF‑Manipulation hinzufügen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: de +lastmod: 2026-07-26 +og_description: Erstellen Sie ein leeres PDF‑Dictionary mit Aspose.Pdf für C#. Folgen + Sie dieser praxisnahen Anleitung, um Grafikzustände in Ihren PDFs zu ändern. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Leeres PDF‑Wörterbuch in C# erstellen – Vollständiges Aspose.Pdf‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Leeres PDF‑Wörterbuch in C# erstellen – Vollständiger Aspose.Pdf‑Leitfaden +url: /de/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Leeres PDF‑Dictionary in C# erstellen – Vollständiger Aspose.Pdf‑Leitfaden + +Haben Sie sich schon einmal gefragt, wie man **leere PDF‑Dictionary**‑Einträge erstellt, wenn man den Grafik‑Status eines PDFs anpasst? Sie sind nicht allein – viele Entwickler stoßen auf dieses Problem, wenn sie Opazität oder Mischmodi programmgesteuert ändern wollen. In diesem Tutorial zeigen wir Ihnen eine konkrete Lösung mit Aspose.Pdf für C#, die exakt erklärt, wie man einen neuen Grafik‑Status in das *ExtGState*‑Dictionary einer bestehenden PDF‑Datei einfügt. + +Wir behandeln alles, was Sie benötigen: Laden einer PDF, Zugriff auf das Ressourcen‑Dictionary, Erzeugen eines frischen **CosPdfDictionary** und schließlich das Persistieren der Änderungen. Am Ende haben Sie ein wiederverwendbares Muster für alle *PDF‑Grafik‑Status*‑Anpassungen, die Sie benötigen könnten. + +--- + +## Was Sie lernen werden + +- Wie man **leere PDF‑Dictionary**‑Objekte mit der Low‑Level‑API von Aspose.Pdf erstellt. +- Die Rolle des **ExtGState‑Dictionary** bei der Steuerung von Strich‑/Füll‑Opazität und Mischmodi. +- Praktische Tipps zur PDF‑Manipulation in C#, inkl. Edge‑Case‑Handling, wenn das Dictionary fehlt. +- Ein vollständiges, ausführbares Code‑Beispiel, das Sie einfach in Ihr Projekt kopieren können. + +### Voraussetzungen + +- .NET 6.0 oder höher (der Code funktioniert auch mit .NET Framework 4.6+). +- Eine lizenzierte Kopie von **Aspose.Pdf for .NET** (die kostenlose Testversion reicht zum Ausprobieren). +- Grundkenntnisse in C# und PDF‑Konzepten wie Ressourcen und Grafik‑Status. + +Falls Ihnen das noch nicht vertraut ist, keine Panik – Sie können Aspose.Pdf via NuGet installieren (`Install-Package Aspose.Pdf`) und der Rest ist reines C#. + +--- + +## Schritt 1 – PDF‑Dokument laden + +Zuerst benötigen Sie ein `Document`‑Objekt, das die zu bearbeitende Datei repräsentiert. Das Einbetten in einen `using`‑Block sorgt für eine korrekte Entsorgung. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Warum das wichtig ist*: Durch das Öffnen der Datei erhalten Sie Zugriff auf die internen COS (Canonical Object Structure)‑Objekte, in denen das **CosPdfDictionary** lebt. Ohne das Dokument‑Objekt können Sie nicht auf die Ressourcen‑Dictionaries zugreifen, die die **ExtGState**‑Einträge enthalten. + +--- + +## Schritt 2 – Auf das Ressourcen‑Dictionary der ersten Seite zugreifen + +PDF‑Seiten speichern ihre Ressourcen (Schriften, Bilder, Grafik‑Status usw.) in einem eigenen Dictionary. Wir holen uns zur Vereinfachung die erste Seite, aber dieselbe Logik gilt für jede Seiten‑Nummer. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Pro‑Tipp*: Hat Ihre PDF mehrere Seiten mit unterschiedlichen Ressourcen‑Sets, wiederholen Sie diesen Block für jede Seite, die Sie ändern möchten. Die Klasse `DictionaryEditor` ist ein praktischer Wrapper, der es Ihnen ermöglicht, das COS‑Dictionary wie ein .NET `Dictionary` zu behandeln. + +--- + +## Schritt 3 – Das ExtGState‑Dictionary abrufen oder initialisieren + +Das **ExtGState‑Dictionary** enthält benannte Grafik‑Status‑Objekte (`GS0`, `GS1`, …). Manche PDFs besitzen es bereits, andere nicht. Wir holen es sicher ab und erzeugen bei Bedarf ein neues leeres Dictionary. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Warum wir das tun*: Der Versuch, einen Grafik‑Status zu einem nicht vorhandenen **ExtGState‑Dictionary** hinzuzufügen, würde eine Ausnahme auslösen. Diese defensive Prüfung macht den Code robust für jede Eingabe‑PDF. + +--- + +## Schritt 4 – Einen neuen Grafik‑Status mit CosPdfDictionary erstellen + +Jetzt kommt der Kern des Tutorials: **ein leeres PDF‑Dictionary** erstellen, das einen benutzerdefinierten Grafik‑Status definiert. Wir setzen Strich‑Opazität (`CA`), Füll‑Opazität (`ca`) und Mischmodus (`BM`). Weitere Einträge können später hinzugefügt werden – das ist nur ein Grundset. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Erklärung*: +- `CA` und `ca` sind standardisierte PDF‑Schlüssel, die die Strich‑ bzw. Füll‑Opazität steuern. +- `BM` wählt den Mischmodus; „Normal“ ist der Standard, Sie können aber auch „Multiply“, „Screen“ usw. verwenden, je nach Design‑Bedarf. +- Durch `CosPdfDictionary.CreateEmptyDictionary` **erstellen wir leere PDF‑Dictionary**‑Objekte, die wir anschließend mit Schlüssel‑/Wert‑Paaren füllen. + +--- + +## Schritt 5 – Den neuen Grafik‑Status in ExtGState einfügen + +Nachdem der Grafik‑Status fertig ist, fügen wir ihn einfach dem **ExtGState‑Dictionary** unter einem eindeutigen Namen (z. B. `GS0`) hinzu. Wenn Sie mehrere Zustände hinzufügen wollen, erhöhen Sie einfach das Suffix. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tipp*: Vor dem Hinzufügen sollten Sie prüfen, ob `GS0` bereits existiert, um ein Überschreiben zu vermeiden. Eine kurze `if (!extGState.ContainsKey("GS0"))`‑Abfrage erledigt das. + +--- + +## Schritt 6 – Das modifizierte PDF speichern + +Alle Änderungen befinden sich im Speicher, bis Sie sie persistieren. Wählen Sie einen Ausgabepfad, der zu Ihrem Workflow passt. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Ergebnis*: Öffnen Sie `output.pdf` in einem beliebigen PDF‑Betrachter und inspizieren Sie die Seiten‑Ressourcen (z. B. mit einem PDF‑Inspector‑Tool). Sie sehen einen neuen Eintrag unter **ExtGState** namens `GS0` mit den von uns definierten Parametern. + +--- + +## Vollständiges, funktionierendes Beispiel + +Alles zusammengeführt, hier das komplette, copy‑and‑paste‑bereite Programm: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Erwartete Ausgabe**: Die `output.pdf` wird exakt wie das Original gerendert, aber jeder Inhalt, der später `GS0` referenziert (z. B. über den `gs`‑Operator in einem Content‑Stream), übernimmt die definierte Opazität und den Mischmodus. Haben Sie noch keinen solchen Verweis, können Sie ihn manuell oder über die höher‑level APIs von Aspose hinzufügen. + +--- + +## Häufig gestellte Fragen & Edge Cases + +| Frage | Antwort | +|----------|--------| +| *Was, wenn die PDF bereits einen `ExtGState`‑Eintrag namens `GS0` hat?* | Prüfen Sie `extGState.ContainsKey("GS0")` bevor Sie hinzufügen. Existiert er, können Sie bewusst überschreiben (`extGState["GS0"] = newGraphicsState`) oder einen neuen Namen wählen, z. B. `GS1`. | +| *Kann ich weitere Parameter hinzufügen, wie Linienbreite (`LW`) oder Strichmuster (`D`)?* | Absolut. Erweitern Sie einfach das `parameters`‑Array um zusätzliche `KeyValuePair`‑Einträge. | +| *Ist dieser Ansatz mit verschlüsselten PDFs kompatibel?* | Ja, solange Sie beim Erzeugen des `Document` das korrekte Passwort übergeben (`new Document(path, password)`). | +| *Muss ich das Dokument manuell schließen?* | Der `using`‑Block übernimmt die Entsorgung, wodurch auch ausstehende Änderungen geschrieben werden. | +| *Wie unterscheidet sich das von der Verwendung der High‑Level‑Klasse `Graphics`?* | Die High‑Level‑API abstrahiert die zugrunde liegenden Dictionaries, was für einfache Aufgaben praktisch ist. Wenn Sie jedoch feinkörnige Kontrolle über Grafik‑Status benötigen – etwa benutzerdefinierte Mischmodi – müssen Sie mit dem Low‑Level **CosPdfDictionary** arbeiten, also **leere PDF‑Dictionary**‑Objekte direkt **erstellen**. | + +--- + +## Fazit + +Wir haben gezeigt, wie man mit Aspose.Pdf **leere PDF‑Dictionary**‑Objekte erstellt, einen benutzerdefinierten Grafik‑Status in das **ExtGState‑Dictionary** einfügt und die geänderte Datei speichert – alles in sauberem, idiomatischem C#. Dieses Muster ermöglicht präzise Kontrolle über Opazität, Mischmodi und alle anderen Grafik‑Status‑Parameter, die im PDF‑Standard definiert sind. + +Von hier aus können Sie: + +- Den neuen Grafik‑Status auf bestehenden Seiteninhalt mittels des `gs`‑Operators anwenden. +- Eine Bibliothek wiederverwendbarer Grafik‑Status für Branding oder Wasserzeichen aufbauen. +- + + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/greek/net/digital-signatures/_index.md b/pdf/greek/net/digital-signatures/_index.md index e08abd976f..3852251a7e 100644 --- a/pdf/greek/net/digital-signatures/_index.md +++ b/pdf/greek/net/digital-signatures/_index.md @@ -59,6 +59,9 @@ ### [Επικύρωση υπογραφής PDF με το Aspose – Μετατροπή PDF σε HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Μάθετε πώς να επικυρώνετε υπογραφές PDF και να μετατρέπετε PDF σε HTML με το Aspose.PDF για .NET. +### [Επικύρωση υπογραφής PDF και λίστα υπογραφών PDF με το Aspose.PDF – Πλήρης Οδηγός](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Μάθετε πώς να επικυρώσετε υπογραφές PDF και να εμφανίσετε όλες τις υπογραφές ενός εγγράφου χρησιμοποιώντας το Aspose.PDF για .NET. + ## Πρόσθετοι Πόροι - [Aspose.PDF για τεκμηρίωση δικτύου](https://docs.aspose.com/pdf/net/) diff --git a/pdf/greek/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/greek/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..6183be1e9c --- /dev/null +++ b/pdf/greek/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-26 +description: Επικύρωση υπογραφής PDF και λίστα υπογραφών PDF χρησιμοποιώντας το Aspose.PDF + σε C#. Κώδικας βήμα‑βήμα, πιθανά προβλήματα και βέλτιστες πρακτικές για ασφαλή διαχείριση + εγγράφων. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: el +lastmod: 2026-07-26 +og_description: Επικυρώστε την υπογραφή PDF και καταγράψτε τις υπογραφές PDF με το + Aspose.PDF. Ακολουθήστε αυτόν τον πρακτικό οδηγό για να ασφαλίσετε τα PDF σε C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Επικύρωση Υπογραφής PDF & Λίστα Υπογραφών PDF – Aspose.PDF Οδηγός +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Επικύρωση υπογραφής PDF και λίστα υπογραφών PDF με το Aspose.PDF – Πλήρης οδηγός +url: /el/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Επικύρωση Υπογραφής PDF και Λίστα Υπογραφών PDF με το Aspose.PDF – Πλήρης Οδηγός + +Έχετε ποτέ αναρωτηθεί πώς να **επαληθεύσετε την υπογραφή PDF** σε μια εφαρμογή .NET χωρίς να τρελαίνεστε; Δεν είστε οι μόνοι. Είτε δημιουργείτε μια πλατφόρμα e‑sign είτε απλώς χρειάζεστε να βεβαιωθείτε ότι ένα ληφθέν συμβόλαιο δεν έχει αλλοιωθεί, η δυνατότητα **να καταγράψετε τις υπογραφές PDF** και να επαληθεύσετε καθεμία είναι απαραίτητη δεξιότητα. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πλήρως εκτελέσιμο παράδειγμα που φορτώνει ένα υπογεγραμμένο PDF, απαριθμεί κάθε ενσωματωμένη υπογραφή, ελέγχει αν κάποια από αυτές έχει παραβιαστεί και εκτυπώνει ένα σαφές αποτέλεσμα στην κονσόλα. Χωρίς ασαφείς αναφορές — μόνο ο κώδικας που μπορείτε να αντιγράψετε‑επικολλήσετε, μαζί με το «γιατί» πίσω από κάθε βήμα. + +## Προαπαιτούμενα + +- **Aspose.PDF for .NET** έκδοση 25.3 ή νεότερη (η ιδιότητα `IsCompromised` εμφανίστηκε στην 25.3). +- Ένα περιβάλλον ανάπτυξης .NET (Visual Studio 2022, Rider ή το `dotnet` CLI). +- Ένα υπογεγραμμένο αρχείο PDF για δοκιμή (μπορείτε να δημιουργήσετε ένα με το Adobe Acrobat ή οποιοδήποτε εργαλείο e‑signature). + +Αν κάποιο από αυτά λείπει, εγκαταστήστε πρώτα το πακέτο NuGet: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Συμβουλή:** Στοχεύστε .NET 6 ή νεότερο για την καλύτερη απόδοση και μακροπρόθεσμη υποστήριξη. + +## Βήμα 1: Φόρτωση του Εγγράφου PDF + +Το πρώτο πράγμα που πρέπει να κάνετε είναι να ανοίξετε το αρχείο PDF. Η κλάση `Document` του Aspose.PDF διαχειρίζεται τα πάντα, από την ανάλυση μέχρι την απόδοση. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Γιατί είναι σημαντικό:* Η φόρτωση του αρχείου δημιουργεί μια αναπαράσταση στη μνήμη που σας επιτρέπει να ερωτήσετε τις υπογραφές χωρίς να αγγίξετε ξανά το σύστημα αρχείων. Επίσης επικυρώνει τη δομή του PDF νωρίς, ώστε να λάβετε άμεσα εξαίρεση αν το αρχείο είναι κατεστραμμένο. + +## Βήμα 2: **Λίστα Υπογραφών PDF** – Απαρίθμηση Όλων των Ενσωματωμένων Υπογραφών + +Ένα υπογεγραμμένο PDF μπορεί να περιέχει πολλαπλές υπογραφές (σκεφτείτε ένα συμβόλαιο πολλαπλών σελίδων όπου κάθε μέρος υπογράφει διαφορετική σελίδα). Το Aspose.PDF τις εκθέτει μέσω της συλλογής `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Τι βλέπετε:* Ο βρόχος εκτυπώνει τις λεπτομέρειες των **υπογραφών PDF** όπως το όνομα του υπογράφοντα, ο λόγος, η τοποθεσία και η χρονική σήμανση. Αυτό είναι χρήσιμο για αρχεία ελέγχου ή εμφανίσεις UI. + +## Βήμα 3: **Επικύρωση Υπογραφής PDF** – Έλεγχος για Παραβίαση + +Τώρα έρχεται το κρίσιμο τμήμα ασφαλείας: η επιβεβαίωση ότι καμία από τις υπογραφές δεν έχει τροποποιηθεί μετά την υπογραφή. Ξεκινώντας από την έκδοση 25.3, το Aspose.PDF παρέχει τη σημαία `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Γιατί πρέπει να χρησιμοποιήσετε το `IsCompromised`*: Η παραδοσιακή επικύρωση ελέγχει μόνο την κρυπτογραφική αλυσίδα (εγκυρότητα πιστοποιητικού, ανάκληση κ.λπ.). Το `IsCompromised` προσθέτει ένα επιπλέον επίπεδο εντοπίζοντας τυχόν αλλαγές μετά την υπογραφή του εγγράφου — ακριβώς αυτό που χρειάζεστε όταν **επικυρώνετε την υπογραφή PDF** για παραβίαση. + +## Βήμα 4: Διαχείριση Αποτελεσμάτων Επικύρωσης + +Ανάλογα με το αποτέλεσμα, μπορεί να θέλετε να λάβετε διαφορετικές ενέργειες. Εδώ είναι ένα γρήγορο μοτίβο που μπορείτε να προσαρμόσετε: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Σημείωση ακραίας περίπτωσης:* Αν ένα PDF περιέχει μια **πιστοποιημένη** υπογραφή (η πρώτη υπογραφή που κλειδώνει το έγγραφο), μια μεταγενέστερη τροποποίηση μπορεί να ακυρώσει ολόκληρο το αρχείο, ακόμη και αν οι επόμενες υπογραφές φαίνονται εντάξει. Θεωρείτε πάντα οποιοδήποτε `true` από το `IsCompromised` ως κόκκινη σημαία. + +## Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα, εδώ είναι ένα ενιαίο, αυτόνομο πρόγραμμα που μπορείτε να μεταγλωττίσετε και να εκτελέσετε: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Αναμενόμενη έξοδος** (υποθέτοντας μία καλή υπογραφή και μία αλλοιωμένη): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Συνηθισμένα Παράπτωμα & Πώς να τα Αποφύγετε + +| Πρόβλημα | Γιατί Συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| **Λείπει η έκδοση Aspose.PDF** | Το `IsCompromised` εισήχθη στην 25.3. Παλαιότερα πακέτα μεταγλωττίζονται αλλά πετούν `MissingMethodException`. | Βεβαιωθείτε ότι η αναφορά NuGet είναι `>= 25.3`. | +| **Null `SignatureInfo`** | Κάποια PDFs έχουν κενές θέσεις υπογραφής που εξακολουθούν να εμφανίζονται στη συλλογή. | Προστατέψτε με `if (signatureInfo != null)` πριν την επικύρωση. | +| **Πρόσπτωση απόδοσης σε μεγάλα PDFs** | Η επικύρωση κάθε υπογραφής διαβάζει ολόκληρο το αρχείο κάθε φορά. | Κρατήστε στην μνήμη τον `PdfSignatureValidator` ή επεξεργαστείτε τις υπογραφές σε παρτίδες αν χρειάζεστε μόνο μια λογική σύνοψη. | +| **Δεν ελέγχεται η ανάκληση πιστοποιητικού** | Το `IsCompromised` σας ενημερώνει μόνο για αλλαγές στο έγγραφο, όχι για την κατάσταση του πιστοποιητικού. | Χρησιμοποιήστε `PdfSignatureValidator.Validate()` επιπλέον του `IsCompromised` για πλήρη ελέγχους PKI. | + +## Επέκταση της Λύσης + +Αν χρειάζεστε να **καταγράψετε τις υπογραφές PDF** σε UI, απλώς περάστε τα αντικείμενα `SignatureInfo` σε ένα data grid. Θέλετε να αποθηκεύσετε τα αποτελέσματα επικύρωσης σε βάση δεδομένων; Σειριοποιήστε το boolean `isCompromised` μαζί με το όνομα του υπογράφοντα και τη χρονική σήμανση. + +Άλλα συναφή θέματα που μπορείτε να εξερευνήσετε: + +- **Επικύρωση υπογραφής PDF έναντι αξιόπιστης ρίζας CA** (χρησιμοποιήστε `validator.Validate()`). +- **Εξαγωγή ενσωματωμένων λεπτομερειών πιστοποιητικού** (`validator.Certificate`). +- **Δημιουργία ψηφιακών υπογραφών** με Aspose.PDF (`PdfSignatureBuilder`). + +## Συμπέρασμα + +Τώρα έχετε μια πρακτική, ολοκληρωμένη μέθοδο για **να επικυρώσετε την υπογραφή PDF** και **να καταγράψετε τις υπογραφές PDF** χρησιμοποιώντας το Aspose.PDF για .NET. Ο κώδικας δείχνει ακριβώς πώς να φορτώσετε ένα έγγραφο, να απαριθμήσετε κάθε υπογραφή, να ελέγξετε τη σημαία `IsCompromised` και να ενεργήσετε βάσει του αποτελέσματος — όλα σε μια σαφή, φιλική προς την κονσόλα μορφή. + +Δοκιμάστε το με τα δικά σας υπογεγραμμένα PDFs, πειραματιστείτε με πολλαπλές υπογραφές και ενσωματώστε τη λογική στο ευρύτερο pipeline επεξεργασίας εγγράφων. Τα ασφαλή PDFs είναι τόσο ισχυρά όσο η επικύρωση που εκτελείτε, οπότε διατηρήστε τους ελέγχους αυστηρούς και τα αρχεία καταγραφής πλήρη. + +Έχετε ερωτήσεις ή θέλετε να μοιραστείτε μια ενδιαφέρουσα περίπτωση χρήσης; Αφήστε ένα σχόλιο παρακάτω ή στείλτε μου μήνυμα στο GitHub. Καλό κώδικα! + +![Επικύρωση Υπογραφής PDF](/images/validate-pdf-signature.png "Στιγμιότυπο οθόνης μιας εφαρμογής C# console που επικυρώνει μια υπογραφή PDF με το Aspose.PDF") + +## Τι Θα Πρέπει Να Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να Επαληθεύσετε PDF – Επικύρωση Υπογραφής PDF με το Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Πώς να Εξάγετε Πληροφορίες Υπογραφής PDF Χρησιμοποιώντας Aspose.PDF .NET: Οδηγός Βήμα‑Βήμα](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Πώς να Εξάγετε Εικόνες από Πεδία Υπογραφής PDF χρησιμοποιώντας Aspose.PDF για .NET: Οδηγός Βήμα‑Βήμα](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/greek/net/programming-with-operators/_index.md b/pdf/greek/net/programming-with-operators/_index.md index d85e0461f7..23dca3395f 100644 --- a/pdf/greek/net/programming-with-operators/_index.md +++ b/pdf/greek/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ | [Σχεδίαση XForm στη σελίδα](./draw-xform-on-page/) | μάθετε πώς να σχεδιάζετε XForms σε PDF χρησιμοποιώντας το Aspose.PDF για .NET με αυτόν τον ολοκληρωμένο οδηγό βήμα προς βήμα. | | [Τελεστές PDF](./pdf-operators/) | Οδηγός βήμα προς βήμα για τη χρήση τελεστών PDF με το Aspose.PDF για .NET. Προσθέστε μια εικόνα σε μια σελίδα PDF και καθορίστε τη θέση της. | | [Αφαίρεση γραφικών αντικειμένων σε αρχείο PDF](./remove-graphics-objects/) Μάθετε πώς να αφαιρείτε γραφικά αντικείμενα από ένα αρχείο PDF χρησιμοποιώντας το Aspose.PDF για .NET σε αυτόν τον οδηγό βήμα προς βήμα. Απλοποιήστε τις εργασίες χειρισμού PDF. | +| [Δημιουργία Κενής Λεξικού PDF σε C# – Πλήρης Οδηγός Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Μάθετε πώς να δημιουργήσετε ένα κενό λεξικό PDF σε C# χρησιμοποιώντας το Aspose.PDF για .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/greek/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/greek/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..47687cab62 --- /dev/null +++ b/pdf/greek/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Δημιουργήστε κενό λεξικό PDF με το Aspose.Pdf σε C#. Μάθετε βήμα‑βήμα + πώς να προσθέσετε μια κατάσταση γραφικών στο λεξικό ExtGState για τη διαχείριση + PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: el +lastmod: 2026-07-26 +og_description: Δημιουργήστε κενό λεξικό PDF χρησιμοποιώντας το Aspose.Pdf για C#. + Ακολουθήστε αυτόν τον πρακτικό οδηγό για να τροποποιήσετε τις καταστάσεις γραφικών + στα PDF σας. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Δημιουργία Κενής Λεξικού PDF σε C# – Πλήρης Οδηγός Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Δημιουργία Κενού Λεξικού PDF σε C# – Πλήρης Οδηγός Aspose.Pdf +url: /el/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία Κενής Λεξικού PDF σε C# – Πλήρης Οδηγός Aspose.Pdf + +Έχετε αναρωτηθεί ποτέ πώς να **create empty PDF dictionary** καταχωρήσεις όταν τροποποιείτε την κατάσταση γραφικών ενός PDF; Δεν είστε μόνοι—πολλοί προγραμματιστές αντιμετωπίζουν αυτό το πρόβλημα προσπαθώντας να ρυθμίσουν την αδιαφάνεια ή τις λειτουργίες ανάμειξης προγραμματιστικά. Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα μια συγκεκριμένη λύση χρησιμοποιώντας το Aspose.Pdf για C#, δείχνοντας ακριβώς πώς να ενσωματώσετε μια νέα κατάσταση γραφικών στο λεξικό *ExtGState* ενός υπάρχοντος PDF. + +Θα καλύψουμε όλα όσα χρειάζεστε: φόρτωση ενός PDF, πρόσβαση στο λεξικό πόρων του, δημιουργία ενός νέου **CosPdfDictionary**, και τελικά αποθήκευση των αλλαγών. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο πρότυπο για οποιεσδήποτε τροποποιήσεις *PDF graphics state* χρειαστείτε. + +--- + +## Τι Θα Μάθετε + +- Πώς να δημιουργήσετε αντικείμενα **create empty PDF dictionary** με το low‑level API του Aspose.Pdf. +- Ο ρόλος του **ExtGState dictionary** στον έλεγχο της αδιαφάνειας γραμμής/γέμισης και των λειτουργιών ανάμειξης. +- Πρακτικές συμβουλές για τη διαχείριση PDF με C#, συμπεριλαμβανομένου του χειρισμού ειδικών περιπτώσεων όταν λείπει το λεξικό. +- Ένα πλήρες, εκτελέσιμο παράδειγμα κώδικα που μπορείτε να αντιγράψετε‑και‑επικολλήσετε στο έργο σας. + +### Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Framework 4.6+). +- Μια αδειοδοτημένη έκδοση του **Aspose.Pdf for .NET** (η δωρεάν δοκιμή λειτουργεί για δοκιμές). +- Βασική εξοικείωση με C# και έννοιες PDF όπως πόροι και καταστάσεις γραφικών. + +Αν κάποιο από αυτά σας φαίνεται άγνωστο, μην πανικοβάλλεστε—μπορείτε να εγκαταστήσετε το Aspose.Pdf μέσω NuGet (`Install-Package Aspose.Pdf`) και το υπόλοιπο είναι απλώς καθαρό C#. + +--- + +## Βήμα 1 – Φόρτωση του Εγγράφου PDF + +Πρώτα απ' όλα, χρειάζεστε ένα αντικείμενο `Document` που αντιπροσωπεύει το αρχείο που θέλετε να επεξεργαστείτε. Η τοποθέτησή του μέσα σε ένα μπλοκ `using` εγγυάται σωστή απελευθέρωση. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Γιατί είναι σημαντικό*: Το άνοιγμα του αρχείου σας δίνει πρόσβαση στα εσωτερικά αντικείμενα COS (Canonical Object Structure), όπου βρίσκεται το **CosPdfDictionary**. Χωρίς το αντικείμενο εγγράφου, δεν μπορείτε να φτάσετε στα λεξικά πόρων που περιέχουν τις καταχωρήσεις **ExtGState**. + +--- + +## Βήμα 2 – Πρόσβαση στο Λεξικό Πόρων της Πρώτης Σελίδας + +Οι σελίδες PDF αποθηκεύουν τους πόρους τους (γραμματοσειρές, εικόνες, καταστάσεις γραφικών κ.λπ.) σε ένα αφιερωμένο λεξικό. Θα πάρουμε την πρώτη σελίδα για απλότητα, αλλά η ίδια λογική ισχύει για οποιονδήποτε δείκτη σελίδας. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Συμβουλή*: Αν το PDF σας έχει πολλαπλές σελίδες με διαφορετικά σύνολα πόρων, επαναλάβετε αυτό το μπλοκ για κάθε σελίδα που χρειάζεται να τροποποιήσετε. Η κλάση `DictionaryEditor` είναι ένας βολικός περιτύλιγμα που σας επιτρέπει να αντιμετωπίζετε το λεξικό COS σαν ένα .NET `Dictionary`. + +--- + +## Βήμα 3 – Ανάκτηση ή Αρχικοποίηση του Λεξικού ExtGState + +Το **ExtGState dictionary** περιέχει αντικείμενα κατάστασης γραφικών με ονόματα (`GS0`, `GS1`, …). Κάποια PDFs το περιέχουν ήδη· άλλα όχι. Θα το ανακτήσουμε με ασφάλεια, δημιουργώντας ένα νέο κενό αν χρειάζεται. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Γιατί το κάνουμε*: Η προσπάθεια προσθήκης μιας κατάστασης γραφικών σε ένα μη‑υπάρχον **ExtGState dictionary** θα προκαλούσε εξαίρεση. Αυτός ο αμυντικός έλεγχος κάνει τον κώδικα ανθεκτικό για οποιοδήποτε εισερχόμενο PDF. + +--- + +## Βήμα 4 – Δημιουργία Νέας Κατάστασης Γραφικών με CosPdfDictionary + +Τώρα έρχεται η καρδιά του tutorial: **creating an empty PDF dictionary** που ορίζει μια προσαρμοσμένη κατάσταση γραφικών. Θα ορίσουμε την αδιαφάνεια γραμμής (`CA`), την αδιαφάνεια γεμίσματος (`ca`) και τη λειτουργία ανάμειξης (`BM`). Μπορείτε να προσθέσετε περισσότερες καταχωρήσεις αργότερα—αυτή είναι μόνο μια αρχική ομάδα. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Εξήγηση*: +- `CA` και `ca` είναι τυπικά κλειδιά PDF που ελέγχουν την αδιαφάνεια γραμμής και γεμίσματος, αντίστοιχα. +- `BM` επιλέγει τη λειτουργία ανάμειξης· το “Normal” είναι η προεπιλογή αλλά μπορείτε να χρησιμοποιήσετε “Multiply”, “Screen”, κ.λπ., ανάλογα με τις ανάγκες του σχεδίου σας. +- Χρησιμοποιώντας το `CosPdfDictionary.CreateEmptyDictionary`, **create empty PDF dictionary** αντικείμενα που αργότερα γεμίζουμε με ζεύγη κλειδί/τιμή. + +--- + +## Βήμα 5 – Εισαγωγή της Νέας Κατάστασης Γραφικών στο ExtGState + +Με την κατάσταση γραφικών έτοιμη, απλώς την προσθέτουμε στο **ExtGState dictionary** κάτω από ένα μοναδικό όνομα (π.χ., `GS0`). Αν σκοπεύετε να προσθέσετε πολλαπλές καταστάσεις, απλώς αυξήστε το επίθημα. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Συμβουλή*: Πριν προσθέσετε, ίσως θέλετε να ελέγξετε αν το `GS0` υπάρχει ήδη για να αποφύγετε την αντικατάσταση. Ένας γρήγορος έλεγχος `if (!extGState.ContainsKey("GS0"))` κάνει τη δουλειά. + +--- + +## Βήμα 6 – Αποθήκευση του Τροποποιημένου PDF + +Όλες οι αλλαγές παραμένουν στη μνήμη μέχρι να τις αποθηκεύσετε. Επιλέξτε μια διαδρομή εξόδου που έχει νόημα για τη ροή εργασίας σας. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Αποτέλεσμα*: Ανοίξτε το `output.pdf` σε οποιονδήποτε προβολέα PDF, μετά ελέγξτε τους πόρους της σελίδας (π.χ., με ένα εργαλείο επιθεώρησης PDF). Θα δείτε μια νέα καταχώρηση κάτω από **ExtGState** με όνομα `GS0` και τις παραμέτρους που ορίσαμε. + +--- + +## Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα, εδώ είναι το πλήρες πρόγραμμα έτοιμο για αντιγραφή‑και‑επικόλληση: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Αναμενόμενο αποτέλεσμα**: Το `output.pdf` θα αποδίδει ακριβώς όπως το αρχικό, αλλά οποιοδήποτε περιεχόμενο που αργότερα αναφέρεται στο `GS0` (για παράδειγμα μέσω του τελεστή `gs` σε ροή περιεχομένου) θα υιοθετήσει την ορισμένη αδιαφάνεια και λειτουργία ανάμειξης. Αν δεν έχετε ακόμη τέτοια αναφορά, μπορείτε να προσθέσετε μία χειροκίνητα ή μέσω των υψηλότερου επιπέδου API του Aspose. + +--- + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +| Ερώτηση | Απάντηση | +|----------|--------| +| *Τι γίνεται αν το PDF έχει ήδη μια καταχώρηση `ExtGState` με όνομα `GS0`;* | Ελέγξτε `extGState.ContainsKey("GS0")` πριν προσθέσετε. Αν υπάρχει, είτε αντικαταστήστε το σκόπιμα (`extGState["GS0"] = newGraphicsState`) είτε επιλέξτε νέο όνομα όπως `GS1`. | +| *Μπορώ να προσθέσω περισσότερες παραμέτρους, όπως το πάχος γραμμής (`LW`) ή το μοτίβο παύλας (`D`);* | Απολύτως. Απλώς επεκτείνετε τον πίνακα `parameters` με επιπλέον εγγραφές `KeyValuePair`. | +| *Είναι αυτή η προσέγγιση συμβατή με κρυπτογραφημένα PDFs;* | Ναι, εφόσον παρέχετε τον σωστό κωδικό πρόσβασης κατά τη δημιουργία του `Document` (`new Document(path, password)`). | +| *Πρέπει να κλείσω το έγγραφο χειροκίνητα;* | Η δήλωση `using` φροντίζει για την απελευθέρωση, η οποία επίσης αποστέλλει τυχόν εκκρεμείς αλλαγές. | +| *Πώς διαφέρει αυτό από τη χρήση της υψηλού επιπέδου κλάσης `Graphics`;* | Το υψηλού επιπέδου API αφαιρεί την ανάγκη για άμεση διαχείριση των υποκείμενων λεξικών, κάτι που είναι εξαιρετικό για απλές εργασίες. Ωστόσο, όταν χρειάζεστε λεπτομερή έλεγχο των καταστάσεων γραφικών—όπως προσαρμοσμένες λειτουργίες ανάμειξης—πρέπει να εργαστείτε με το χαμηλού επιπέδου **CosPdfDictionary**, δηλαδή με αντικείμενα **create empty PDF dictionary** άμεσα. | + +--- + +## Συμπέρασμα + +Μόλις δείξαμε πώς να **create empty PDF dictionary** αντικείμενα με το Aspose.Pdf, να ενσωματώσουμε μια προσαρμοσμένη κατάσταση γραφικών στο **ExtGState dictionary**, και να αποθηκεύσουμε το τροποποιημένο αρχείο—όλα σε καθαρό, ιδιωματικό C#. Αυτό το πρότυπο παρέχει ακριβή έλεγχο της αδιαφάνειας, των λειτουργιών ανάμειξης, και οποιωνδήποτε άλλων παραμέτρων κατάστασης γραφικών που ορίζονται από την προδιαγραφή PDF. + +Από εδώ μπορείτε: + +- Εφαρμόστε τη νέα κατάσταση γραφικών στο υπάρχον περιεχόμενο της σελίδας χρησιμοποιώντας τον τελεστή `gs`. +- Δημιουργήστε μια βιβλιοθήκη επαναχρησιμοποιήσιμων καταστάσεων γραφικών για branding ή υδατογράφημα. +- + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να Δημιουργήσετε Διακεκομμένες Γραμμές σε PDFs Χρησιμοποιώντας το Aspose.PDF για .NET: Οδηγός Βήμα‑Βήμα](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Δημιουργία & Γέμισμα Ορθογωνίων σε PDFs Χρησιμοποιώντας το Aspose.PDF για .NET: Οδηγός Βήμα‑Βήμα](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/hindi/net/digital-signatures/_index.md b/pdf/hindi/net/digital-signatures/_index.md index 85a0f84d5f..7e3dd79aae 100644 --- a/pdf/hindi/net/digital-signatures/_index.md +++ b/pdf/hindi/net/digital-signatures/_index.md @@ -53,6 +53,9 @@ C# में PDF दस्तावेज़ लोड करके उसे PD ### [Aspose के साथ PDF हस्ताक्षर सत्यापित करें – PDF को HTML में परिवर्तित करें](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Aspose का उपयोग करके PDF हस्ताक्षर की वैधता जांचें और PDF को HTML में बदलें। +### [Aspose.PDF के साथ PDF हस्ताक्षर सत्यापित करें और सभी हस्ताक्षर सूचीबद्ध करें – पूर्ण गाइड](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Aspose.PDF का उपयोग करके PDF हस्ताक्षर को सत्यापित करने और दस्तावेज़ में मौजूद सभी हस्ताक्षरों की सूची प्राप्त करने की पूरी प्रक्रिया सीखें। + ## अतिरिक्त संसाधन - [Aspose.PDF for Net दस्तावेज़ीकरण](https://docs.aspose.com/pdf/net/) diff --git a/pdf/hindi/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/hindi/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..c098ce4342 --- /dev/null +++ b/pdf/hindi/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-07-26 +description: Aspose.PDF का उपयोग करके C# में PDF हस्ताक्षर को मान्य करें और PDF हस्ताक्षरों + की सूची बनाएं। चरण‑दर‑चरण कोड, संभावित समस्याएँ, और सुरक्षित दस्तावेज़ प्रबंधन के + लिए सर्वोत्तम प्रथाएँ। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: hi +lastmod: 2026-07-26 +og_description: Aspose.PDF के साथ PDF हस्ताक्षर को मान्य करें और PDF हस्ताक्षरों की + सूची बनाएं। C# में PDF को सुरक्षित करने के लिए इस व्यावहारिक गाइड का पालन करें। +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: PDF हस्ताक्षर को सत्यापित करें और PDF हस्ताक्षरों की सूची बनाएं – Aspose.PDF + कैसे‑करें +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Aspose.PDF के साथ PDF हस्ताक्षर को मान्य करें और PDF हस्ताक्षरों की सूची बनाएं + – पूर्ण मार्गदर्शिका +url: /hi/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.PDF के साथ PDF हस्ताक्षर सत्यापित करें और PDF हस्ताक्षर सूचीबद्ध करें – पूर्ण गाइड + +क्या आपने कभी सोचा है कि .NET एप्लिकेशन में **PDF हस्ताक्षर सत्यापित** कैसे किया जाए बिना सिरदर्द के? आप अकेले नहीं हैं। चाहे आप एक e‑sign प्लेटफ़ॉर्म बना रहे हों या सिर्फ यह सुनिश्चित करना चाहते हों कि प्राप्त अनुबंध में कोई छेड़छाड़ नहीं हुई है, **PDF हस्ताक्षर सूचीबद्ध** करना और प्रत्येक को सत्यापित करना एक आवश्यक कौशल है। + +इस ट्यूटोरियल में हम एक पूरी तरह चलने योग्य उदाहरण के माध्यम से जाएंगे जो एक साइन किया हुआ PDF लोड करता है, सभी एम्बेडेड हस्ताक्षरों को सूचीबद्ध करता है, जांचता है कि उनमें से कोई समझौता तो नहीं हुआ, और कंसोल में स्पष्ट परिणाम प्रिंट करता है। कोई अस्पष्ट संदर्भ नहीं—सिर्फ वह कोड जिसे आप कॉपी‑पेस्ट कर सकते हैं, साथ ही प्रत्येक चरण के “क्यों” की व्याख्या। + +## पूर्वापेक्षाएँ + +- **Aspose.PDF for .NET** संस्करण 25.3 या नया ( `IsCompromised` प्रॉपर्टी 25.3 में पेश की गई)। +- एक .NET विकास पर्यावरण (Visual Studio 2022, Rider, या `dotnet` CLI)। +- एक साइन किया हुआ PDF फ़ाइल जिसे आप परीक्षण के लिए उपयोग कर सकते हैं (आप इसे Adobe Acrobat या किसी भी e‑signature टूल से बना सकते हैं)। + +यदि इनमें से कोई भी अनुपलब्ध है, तो पहले NuGet पैकेज स्थापित करें: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** सर्वोत्तम प्रदर्शन और दीर्घकालिक समर्थन के लिए .NET 6 या बाद का लक्ष्य रखें। + +## चरण 1: PDF दस्तावेज़ लोड करें + +सबसे पहला काम है PDF फ़ाइल खोलना। Aspose.PDF की `Document` क्लास पार्सिंग से लेकर रेंडरिंग तक सब कुछ संभालती है। + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Why this matters:* फ़ाइल लोड करने से एक इन‑मेमोरी प्रतिनिधित्व बनता है जिससे आप फ़ाइल सिस्टम को फिर से छुए बिना हस्ताक्षरों को क्वेरी कर सकते हैं। यह PDF संरचना को शुरुआती चरण में ही वैध करता है, इसलिए यदि फ़ाइल भ्रष्ट है तो आपको तुरंत अपवाद मिलेगा। + +## चरण 2: **PDF हस्ताक्षर सूचीबद्ध करें** – सभी एम्बेडेड हस्ताक्षरों को क्रमबद्ध करें + +एक साइन किया हुआ PDF कई हस्ताक्षर रख सकता है (जैसे एक बहु‑पृष्ठ अनुबंध जहाँ प्रत्येक पक्ष अलग पृष्ठ पर साइन करता है)। Aspose.PDF इन्हें `Signatures` संग्रह के माध्यम से उपलब्ध कराता है। + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*What you’re seeing:* लूप **PDF हस्ताक्षर सूचीबद्ध** करने के विवरण जैसे साइनर का नाम, कारण, स्थान, और टाइमस्टैम्प प्रिंट करता है। यह ऑडिट लॉग या UI डिस्प्ले के लिए उपयोगी है। + +## चरण 3: **PDF हस्ताक्षर सत्यापित करें** – समझौता जांचें + +अब सुरक्षा‑संबंधी महत्वपूर्ण भाग आता है: यह पुष्टि करना कि साइनिंग के बाद किसी भी हस्ताक्षर में बदलाव नहीं हुआ है। संस्करण 25.3 से, Aspose.PDF `PdfSignatureValidator.IsCompromised` फ़्लैग प्रदान करता है। + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Why you should use `IsCompromised`*: पारंपरिक वैधता केवल क्रिप्टोग्राफ़िक चेन (प्रमाणपत्र वैधता, रद्दीकरण आदि) की जाँच करती है। `IsCompromised` दस्तावेज़ में साइनिंग के बाद हुए किसी भी परिवर्तन का पता लगाकर अतिरिक्त सुरक्षा परत जोड़ता है—जब आप **PDF हस्ताक्षर सत्यापित** करते हैं तो यह बिल्कुल आवश्यक है। + +## चरण 4: वैधता परिणामों को संभालना + +परिणाम के आधार पर, आप विभिन्न कार्य करना चाह सकते हैं। यहाँ एक त्वरित पैटर्न है जिसे आप अपनाकर उपयोग कर सकते हैं: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Edge case note:* यदि PDF में एक **certified** हस्ताक्षर है (पहला हस्ताक्षर जो दस्तावेज़ को लॉक करता है), तो बाद में किया गया कोई भी संशोधन पूरी फ़ाइल को अमान्य कर सकता है, भले ही बाद के हस्ताक्षर ठीक दिखें। `IsCompromised` से मिलने वाला कोई भी `true` हमेशा एक चेतावनी संकेत मानें। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ मिलाकर, यहाँ एक एकल, स्वतंत्र प्रोग्राम है जिसे आप संकलित करके चला सकते हैं: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**अपेक्षित आउटपुट** (मान लेते हैं कि एक सही हस्ताक्षर और एक छेड़छाड़ किया हुआ है): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## सामान्य कठिनाइयाँ और उन्हें कैसे टालें + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Aspose.PDF संस्करण अनुपलब्ध** | `IsCompromised` 25.3 में पेश किया गया था। पुराने पैकेज कंपाइल होते हैं लेकिन `MissingMethodException` फेंकते हैं। | सुनिश्चित करें कि आपका NuGet रेफ़रेंस `>= 25.3` है। | +| **Null `SignatureInfo`** | कुछ PDFs में खाली हस्ताक्षर स्लॉट होते हैं जो अभी भी संग्रह में दिखते हैं। | वैधता से पहले `if (signatureInfo != null)` की जाँच जोड़ें। | +| **बड़े PDFs पर प्रदर्शन गिरावट** | हर हस्ताक्षर को वैध करने से हर बार पूरी फ़ाइल पढ़ी जाती है। | यदि आपको केवल बूलियन सारांश चाहिए तो `PdfSignatureValidator` को कैश करें या हस्ताक्षरों को बैच‑प्रोसेस करें। | +| **प्रमाणपत्र रद्दीकरण जाँच नहीं हुई** | `IsCompromised` केवल दस्तावेज़ परिवर्तन के बारे में बताता है, प्रमाणपत्र स्थिति के बारे में नहीं। | पूर्ण PKI जाँच के लिए `IsCompromised` के साथ `PdfSignatureValidator.Validate()` भी उपयोग करें। | + +## समाधान का विस्तार + +यदि आपको UI में **PDF हस्ताक्षर सूचीबद्ध** करने की आवश्यकता है, तो बस `SignatureInfo` ऑब्जेक्ट को डेटा ग्रिड में पास करें। क्या आप वैधता परिणाम को डेटाबेस में संग्रहीत करना चाहते हैं? बूलियन `isCompromised` को साइनर के नाम और टाइमस्टैम्प के साथ सीरियलाइज़ करें। + +अन्य संबंधित विषय जिन्हें आप आगे देख सकते हैं: + +- **विश्वसनीय रूट CA के विरुद्ध PDF हस्ताक्षर सत्यापित करें** (`validator.Validate()` का उपयोग करें)। +- **एम्बेडेड प्रमाणपत्र विवरण निकालें** (`validator.Certificate`)। +- **डिजिटल हस्ताक्षर बनाएं** Aspose.PDF के साथ (`PdfSignatureBuilder`)। + +## निष्कर्ष + +अब आपके पास Aspose.PDF for .NET का उपयोग करके **PDF हस्ताक्षर सत्यापित** करने और **PDF हस्ताक्षर सूचीबद्ध** करने की एक व्यावहारिक, अंत‑से‑अंत विधि है। कोड यह दर्शाता है कि दस्तावेज़ कैसे लोड करें, प्रत्येक हस्ताक्षर को क्रमबद्ध करें, `IsCompromised` फ़्लैग की जाँच करें, और परिणाम के आधार पर कार्रवाई करें—सब कुछ स्पष्ट, कंसोल‑अनुकूल स्वरूप में। + +इसे अपने साइन किए हुए PDFs के साथ आज़माएँ, कई हस्ताक्षरों के साथ प्रयोग करें, और इस लॉजिक को अपने बड़े दस्तावेज़‑प्रसंस्करण पाइपलाइन में एकीकृत करें। सुरक्षित PDFs उतने ही मजबूत होते हैं जितनी आपकी वैधता प्रक्रिया, इसलिए जांच को कड़ा रखें और लॉग को विस्तृत रखें। + +कोई प्रश्न हैं या कोई रोचक उपयोग केस साझा करना चाहते हैं? नीचे टिप्पणी छोड़ें या GitHub पर मुझे संदेश भेजें। कोडिंग का आनंद लें! + +![PDF हस्ताक्षर सत्यापित करें](/images/validate-pdf-signature.png "Aspose.PDF के साथ PDF हस्ताक्षर सत्यापित करने वाले C# कंसोल ऐप का स्क्रीनशॉट") + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API सुविधाओं में निपुण बनने और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों का अन्वेषण करने में मदद करती हैं। + +- [PDF कैसे सत्यापित करें – Aspose के साथ PDF हस्ताक्षर सत्यापित करें](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Aspose.PDF .NET का उपयोग करके PDF हस्ताक्षर जानकारी निकालें: चरण‑दर‑चरण गाइड](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Aspose.PDF for .NET का उपयोग करके PDF हस्ताक्षर फ़ील्ड से छवियां निकालें: चरण‑दर‑चरण गाइड](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/hindi/net/programming-with-operators/_index.md b/pdf/hindi/net/programming-with-operators/_index.md index c421e807e7..5b4610bee3 100644 --- a/pdf/hindi/net/programming-with-operators/_index.md +++ b/pdf/hindi/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Aspose.PDF for .NET के "ऑपरेटर्स के साथ प्र | [पेज पर XForm बनाएं](./draw-xform-on-page/) | इस व्यापक चरण-दर-चरण मार्गदर्शिका के साथ .NET के लिए Aspose.PDF का उपयोग करके PDF में XForms बनाना सीखें। | | [पीडीएफ ऑपरेटर](./pdf-operators/) | .NET के लिए Aspose.PDF के साथ PDF ऑपरेटर का उपयोग करने के लिए चरण-दर-चरण मार्गदर्शिका। PDF पृष्ठ पर एक छवि जोड़ें और उसकी स्थिति निर्दिष्ट करें। | | [पीडीएफ फाइल में ग्राफिक ऑब्जेक्ट्स हटाएँ](./remove-graphics-objects/) इस चरण-दर-चरण मार्गदर्शिका में .NET के लिए Aspose.PDF का उपयोग करके PDF फ़ाइल से ग्राफ़िक्स ऑब्जेक्ट को निकालना सीखें। अपने PDF हेरफेर कार्यों को सरल बनाएँ। | +| [C# में खाली PDF डिक्शनरी बनाएं – पूर्ण Aspose.Pdf गाइड](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | C# में Aspose.PDF का उपयोग करके खाली PDF डिक्शनरी बनाने की पूरी गाइड। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/hindi/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/hindi/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..6d99ecac01 --- /dev/null +++ b/pdf/hindi/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: Aspose.Pdf का उपयोग करके C# में खाली PDF डिक्शनरी बनाएं। PDF हेरफेर के + लिए ExtGState डिक्शनरी में ग्राफ़िक्स स्टेट जोड़ने के चरण‑दर‑चरण सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: hi +lastmod: 2026-07-26 +og_description: Aspose.Pdf for C# का उपयोग करके खाली PDF शब्दकोश बनाएं। अपने PDFs + में ग्राफ़िक्स स्टेट्स को संशोधित करने के लिए इस व्यावहारिक गाइड का पालन करें। +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: C# में खाली PDF डिक्शनरी बनाएं – पूर्ण Aspose.Pdf ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: C# में खाली PDF डिक्शनरी बनाएं – पूर्ण Aspose.Pdf गाइड +url: /hi/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में Empty PDF Dictionary बनाएं – Complete Aspose.Pdf Guide + +क्या आपने कभी सोचा है कि **खाली PDF डिक्शनरी** एंट्रीज़ कैसे बनाएं जब आप PDF की ग्राफ़िक्स स्टेट को ट्यून कर रहे हों? आप अकेले नहीं हैं—कई डेवलपर्स को प्रोग्रामेटिकली opacity या blend modes को एडजस्ट करने की कोशिश करते समय यही समस्या आती है। इस ट्यूटोरियल में हम Aspose.Pdf for C# का उपयोग करके एक ठोस समाधान दिखाएंगे, जिसमें हम मौजूदा PDF के *ExtGState* डिक्शनरी में एक नया ग्राफ़िक्स स्टेट इन्जेक्ट करेंगे। + +हम सब कुछ कवर करेंगे: PDF लोड करना, उसके रिसोर्स डिक्शनरी तक पहुंचना, एक नया **CosPdfDictionary** बनाना, और अंत में बदलावों को सेव करना। अंत तक आपके पास किसी भी *PDF ग्राफ़िक्स स्टेट* ट्यूनिंग के लिए एक पुन: उपयोग योग्य पैटर्न होगा। + +--- + +## आप क्या सीखेंगे + +- Aspose.Pdf के लो‑लेवल API से **खाली PDF डिक्शनरी** ऑब्जेक्ट्स कैसे बनाएं। +- **ExtGState डिक्शनरी** की भूमिका, जो stroke/fill opacity और blend modes को नियंत्रित करती है। +- C# PDF मैनिपुलेशन के व्यावहारिक टिप्स, जिसमें डिक्शनरी के न होने पर एज़‑केस हैंडलिंग शामिल है। +- एक पूर्ण, रन‑एबल कोड सैंपल जिसे आप अपने प्रोजेक्ट में कॉपी‑पेस्ट कर सकते हैं। + +### पूर्वापेक्षाएँ + +- .NET 6.0 या बाद का (कोड .NET Framework 4.6+ के साथ भी काम करता है)। +- **Aspose.Pdf for .NET** की लाइसेंस्ड कॉपी (ट्रायल संस्करण टेस्टिंग के लिए पर्याप्त है)। +- C# और PDF अवधारणाओं जैसे रिसोर्सेज़ और ग्राफ़िक्स स्टेट्स की बेसिक समझ। + +यदि ये चीज़ें अपरिचित लग रही हों, तो घबराएँ नहीं—आप NuGet (`Install-Package Aspose.Pdf`) से Aspose.Pdf इंस्टॉल कर सकते हैं और बाकी सब सिर्फ साधारण C# है। + +--- + +## चरण 1 – PDF डॉक्यूमेंट लोड करें + +सबसे पहले, आपको एक `Document` ऑब्जेक्ट चाहिए जो उस फ़ाइल का प्रतिनिधित्व करता है जिसे आप एडिट करना चाहते हैं। इसे `using` ब्लॉक में रैप करने से उचित डिस्पोज़ल सुनिश्चित होता है। + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*क्यों महत्वपूर्ण है*: फ़ाइल खोलने से आपको अंदरूनी COS (Canonical Object Structure) ऑब्जेक्ट्स तक पहुंच मिलती है, जहाँ **CosPdfDictionary** स्थित होता है। डॉक्यूमेंट ऑब्जेक्ट के बिना आप उन रिसोर्स डिक्शनरीज़ तक नहीं पहुंच सकते जो **ExtGState** एंट्रीज़ रखती हैं। + +--- + +## चरण 2 – पहले पेज की रिसोर्स डिक्शनरी तक पहुंचें + +PDF पेज अपने रिसोर्सेज़ (फ़ॉन्ट्स, इमेजेज़, ग्राफ़िक्स स्टेट्स आदि) को एक समर्पित डिक्शनरी में स्टोर करता है। हम सरलता के लिए पहला पेज लेंगे, लेकिन यही लॉजिक किसी भी पेज इंडेक्स पर लागू हो सकता है। + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*प्रो टिप*: यदि आपके PDF में कई पेज हैं जिनके रिसोर्स सेट अलग हैं, तो इस ब्लॉक को प्रत्येक पेज के लिए दोहराएँ जिसे आप मॉडिफ़ाई करना चाहते हैं। `DictionaryEditor` क्लास एक सुविधाजनक रैपर है जो COS डिक्शनरी को .NET `Dictionary` की तरह ट्रीट करता है। + +--- + +## चरण 3 – ExtGState डिक्शनरी को रिट्रीव या इनिशियलाइज़ करें + +**ExtGState डिक्शनरी** नामित ग्राफ़िक्स स्टेट ऑब्जेक्ट्स (`GS0`, `GS1`, …) रखती है। कुछ PDFs में यह पहले से मौजूद होती है; कुछ में नहीं। हम इसे सुरक्षित रूप से फ़ेच करेंगे, और यदि आवश्यक हो तो एक नई खाली डिक्शनरी बनाएंगे। + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*क्यों कर रहे हैं*: एक नॉन‑एक्ज़िस्टेंट **ExtGState डिक्शनरी** में ग्राफ़िक्स स्टेट जोड़ने की कोशिश करने से एक्सेप्शन फेंका जाएगा। यह डिफेंसिव चेक कोड को किसी भी इनपुट PDF के लिए मजबूत बनाता है। + +--- + +## चरण 4 – CosPdfDictionary के साथ नया ग्राफ़िक्स स्टेट बनाएं + +अब ट्यूटोरियल का मुख्य भाग: **खाली PDF डिक्शनरी** बनाना जो एक कस्टम ग्राफ़िक्स स्टेट को परिभाषित करे। हम stroke opacity (`CA`), fill opacity (`ca`), और blend mode (`BM`) सेट करेंगे। आप बाद में और एंट्रीज़ जोड़ सकते हैं—यह सिर्फ एक शुरुआती सेट है। + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*व्याख्या*: +- `CA` और `ca` मानक PDF कीज़ हैं जो क्रमशः stroke और fill opacity को नियंत्रित करती हैं। +- `BM` blend mode चुनता है; “Normal” डिफ़ॉल्ट है लेकिन आप “Multiply”, “Screen” आदि का उपयोग कर सकते हैं, आपके डिज़ाइन की जरूरतों के अनुसार। +- `CosPdfDictionary.CreateEmptyDictionary` का उपयोग करके हम **खाली PDF डिक्शनरी** ऑब्जेक्ट बनाते हैं, जिन्हें बाद में key/value पेयर्स से भरते हैं। + +--- + +## चरण 5 – नया ग्राफ़िक्स स्टेट ExtGState में इन्सर्ट करें + +ग्राफ़िक्स स्टेट तैयार होने के बाद, हम इसे **ExtGState डिक्शनरी** में एक यूनिक नाम (जैसे `GS0`) के तहत जोड़ते हैं। यदि आप कई स्टेट्स जोड़ने वाले हैं, तो बस सफ़िक्स को इन्क्रीमेंट करें। + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*टिप*: जोड़ने से पहले आप चेक कर सकते हैं कि `GS0` पहले से मौजूद है या नहीं, ताकि ओवरराइट न हो। एक सरल `if (!extGState.ContainsKey("GS0"))` गार्ड इस काम को कर देता है। + +--- + +## चरण 6 – मॉडिफ़ाइड PDF सेव करें + +सभी बदलाव मेमोरी में रहते हैं जब तक आप उन्हें persist नहीं करते। अपने वर्कफ़्लो के अनुसार एक उपयुक्त आउटपुट पाथ चुनें। + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*परिणाम*: `output.pdf` को किसी भी PDF व्यूअर में खोलें, फिर पेज रिसोर्सेज़ (जैसे PDF inspector टूल से) देखें। आपको **ExtGState** के तहत `GS0` नाम की नई एंट्री दिखेगी जिसमें हमने परिभाषित पैरामीटर्स होंगे। + +--- + +## पूर्ण कार्यशील उदाहरण + +सब कुछ एक साथ मिलाकर, यहाँ पूरा, कॉपी‑एंड‑पेस्ट‑रेडी प्रोग्राम है: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**अपेक्षित आउटपुट**: `output.pdf` मूल फ़ाइल जैसा ही रेंडर होगा, लेकिन कोई भी कंटेंट जो बाद में `GS0` को रेफ़र करेगा (जैसे कंटेंट स्ट्रीम में `gs` ऑपरेटर) वह परिभाषित opacity और blend mode अपनाएगा। यदि आपके पास अभी तक ऐसा रेफ़रेंस नहीं है, तो आप इसे मैन्युअली या Aspose की हाई‑लेवल API से जोड़ सकते हैं। + +--- + +## अक्सर पूछे जाने वाले प्रश्न और एज़ केस + +| प्रश्न | उत्तर | +|----------|--------| +| *यदि PDF में पहले से ही `GS0` नाम का ExtGState एंट्री मौजूद है तो क्या करें?* | जोड़ने से पहले `extGState.ContainsKey("GS0")` चेक करें। यदि मौजूद है, तो या तो जानबूझकर ओवरराइट करें (`extGState["GS0"] = newGraphicsState`) या नया नाम जैसे `GS1` चुनें। | +| *क्या मैं लाइन विड्थ (`LW`) या डैश पैटर्न (`D`) जैसे और पैरामीटर्स जोड़ सकता हूँ?* | बिल्कुल। बस `parameters` एरे में अतिरिक्त `KeyValuePair` एंट्रीज़ जोड़ दें। | +| *क्या यह एप्रोच एन्क्रिप्टेड PDFs के साथ काम करता है?* | हाँ, बशर्ते आप `Document` बनाते समय सही पासवर्ड प्रदान करें (`new Document(path, password)`)। | +| *क्या मुझे डॉक्यूमेंट को मैन्युअली क्लोज़ करना पड़ेगा?* | `using` स्टेटमेंट डिस्पोज़ल का ख्याल रखता है, जो किसी भी पेंडिंग बदलाव को भी फ्लश कर देता है। | +| *यह हाई‑लेवल `Graphics` क्लास से कैसे अलग है?* | हाई‑लेवल API डिक्शनरीज़ को एब्स्ट्रैक्ट कर देती है, जो साधारण टास्क के लिए बढ़िया है। लेकिन जब आपको ग्राफ़िक्स स्टेट्स पर फाइन‑ग्रेन कंट्रोल चाहिए—जैसे कस्टम blend modes—तो आपको लो‑लेवल **CosPdfDictionary** के साथ काम करना पड़ता है, यानी सीधे **खाली PDF डिक्शनरी** ऑब्जेक्ट बनाना। | + +--- + +## निष्कर्ष + +हमने अभी दिखाया कि कैसे Aspose.Pdf के साथ **खाली PDF डिक्शनरी** ऑब्जेक्ट्स बनाकर एक कस्टम ग्राफ़िक्स स्टेट को **ExtGState डिक्शनरी** में इन्जेक्ट करें और संशोधित फ़ाइल को सेव करें—सब कुछ साफ़, idiomatic C# में। यह पैटर्न आपको opacity, blend modes, और PDF स्पेसिफ़िकेशन द्वारा परिभाषित किसी भी अन्य ग्राफ़िक्स‑स्टेट पैरामीटर पर सटीक नियंत्रण देता है। + +अब आप आगे कर सकते हैं: + +- `gs` ऑपरेटर का उपयोग करके नई ग्राफ़िक्स स्टेट को मौजूदा पेज कंटेंट पर लागू करें। +- ब्रांडिंग या वॉटरमार्किंग के लिए पुन: उपयोग योग्य ग्राफ़िक्स स्टेट्स की लाइब्रेरी बनाएं। +- + +## आगे क्या सीखें? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर कर सकें। + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/hongkong/net/digital-signatures/_index.md b/pdf/hongkong/net/digital-signatures/_index.md index e82f0d6787..7ad506a58d 100644 --- a/pdf/hongkong/net/digital-signatures/_index.md +++ b/pdf/hongkong/net/digital-signatures/_index.md @@ -59,6 +59,9 @@ Aspose.PDF Net 程式碼教學 ### [使用 Aspose 驗證 PDF 簽章並將 PDF 轉換為 HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) 了解如何使用 Aspose 驗證 PDF 簽章,同時將 PDF 轉換為 HTML 以便於網頁顯示。 +### [使用 Aspose.PDF 驗證 PDF 簽章並列出 PDF 簽章 – 完整指南](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +了解如何使用 Aspose.PDF 驗證 PDF 簽章並列出所有簽章,提供完整步驟與範例程式碼。 + ## 其他資源 - [Aspose.PDF 用於網頁文檔](https://docs.aspose.com/pdf/net/) diff --git a/pdf/hongkong/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/hongkong/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..e95873c365 --- /dev/null +++ b/pdf/hongkong/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-07-26 +description: 使用 Aspose.PDF 於 C# 驗證 PDF 簽章並列出 PDF 簽章。逐步程式碼、常見陷阱與安全文件處理的最佳實踐。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: zh-hant +lastmod: 2026-07-26 +og_description: 使用 Aspose.PDF 驗證 PDF 簽名並列出 PDF 簽名。遵循此實用指南,以在 C# 中保護 PDF。 +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: 驗證 PDF 簽名與列出 PDF 簽名 – Aspose.PDF 使用說明 +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: 使用 Aspose.PDF 驗證 PDF 簽名並列出 PDF 簽名 – 完整指南 +url: /zh-hant/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.PDF 驗證 PDF 簽章與列出 PDF 簽章 – 完整指南 + +有沒有想過如何在 .NET 應用程式中 **validate PDF signature** 而不至於抓狂?你並不是唯一有此疑問的人。無論你是在建構 e‑sign 平台,或只是需要確保收到的合約未被竄改,能夠 **list PDF signatures** 並逐一驗證是必備的技能。 + +在本教學中,我們將逐步示範一個完整可執行的範例,載入已簽署的 PDF,列舉所有內嵌的簽章,檢查是否有任何簽章被破壞,並將清晰的結果輸出至主控台。沒有模糊的說明——只有可直接 copy‑paste 的程式碼,以及每一步背後的「原因」說明。 + +## 前置條件 + +- **Aspose.PDF for .NET** 版本 25.3 或更新(`IsCompromised` 屬性於 25.3 版首次出現)。 +- 一個 .NET 開發環境(Visual Studio 2022、Rider,或 `dotnet` CLI)。 +- 一個可用於測試的已簽署 PDF 檔案(可使用 Adobe Acrobat 或任何 e‑signature 工具建立)。 + +如果缺少上述任一項,請先安裝 NuGet 套件: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** 目標設定為 .NET 6 或更新版本,以獲得最佳效能與長期支援。 + +## 步驟 1:載入 PDF 文件 + +首先要做的事就是開啟 PDF 檔案。Aspose.PDF 的 `Document` 類別負責從解析到渲染的所有工作。 + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Why this matters:* 載入檔案會在記憶體中建立表示,讓你在不再次存取檔案系統的情況下查詢簽章。它同時會提前驗證 PDF 結構,若檔案損毀會立即拋出例外。 + +## 步驟 2:**List PDF Signatures** – 列舉所有內嵌簽章 + +已簽署的 PDF 可能包含多個簽章(例如多頁合約,每一方在不同頁面簽署)。Aspose.PDF 透過 `Signatures` 集合將它們公開。 + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*What you’re seeing:* 迴圈會列印 **list PDF signatures** 的詳細資訊,如簽署者姓名、原因、位置與時間戳記。這對於稽核日誌或 UI 顯示相當便利。 + +## 步驟 3:**Validate PDF Signature** – 檢查是否被破壞 + +現在進入安全關鍵的部分:確認所有簽章在簽署後未被更改。自 25.3 版起,Aspose.PDF 提供 `PdfSignatureValidator.IsCompromised` 標誌。 + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Why you should use `IsCompromised`*: 傳統驗證僅檢查加密鏈(憑證有效性、撤銷等)。`IsCompromised` 透過偵測簽署後的任何文件變更,提供額外層級——這正是當你 **validate PDF signature** 以防篡改時所需要的。 + +## 步驟 4:處理驗證結果 + +根據結果,你可能需要採取不同的行動。以下是一個可供調整的快速範例: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Edge case note:* 若 PDF 包含 **certified** 簽章(第一個鎖定文件的簽章),之後的任何修改都可能使整個檔案失效,即使後續簽章看似正常。任何來自 `IsCompromised` 為 `true` 的情況,都應視為警訊。 + +## 完整範例 + +將所有步驟整合起來,以下是一個可直接編譯執行的單一自包含程式: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Expected output**(假設有一個正常簽章與一個被竄改的簽章): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## 常見陷阱與避免方法 + +| 問題 | 發生原因 | 解決方案 | +|---------|----------------|-----| +| **Missing Aspose.PDF version** | `IsCompromised` 於 25.3 版首次推出。較舊的套件雖能編譯,卻會拋出 `MissingMethodException`。 | 確保你的 NuGet 參考版本為 `>= 25.3`。 | +| **Null `SignatureInfo`** | 某些 PDF 內有空的簽章槽位,仍會出現在集合中。 | 在驗證前以 `if (signatureInfo != null)` 進行防護。 | +| **Performance hit on large PDFs** | 驗證每個簽章都會每次讀取整個檔案。 | 若只需布林摘要,可快取 `PdfSignatureValidator` 或批次處理簽章。 | +| **Certificate revocation not checked** | `IsCompromised` 只告知文件是否變更,未檢查憑證狀態。 | 結合 `IsCompromised`,使用 `PdfSignatureValidator.Validate()` 以完成完整的 PKI 檢查。 | + +## 擴充解決方案 + +如果需要在 UI 中 **list PDF signatures**,只要將 `SignatureInfo` 物件輸入資料格即可。想將驗證結果儲存至資料庫嗎?可將布林值 `isCompromised` 與簽署者姓名、時間戳記一起序列化。 + +其他相關主題你可以進一步探索: + +- **Validate PDF signature against a trusted root CA**(使用 `validator.Validate()`)。 +- **Extract embedded certificate details**(`validator.Certificate`)。 +- **Create digital signatures** with Aspose.PDF(`PdfSignatureBuilder`)。 + +## 結論 + +現在你已掌握使用 Aspose.PDF for .NET 進行 **validate PDF signature** 與 **list PDF signatures** 的實務、端對端方法。程式碼清楚示範如何載入文件、列舉每個簽章、檢查 `IsCompromised` 標誌,並依結果採取行動——全部以簡潔、適合主控台的格式呈現。 + +試著使用自己的已簽署 PDF,實驗多重簽章,並將此邏輯整合至更大的文件處理流程中。PDF 的安全性取決於你執行的驗證程度,務必保持檢查嚴謹、日誌完整。 + +有任何問題或想分享有趣的使用案例嗎?在下方留言或於 GitHub 上私訊我。祝開發愉快! + +![驗證 PDF 簽章](/images/validate-pdf-signature.png "使用 Aspose.PDF 的 C# 主控台應用程式驗證 PDF 簽章的螢幕截圖") + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,並以此為基礎。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通其他 API 功能,並在專案中探索替代實作方式。 + +- [如何驗證 PDF – 使用 Aspose 驗證 PDF 簽章](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [如何使用 Aspose.PDF .NET 提取 PDF 簽章資訊:逐步指南](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [如何使用 Aspose.PDF for .NET 從 PDF 簽章欄位提取圖像:逐步指南](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/hongkong/net/programming-with-operators/_index.md b/pdf/hongkong/net/programming-with-operators/_index.md index 855a4ca86a..ac5f99cb0c 100644 --- a/pdf/hongkong/net/programming-with-operators/_index.md +++ b/pdf/hongkong/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Aspose.PDF for .NET 的「使用運算子進行程式設計」教學課程將引 | [在頁面上繪製 XForm](./draw-xform-on-page/) |透過本全面的逐步指南了解如何使用 Aspose.PDF for .NET 在 PDF 中繪製 XForms。 | | [PDF 運算符](./pdf-operators/) |使用 Aspose.PDF for .NET 的 PDF 運算子的逐步指南。將圖像新增至 PDF 頁面並指定其位置。 | | [刪除 PDF 檔案中的圖形對象](./remove-graphics-objects/) |在本逐步指南中了解如何使用 Aspose.PDF for .NET 從 PDF 檔案中刪除圖形物件。簡化您的 PDF 操作任務。 | +| [在 C# 中建立空 PDF 字典 – 完整 Aspose.Pdf 指南](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) |本完整指南說明如何在 C# 使用 Aspose.PDF 建立空的 PDF 字典,並設定其屬性。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/hongkong/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/hongkong/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..3bea6de318 --- /dev/null +++ b/pdf/hongkong/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-07-26 +description: 使用 Aspose.Pdf 在 C# 中建立空的 PDF 字典。一步一步學習如何將圖形狀態加入 ExtGState 字典,以進行 PDF + 操作。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: zh-hant +lastmod: 2026-07-26 +og_description: 使用 Aspose.Pdf for C# 建立空的 PDF 字典。請參考此實作指南以修改 PDF 中的圖形狀態。 +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: 在 C# 中建立空的 PDF 字典 – 完整 Aspose.Pdf 教程 +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: 在 C# 中建立空的 PDF 字典 – 完整 Aspose.Pdf 指南 +url: /zh-hant/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立空的 PDF 字典 – 完整 Aspose.Pdf 指南 + +有沒有想過在調整 PDF 的圖形狀態時,如何 **create empty PDF dictionary** 條目?你並不孤單——許多開發者在程式化調整不透明度或混合模式時會遇到這個問題。在本教學中,我們將使用 Aspose.Pdf for C# 逐步說明具體解決方案,展示如何將新的圖形狀態注入現有 PDF 的 *ExtGState* 字典。 + +我們會涵蓋所有必備內容:載入 PDF、存取其資源字典、建立全新的 **CosPdfDictionary**,最後將變更寫回。完成後,你將擁有一套可重複使用的模式,適用於任何 *PDF graphics state* 的調整需求。 + +## 你將學到什麼 + +- 如何使用 Aspose.Pdf 的低階 API **create empty PDF dictionary** 物件。 +- **ExtGState dictionary** 在控制描邊/填充不透明度與混合模式中的角色。 +- C# PDF 操作的實用技巧,包括字典缺失時的邊緣案例處理。 +- 完整、可執行的程式碼範例,可直接 copy‑paste 到你的專案中。 + +### 前置條件 + +- .NET 6.0 或更新版本(此程式碼亦相容 .NET Framework 4.6+)。 +- 取得 **Aspose.Pdf for .NET** 的授權版(免費試用版可用於測試)。 +- 具備 C# 基礎以及 PDF 概念(如資源與圖形狀態)的基本認識。 + +如果上述任一項聽起來陌生,別慌——你可以透過 NuGet 安裝 Aspose.Pdf(`Install-Package Aspose.Pdf`),其餘只要使用純粹的 C# 即可。 + +## 步驟 1 – 載入 PDF 文件 + +首先,你需要一個代表欲編輯檔案的 `Document` 物件。將其包在 `using` 區塊中可確保正確釋放資源。 + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*為何重要*:開啟檔案後,你即可存取內部的 COS(Canonical Object Structure)物件,**CosPdfDictionary** 就位於其中。若沒有 Document 物件,就無法取得包含 **ExtGState** 條目的資源字典。 + +## 步驟 2 – 取得第一頁的資源字典 + +PDF 頁面會將其資源(字型、影像、圖形狀態等)儲存在專屬的字典中。我們為簡化起見只取第一頁,但相同的邏輯可套用於任何頁碼。 + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*小技巧*:若 PDF 有多頁且資源集合不同,請對每個需要修改的頁面重複此區塊。`DictionaryEditor` 類別是一個便利的封裝,讓你可以將 COS 字典當作 .NET 的 `Dictionary` 來使用。 + +## 步驟 3 – 取得或初始化 ExtGState 字典 + +**ExtGState dictionary** 保存具名的圖形狀態物件(`GS0`、`GS1`…)。有些 PDF 已經包含此字典;有些則沒有。我們將安全地取得它,若不存在則建立一個全新的空字典。 + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*為什麼要這樣做*:若嘗試將圖形狀態加入不存在的 **ExtGState dictionary**,會拋出例外。此防禦性檢查讓程式對任何輸入的 PDF 都更穩健。 + +## 步驟 4 – 使用 CosPdfDictionary 建立新圖形狀態 + +現在進入本教學的核心:**creating an empty PDF dictionary**,用以定義自訂的圖形狀態。我們將設定描邊不透明度(`CA`)、填充不透明度(`ca`)以及混合模式(`BM`)。之後你可以再加入更多條目——這只是入門範例。 + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*說明*: +- `CA` 與 `ca` 為標準 PDF 鍵,分別控制描邊與填充的不透明度。 +- `BM` 用於選擇混合模式;預設為 “Normal”,但你也可以根據設計需求使用 “Multiply”、 “Screen”等。 +- 透過 `CosPdfDictionary.CreateEmptyDictionary`,我們 **create empty PDF dictionary** 物件,之後再以鍵值對填入內容。 + +## 步驟 5 – 將新圖形狀態插入 ExtGState + +圖形狀態準備好後,我們只需將它以唯一名稱(例如 `GS0`)加入 **ExtGState dictionary**。若要加入多個狀態,只需遞增後綴即可。 + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*提示*:加入前,建議先檢查 `GS0` 是否已存在,以免覆寫。使用 `if (!extGState.ContainsKey("GS0"))` 的簡易判斷即可。 + +## 步驟 6 – 儲存已修改的 PDF + +所有變更皆在記憶體中,直到你將其寫入檔案。請選擇符合工作流程的輸出路徑。 + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*結果*:在任何 PDF 檢視器中開啟 `output.pdf`,再檢查頁面資源(例如使用 PDF 檢測工具)。你會看到 **ExtGState** 下新增名為 `GS0` 的條目,內含我們定義的參數。 + +## 完整可執行範例 + +將上述所有步驟整合起來,以下是完整、可直接 copy‑and‑paste 的程式: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**預期結果**:`output.pdf` 的呈現將與原始檔案完全相同,但任何之後引用 `GS0`(例如在內容串流中使用 `gs` 運算子)的內容,將套用我們定義的不透明度與混合模式。若尚未有此類引用,你可以手動或透過 Aspose 的高階 API 加入。 + +## 常見問題與邊緣案例 + +| Question | Answer | +|----------|--------| +| *如果 PDF 已經有名為 `GS0` 的 `ExtGState` 條目,該怎麼辦?* | 在加入前先檢查 `extGState.ContainsKey("GS0")`。若已存在,可刻意覆寫(`extGState["GS0"] = newGraphicsState`),或改用新名稱如 `GS1`。 | +| *我可以加入更多參數,例如線寬 (`LW`) 或虛線模式 (`D`) 嗎?* | 當然可以。只要在 `parameters` 陣列中再加入額外的 `KeyValuePair` 條目即可。 | +| *此方法能支援加密的 PDF 嗎?* | 可以,只要在建立 `Document` 時提供正確的密碼(`new Document(path, password)`)。 | +| *我需要手動關閉文件嗎?* | `using` 陳述式會自動處理釋放,亦會將任何未寫入的變更刷新。 | +| *使用高階的 `Graphics` 類別與此有何不同?* | 高階 API 會將底層字典抽象化,適合簡單任務。但若需對圖形狀態(例如自訂混合模式)進行精細控制,必須使用低階的 **CosPdfDictionary**,也就是直接操作 **create empty PDF dictionary** 物件。 | + +## 結論 + +我們剛剛示範了如何使用 Aspose.Pdf **create empty PDF dictionary** 物件,將自訂圖形狀態注入 **ExtGState dictionary**,並儲存修改後的檔案——全部以乾淨、符合慣例的 C# 完成。此模式讓你能精確控制不透明度、混合模式以及 PDF 規範中定義的其他圖形狀態參數。 + +從此你可以: + +- 使用 `gs` 運算子將新圖形狀態套用至現有頁面內容。 +- 建立可重複使用的圖形狀態庫,以供品牌或浮水印使用。 +- + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,建立在本教學示範的技巧之上。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索其他實作方式。 + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/hungarian/net/digital-signatures/_index.md b/pdf/hungarian/net/digital-signatures/_index.md index 7f9a258004..5a8bbf1c69 100644 --- a/pdf/hungarian/net/digital-signatures/_index.md +++ b/pdf/hungarian/net/digital-signatures/_index.md @@ -59,6 +59,9 @@ Ismerje meg, hogyan tölthet be PDF-et C#-ban, konvertálhatja PDF/X‑4-re, és ### [PDF aláírás ellenőrzése Aspose-szal – PDF konvertálása HTML-re](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Ismerje meg, hogyan ellenőrizheti a PDF aláírását és konvertálhatja a dokumentumot HTML formátumba az Aspose.PDF for .NET használatával. +### [PDF aláírás ellenőrzése és PDF aláírások listázása az Aspose.PDF segítségével – Teljes útmutató](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Ismerje meg, hogyan ellenőrizheti a PDF aláírásokat és listázhatja az összes aláírást az Aspose.PDF segítségével, lépésről lépésre útmutató. + ## További források - [Aspose.PDF a hálózati dokumentációhoz](https://docs.aspose.com/pdf/net/) diff --git a/pdf/hungarian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/hungarian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..7ee1677261 --- /dev/null +++ b/pdf/hungarian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-07-26 +description: PDF aláírás ellenőrzése és PDF aláírások listázása az Aspose.PDF használatával + C#-ban. Lépésről lépésre kód, buktatók és legjobb gyakorlatok a biztonságos dokumentumkezeléshez. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: hu +lastmod: 2026-07-26 +og_description: Ellenőrizze a PDF-aláírást és listázza a PDF-aláírásokat az Aspose.PDF + segítségével. Kövesse ezt a gyakorlati útmutatót a PDF-ek C#-ban történő biztonságos + kezeléséhez. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: PDF-aláírás ellenőrzése és PDF-aláírások listázása – Aspose.PDF útmutató +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: PDF-aláírás ellenőrzése és PDF-aláírások listázása az Aspose.PDF segítségével + – Teljes útmutató +url: /hu/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF-aláírás ellenőrzése és PDF-aláírások listázása az Aspose.PDF‑vel – Teljes útmutató + +Gondolkodtál már azon, hogyan **validate PDF signature**‑t végezz egy .NET alkalmazásban anélkül, hogy a hajadba ragadnál? Nem vagy egyedül. Akár e‑sign platformot építesz, akár csak biztosra akarsz menni, hogy a kapott szerződés nem lett megváltoztatva, a **list PDF signatures** és az egyes aláírások ellenőrzése alapvető képesség. + +Ebben a tutorialban egy teljesen futtatható példán keresztül vezetünk végig: betöltünk egy aláírt PDF‑et, felsoroljuk az összes beágyazott aláírást, ellenőrizzük, hogy valamelyik kompromittálódott‑e, és egyértelmű eredményt írunk ki a konzolra. Nincs homályos hivatkozás – csak a másolható‑beilleszthető kód, plusz a „miért” minden lépés mögött. + +## Prerequisites + +Mielőtt belevágnánk, győződj meg róla, hogy rendelkezel a következőkkel: + +- **Aspose.PDF for .NET** 25.3 vagy újabb verzióval (az `IsCompromised` tulajdonság 25.3‑tól elérhető). +- .NET fejlesztői környezettel (Visual Studio 2022, Rider vagy a `dotnet` CLI). +- Egy aláírt PDF fájllal, amivel tesztelhetsz (létrehozhatod Adobe Acrobat‑tal vagy bármely e‑signature eszközzel). + +Ha bármelyik hiányzik, először telepítsd a NuGet csomagot: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** Célozd meg a .NET 6 vagy újabb verziót a legjobb teljesítmény és hosszú távú támogatás érdekében. + +## Step 1: Load the PDF Document + +Az első dolog, amit meg kell tenned, hogy megnyitod a PDF fájlt. Az Aspose.PDF `Document` osztálya mindent kezel a beolvasástól a renderelésig. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Miért fontos:* A fájl betöltése egy memóriában lévő reprezentációt hoz létre, amely lehetővé teszi az aláírások lekérdezését anélkül, hogy újra a fájlrendszert érintenéd. Emellett már a kezdetekkor ellenőrzi a PDF struktúráját, így ha a fájl sérült, azonnal kivételt kapsz. + +## Step 2: **List PDF Signatures** – Enumerate All Embedded Signatures + +Egy aláírt PDF több aláírást is tartalmazhat (gondolj egy többoldalas szerződésre, ahol minden fél másik oldalt ír alá). Az Aspose.PDF a `Signatures` gyűjteményen keresztül teszi elérhetővé őket. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Mit látsz:* A ciklus kiírja a **list PDF signatures** részleteit, például a aláíró nevét, az okot, a helyet és az időbélyeget. Ez hasznos auditnaplókhoz vagy UI megjelenítésekhez. + +## Step 3: **Validate PDF Signature** – Check for Compromise + +Most jön a biztonságkritikus rész: annak megerősítése, hogy egyik aláírás sem változott meg az aláírás után. A 25.3‑as verziótól az Aspose.PDF biztosítja a `PdfSignatureValidator.IsCompromised` jelzőt. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Miért használd az `IsCompromised`‑t*: A hagyományos ellenőrzés csak a kriptográfiai láncot (tanúsítvány érvényesség, visszavonás stb.) vizsgálja. Az `IsCompromised` egy extra réteget ad hozzá, amely felismeri a dokumentum aláírás utáni módosításait – pontosan azt, amire szükséged van, amikor **validate PDF signature**‑t végzel a manipuláció ellen. + +## Step 4: Handling Validation Outcomes + +Az eredménytől függően különböző műveleteket szeretnél végrehajtani. Íme egy gyors minta, amelyet testre szabhatsz: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Edge case megjegyzés:* Ha egy PDF **certified** aláírást tartalmaz (az első aláírás, amely lezárja a dokumentumot), egy későbbi módosítás érvénytelenítheti az egész fájlt, még akkor is, ha a későbbi aláírások rendben vannak. Mindig tekintsd a `true` értéket az `IsCompromised`‑ből piros zászlónak. + +## Full Working Example + +Mindent egy helyen, itt egy önálló program, amelyet lefordíthatsz és futtathatsz: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Várható kimenet** (feltételezve egy jó aláírást és egy manipuláltat): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Common Pitfalls & How to Avoid Them + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Missing Aspose.PDF version** | `IsCompromised` was introduced in 25.3. Older packages compile but throw `MissingMethodException`. | Ensure your NuGet reference is `>= 25.3`. | +| **Null `SignatureInfo`** | Some PDFs have empty signature slots that still appear in the collection. | Guard with `if (signatureInfo != null)` before validation. | +| **Performance hit on large PDFs** | Validating every signature reads the whole file each time. | Cache the `PdfSignatureValidator` or batch‑process signatures if you only need a boolean summary. | +| **Certificate revocation not checked** | `IsCompromised` only tells you about document changes, not certificate status. | Use `PdfSignatureValidator.Validate()` in addition to `IsCompromised` for full PKI checks. | + +## Extending the Solution + +Ha **list PDF signatures**‑t szeretnél megjeleníteni egy UI‑ban, egyszerűen add át a `SignatureInfo` objektumokat egy adatgridnek. Szeretnéd a validációs eredményeket adatbázisba menteni? Sorold be a boolean `isCompromised` értéket a aláíró nevével és időbélyegével együtt. + +Más kapcsolódó témák, amelyeket érdemes felfedezni: + +- **Validate PDF signature against a trusted root CA** (use `validator.Validate()`). +- **Extract embedded certificate details** (`validator.Certificate`). +- **Create digital signatures** with Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusion + +Most már kéznél van egy gyakorlati, vég‑től‑végig módszer a **validate PDF signature** és a **list PDF signatures** végrehajtására az Aspose.PDF for .NET segítségével. A kód pontosan megmutatja, hogyan tölts be egy dokumentumot, sorold fel az egyes aláírásokat, ellenőrizd az `IsCompromised` jelzőt, és reagálj az eredményre – mindezt egy tiszta, konzolbarát formátumban. + +Próbáld ki a saját aláírt PDF‑eidben, kísérletezz több aláírással, és integráld a logikát a nagyobb dokumentum‑feldolgozó csővezetékedbe. A biztonságos PDF‑ek csak annyira erősek, mint a végzett ellenőrzés, ezért tartsd szorosra a kontrollt és alaposra a naplózást. + +Van kérdésed vagy szeretnél egy menő felhasználási esetet megosztani? Hagyj kommentet lent vagy írj nekem a GitHub‑on. Boldog kódolást! + +![PDF-aláírás ellenőrzése](/images/validate-pdf-signature.png "Képernyőkép egy C# konzolalkalmazásról, amely PDF-aláírást ellenőriz az Aspose.PDF‑vel") + + +## What Should You Learn Next? + + +Az alábbi tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden erőforrás komplett, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsen elsajátítani további API‑funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [How to Verify PDF – Validate PDF Signature with Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [How to Extract PDF Signature Information Using Aspose.PDF .NET: A Step-by-Step Guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [How to Extract Images from PDF Signature Fields using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/hungarian/net/programming-with-operators/_index.md b/pdf/hungarian/net/programming-with-operators/_index.md index 27868b3575..0b7727f25b 100644 --- a/pdf/hungarian/net/programming-with-operators/_index.md +++ b/pdf/hungarian/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ Az Aspose.PDF for .NET „Operátorokkal való programozás” című oktatóany | --- | --- | | [XForm rajzolása az oldalon](./draw-xform-on-page/) | Tanuld meg, hogyan rajzolhatsz XForm-okat PDF-ben az Aspose.PDF for .NET segítségével ezzel az átfogó, lépésről lépésre szóló útmutatóval. | | [PDF-operátorok](./pdf-operators/) | Lépésről lépésre útmutató a PDF operátorok használatához az Aspose.PDF for .NET fájlban. Kép hozzáadása egy PDF oldalhoz és a pozíciójának megadása. | -| [Grafikus objektumok eltávolítása PDF fájlból](./remove-graphics-objects/) Tanulja meg, hogyan távolíthat el grafikus objektumokat egy PDF fájlból az Aspose.PDF for .NET segítségével ebben a lépésenkénti útmutatóban. Egyszerűsítse PDF-szerkesztési feladatait. | +| [Grafikus objektumok eltávolítása PDF fájlból](./remove-graphics-objects/) | Tanulja meg, hogyan távolíthat el grafikus objektumokat egy PDF fájlból az Aspose.PDF for .NET segítségével ebben a lépésenkénti útmutatóban. Egyszerűsítse PDF-szerkesztési feladatait. | +| [Üres PDF-szótár létrehozása C#-ban – Teljes Aspose.Pdf útmutató](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Tanulja meg, hogyan hozhat létre üres PDF-szótárat C#-ban az Aspose.PDF for .NET segítségével. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/hungarian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/hungarian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..79bccd8bbc --- /dev/null +++ b/pdf/hungarian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Üres PDF szótár létrehozása Aspose.Pdf segítségével C#-ban. Tanulja meg + lépésről lépésre, hogyan adjon hozzá grafikai állapotot az ExtGState szótárhoz a + PDF-manipulációhoz. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: hu +lastmod: 2026-07-26 +og_description: Üres PDF szótár létrehozása az Aspose.Pdf for C# használatával. Kövesd + ezt a gyakorlati útmutatót a PDF-ek grafikus állapotainak módosításához. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Üres PDF szótár létrehozása C#-ban – Teljes Aspose.Pdf útmutató +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Üres PDF szótár létrehozása C#‑ban – Teljes Aspose.Pdf útmutató +url: /hu/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Üres PDF szótár létrehozása C#‑ban – Teljes Aspose.Pdf útmutató + +Gondolkodtál már azon, hogyan **hozz létre üres PDF szótár** bejegyzéseket, amikor egy PDF grafikai állapotát módosítod? Nem vagy egyedül – sok fejlesztő ütközik ebbe a problémába, amikor programozottan szeretne átlátszóságot vagy keverési módokat beállítani. Ebben a bemutatóban egy konkrét megoldáson keresztül vezetünk végig az Aspose.Pdf for C# használatával, bemutatva, hogyan lehet egy új grafikai állapotot beilleszteni egy meglévő PDF *ExtGState* szótárába. + +Mindent lefedünk, amire szükséged lehet: PDF betöltése, erőforrás‑szótár elérése, friss **CosPdfDictionary** felépítése, és végül a változtatások mentése. A végére egy újrahasználható mintát kapsz bármilyen *PDF grafikai állapot* módosításhoz. + +--- + +## Mit fogsz megtanulni + +- Hogyan **hozz létre üres PDF szótár** objektumokat az Aspose.Pdf alacsony szintű API‑jával. +- Az **ExtGState szótár** szerepe a vonal‑/kitöltési átlátszóság és a keverési módok vezérlésében. +- Gyakorlati tippek C# PDF manipulációhoz, beleértve a szótár hiánya esetén felmerülő szélsőséges esetek kezelését. +- Egy teljes, futtatható kódminta, amelyet egyszerűen be tudsz másolni a projektedbe. + +### Előfeltételek + +- .NET 6.0 vagy újabb (a kód .NET Framework 4.6+‑al is működik). +- Egy licencelt példány a **Aspose.Pdf for .NET**‑ből (a ingyenes próba verzió teszteléshez elegendő). +- Alapvető ismeretek C#‑ról és a PDF koncepciókról, mint például az erőforrások és grafikai állapotok. + +Ha valamelyik ismeretlennek tűnik, ne aggódj – telepítheted az Aspose.Pdf‑t a NuGet‑en keresztül (`Install-Package Aspose.Pdf`), a többi pedig csak tiszta C#. + +--- + +## 1. lépés – PDF dokumentum betöltése + +Elsőként szükséged van egy `Document` objektumra, amely a szerkeszteni kívánt fájlt képviseli. Egy `using` blokkba helyezve biztosíthatod a megfelelő erőforrás‑felszabadítást. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Miért fontos*: A fájl megnyitása hozzáférést biztosít a belső COS (Canonical Object Structure) objektumokhoz, ahol a **CosPdfDictionary** található. Dokumentumobjektus nélkül nem érheted el az erőforrás‑szótárakat, amelyek a **ExtGState** bejegyzéseket tartalmazzák. + +--- + +## 2. lépés – Az első oldal erőforrás‑szótárának elérése + +A PDF oldalak az erőforrásaikat (betűkészletek, képek, grafikai állapotok stb.) egy dedikált szótárban tárolják. Egyszerűség kedvéért az első oldalt fogjuk használni, de ugyanaz a logika bármely oldal indexre alkalmazható. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Pro tipp*: Ha a PDF több oldalt tartalmaz különböző erőforrás‑készletekkel, ismételd meg ezt a blokkot minden módosítani kívánt oldalra. A `DictionaryEditor` osztály egy kényelmes burkoló, amely lehetővé teszi, hogy a COS szótárat úgy kezeld, mint egy .NET `Dictionary`‑et. + +--- + +## 3. lépés – Az ExtGState szótár lekérdezése vagy inicializálása + +Az **ExtGState szótár** névvel ellátott grafikai állapot‑objektumokat (`GS0`, `GS1`, …) tárolja. Egyes PDF‑ek már tartalmazzák; mások nem. Biztonságosan lekérjük, és ha szükséges, egy új üres szótárat hozunk létre. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Miért csináljuk*: Ha egy nem létező **ExtGState szótár**‑ba próbálunk grafikai állapotot hozzáadni, kivétel keletkezik. Ez a védelmi ellenőrzés a kódot robusztusabbá teszi bármilyen bemeneti PDF‑hez. + +--- + +## 4. lépés – Új grafikai állapot felépítése CosPdfDictionary‑val + +Most jön a bemutató középpontja: **üres PDF szótár** létrehozása, amely egy egyedi grafikai állapotot definiál. Beállítjuk a vonal‑átlátszóságot (`CA`), a kitöltési átlátszóságot (`ca`) és a keverési módot (`BM`). Később további bejegyzéseket is hozzáadhatsz – ez csak egy kezdőcsomag. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Magyarázat*: +- A `CA` és `ca` a PDF szabványos kulcsai, amelyek a vonal‑ és kitöltési átlátszóságot vezérlik. +- A `BM` a keverési módot választja; a „Normal” az alapértelmezett, de használhatsz „Multiply”, „Screen” stb. a tervezési igényeidnek megfelelően. +- A `CosPdfDictionary.CreateEmptyDictionary` használatával **üres PDF szótár** objektumokat hozunk létre, amelyeket később kulcs/érték párokkal töltünk fel. + +--- + +## 5. lépés – Az új grafikai állapot beillesztése az ExtGState‑be + +Miután a grafikai állapot készen áll, egyszerűen hozzáadjuk a **ExtGState szótárhoz** egy egyedi név alatt (pl. `GS0`). Ha több állapotot szeretnél hozzáadni, csak növeld a szuffixet. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tip*: Hozzáadás előtt érdemes ellenőrizni, hogy a `GS0` már létezik‑e, hogy elkerüld a felülírást. Egy gyors `if (!extGState.ContainsKey("GS0"))` feltétel megoldja a dolgot. + +--- + +## 6. lépés – Módosított PDF mentése + +Minden változtatás a memóriában marad, amíg nem mented őket. Válassz egy olyan kimeneti útvonalat, amely illik a munkafolyamatodhoz. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Eredmény*: Nyisd meg az `output.pdf`‑t bármely PDF‑olvasóval, majd ellenőrizd az oldal erőforrásait (pl. egy PDF‑inspektor eszközzel). Látni fogsz egy új bejegyzést az **ExtGState** alatt, amelynek neve `GS0` és a megadott paramétereket tartalmazza. + +--- + +## Teljes működő példa + +Mindent összegezve, itt a teljes, másolás‑beillesztés‑kész program: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Várt kimenet**: Az `output.pdf` pontosan úgy fog megjelenni, mint az eredeti, de minden olyan tartalom, amely később hivatkozik a `GS0`‑ra (például a `gs` operátorral egy tartalmi áramlathoz), az általunk definiált átlátszóságot és keverési módot fogja használni. Ha még nincs ilyen hivatkozás, manuálisan vagy az Aspose magasabb szintű API‑jaival hozzáadhatod. + +--- + +## Gyakran ismételt kérdések és szélsőséges esetek + +| Kérdés | Válasz | +|----------|--------| +| *Mi a teendő, ha a PDF már tartalmaz egy `ExtGState` bejegyzést `GS0` néven?* | Ellenőrizd a `extGState.ContainsKey("GS0")` feltételt a hozzáadás előtt. Ha létezik, vagy szándékosan felülírhatod (`extGState["GS0"] = newGraphicsState`), vagy választhatsz új nevet, például `GS1`. | +| *Hozzáadhatok további paramétereket, például vonalvastagságot (`LW`) vagy szaggatott mintát (`D`)?* | Természetesen. Egyszerűen bővítsd a `parameters` tömböt további `KeyValuePair` bejegyzésekkel. | +| *Kompatibilis ez a megközelítés titkosított PDF‑ekkel?* | Igen, amennyiben a `Document` konstruktorában megadod a helyes jelszót (`new Document(path, password)`). | +| *Kell-e manuálisan bezárni a dokumentumot?* | A `using` utasítás gondoskodik a felszabadításról, amely egyúttal kiüríti az esetleges függőben lévő változtatásokat is. | +| *Miben különbözik ez a magasabb szintű `Graphics` osztály használatától?* | A magasabb szintű API elrejti a háttérben lévő szótárakat, ami egyszerű feladatoknál előnyös. Amikor finomhangolt vezérlésre van szükség – például egyedi keverési módokra – a **CosPdfDictionary**‑val, vagyis **üres PDF szótár** objektumokkal kell dolgozni. | + +--- + +## Összegzés + +Most már tudod, hogyan **hozz létre üres PDF szótár** objektumokat az Aspose.Pdf‑vel, hogyan illessz be egy egyedi grafikai állapotot az **ExtGState szótárba**, és hogyan mentsd el a módosított fájlt – mindezt tiszta, idiomatikus C#‑ban. Ez a minta pontos kontrollt biztosít az átlátszóság, keverési módok és a PDF specifikáció által definiált egyéb grafikai‑állapot paraméterek felett. + +Innen tovább: + +- Alkalmazd az új grafikai állapotot a meglévő oldal tartalmára a `gs` operátor segítségével. +- Építs fel egy újrahasználható grafikai állapot‑könyvtárat márkázáshoz vagy vízjelzéshez. +- + +## Mit tanulj meg legközelebb? + + +Az alábbi oktatóanyagok szorosan kapcsolódnak a jelen útmutatóban bemutatott technikákhoz, és további API‑funkciók elsajátítását, valamint alternatív megvalósítási megközelítéseket mutatnak be a saját projektjeidben. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/indonesian/net/digital-signatures/_index.md b/pdf/indonesian/net/digital-signatures/_index.md index 9de5e0f7f7..5fc7c4fd2e 100644 --- a/pdf/indonesian/net/digital-signatures/_index.md +++ b/pdf/indonesian/net/digital-signatures/_index.md @@ -47,7 +47,6 @@ Pelajari cara memverifikasi tanda tangan digital dalam file PDF menggunakan Aspo ### [Verifikasi Tanda Tangan PDF di C# – Panduan Lengkap untuk Memvalidasi Tanda Tangan Digital PDF](./verify-pdf-signature-in-c-complete-guide-to-validate-digital/) Panduan langkah demi langkah untuk memverifikasi tanda tangan digital pada file PDF menggunakan C# dan Aspose.PDF. - ### [Kuasai Penandatanganan & Verifikasi PDF dengan Aspose.PDF .NET](./mastering-aspose-pdf-net-sign-verify-smart-card-certificates/) Tutorial kode untuk Aspose.PDF Net @@ -56,12 +55,16 @@ Pelajari cara memverifikasi tanda tangan digital dalam file PDF menggunakan Aspo ### [Cara Memverifikasi PDF – Validasi Tanda Tangan PDF dengan Aspose](./how-to-verify-pdf-validate-pdf-signature-with-aspose/) Panduan langkah demi langkah untuk memverifikasi dan memvalidasi tanda tangan PDF menggunakan Aspose. + ### [Muat Dokumen PDF C# – Konversi ke PDF/X‑4 & Daftar Tanda Tangan](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) Pelajari cara memuat dokumen PDF, mengonversinya ke format PDF/X‑4, dan menampilkan daftar tanda tangan menggunakan C# dan Aspose.PDF. ### [Validasi Tanda Tangan PDF dengan Aspose – Konversi PDF ke HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Pelajari cara memvalidasi tanda tangan PDF dan mengonversi PDF ke HTML menggunakan Aspose. +### [Validasi Tanda Tangan PDF dan Daftar Tanda Tangan PDF dengan Aspose.PDF – Panduan Lengkap](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Panduan langkah demi langkah untuk memvalidasi tanda tangan PDF dan menampilkan semua tanda tangan dalam dokumen menggunakan Aspose.PDF. + ## Sumber Daya Tambahan - [Dokumentasi Aspose.PDF untuk Net](https://docs.aspose.com/pdf/net/) diff --git a/pdf/indonesian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/indonesian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..009d7539bf --- /dev/null +++ b/pdf/indonesian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Validasi tanda tangan PDF dan daftar tanda tangan PDF menggunakan Aspose.PDF + dalam C#. Kode langkah demi langkah, jebakan, dan praktik terbaik untuk penanganan + dokumen yang aman. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: id +lastmod: 2026-07-26 +og_description: Validasi tanda tangan PDF dan daftar tanda tangan PDF dengan Aspose.PDF. + Ikuti panduan praktis ini untuk mengamankan PDF di C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Validasi Tanda Tangan PDF & Daftar Tanda Tangan PDF – Panduan Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Validasi Tanda Tangan PDF dan Daftar Tanda Tangan PDF dengan Aspose.PDF – Panduan + Lengkap +url: /id/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Validasi Tanda Tangan PDF dan Daftar Tanda Tangan PDF dengan Aspose.PDF – Panduan Lengkap + +Pernah bertanya-tanya bagaimana cara **memvalidasi tanda tangan PDF** dalam aplikasi .NET tanpa stres? Anda tidak sendirian. Baik Anda sedang membangun platform e‑sign atau hanya perlu memastikan kontrak yang diterima tidak diubah, kemampuan untuk **mendaftar tanda tangan PDF** dan memverifikasi masing‑masingnya adalah keterampilan yang wajib dimiliki. + +Pada tutorial ini kami akan membimbing Anda melalui contoh yang dapat dijalankan sepenuhnya yang memuat PDF yang ditandatangani, mengenumerasi setiap tanda tangan yang tersemat, memeriksa apakah ada yang telah dikompromikan, dan mencetak hasil yang jelas ke konsol. Tidak ada referensi yang samar—hanya kode yang dapat Anda salin‑tempel, plus “mengapa” di balik setiap langkah. + +## Prasyarat + +- **Aspose.PDF for .NET** versi 25.3 atau lebih baru (properti `IsCompromised` muncul pada 25.3). +- Lingkungan pengembangan .NET (Visual Studio 2022, Rider, atau `dotnet` CLI). +- File PDF yang ditandatangani untuk diuji (Anda dapat membuatnya dengan Adobe Acrobat atau alat e‑signature apa pun). + +Jika ada yang belum ada, instal paket NuGet terlebih dahulu: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** Target .NET 6 atau yang lebih baru untuk mendapatkan kinerja terbaik dan dukungan jangka panjang. + +## Langkah 1: Muat Dokumen PDF + +Hal pertama yang harus Anda lakukan adalah membuka file PDF. Kelas `Document` milik Aspose.PDF menangani semua mulai dari parsing hingga rendering. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Mengapa ini penting:* Memuat file membuat representasi dalam memori yang memungkinkan Anda menanyakan tanda tangan tanpa harus mengakses sistem file lagi. Ini juga memvalidasi struktur PDF lebih awal, sehingga Anda akan langsung mendapatkan pengecualian jika file rusak. + +## Langkah 2: **Daftar Tanda Tangan PDF** – Enumerasi Semua Tanda Tangan yang Tersemat + +PDF yang ditandatangani dapat berisi beberapa tanda tangan (bayangkan kontrak multi‑halaman di mana setiap pihak menandatangani halaman yang berbeda). Aspose.PDF menampilkannya melalui koleksi `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Apa yang Anda lihat:* Loop mencetak detail **daftar tanda tangan PDF** seperti nama penandatangan, alasan, lokasi, dan timestamp. Ini berguna untuk log audit atau tampilan UI. + +## Langkah 3: **Validasi Tanda Tangan PDF** – Periksa Kompromi + +Berikutnya adalah bagian krusial keamanan: memastikan tidak ada tanda tangan yang diubah setelah penandatanganan. Mulai versi 25.3, Aspose.PDF menyediakan flag `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Mengapa Anda harus menggunakan `IsCompromised`*: Validasi tradisional hanya memeriksa rantai kriptografi (validitas sertifikat, pencabutan, dll.). `IsCompromised` menambahkan lapisan ekstra dengan mendeteksi perubahan apa pun pada dokumen setelah penandatanganan—tepat apa yang Anda butuhkan ketika **memvalidasi tanda tangan PDF** untuk manipulasi. + +## Langkah 4: Menangani Hasil Validasi + +Bergantung pada hasilnya, Anda mungkin ingin mengambil tindakan berbeda. Berikut pola cepat yang dapat Anda sesuaikan: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Catatan kasus tepi:* Jika PDF berisi tanda tangan **bersertifikat** (tanda tangan pertama yang mengunci dokumen), modifikasi selanjutnya dapat membuat seluruh file tidak valid, meskipun tanda tangan berikutnya tampak baik. Selalu perlakukan setiap `true` dari `IsCompromised` sebagai peringatan merah. + +## Contoh Kerja Lengkap + +Menggabungkan semuanya, berikut program tunggal yang mandiri yang dapat Anda kompilasi dan jalankan: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Output yang diharapkan** (asumsi satu tanda tangan baik dan satu yang dirusak): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Kesalahan Umum & Cara Menghindarinya + +| Kesalahan | Mengapa Terjadi | Solusi | +|-----------|-----------------|--------| +| **Versi Aspose.PDF Hilang** | `IsCompromised` diperkenalkan pada 25.3. Paket lama dapat dikompilasi tetapi melempar `MissingMethodException`. | Pastikan referensi NuGet Anda `>= 25.3`. | +| **`SignatureInfo` Null** | Beberapa PDF memiliki slot tanda tangan kosong yang tetap muncul dalam koleksi. | Lindungi dengan `if (signatureInfo != null)` sebelum validasi. | +| **Penurunan performa pada PDF besar** | Memvalidasi setiap tanda tangan membaca seluruh file setiap kali. | Cache `PdfSignatureValidator` atau proses tanda tangan secara batch jika Anda hanya membutuhkan ringkasan boolean. | +| **Pencabutan sertifikat tidak diperiksa** | `IsCompromised` hanya memberi tahu tentang perubahan dokumen, bukan status sertifikat. | Gunakan `PdfSignatureValidator.Validate()` selain `IsCompromised` untuk pemeriksaan PKI lengkap. | + +## Memperluas Solusi + +Jika Anda perlu **mendaftar tanda tangan PDF** dalam UI, cukup masukkan objek `SignatureInfo` ke dalam data grid. Ingin menyimpan hasil validasi ke basis data? Serialisasikan boolean `isCompromised` bersama nama penandatangan dan timestamp. + +Topik terkait lain yang mungkin ingin Anda jelajahi selanjutnya: + +- **Validasi tanda tangan PDF terhadap CA root tepercaya** (gunakan `validator.Validate()`). +- **Ekstrak detail sertifikat yang tersemat** (`validator.Certificate`). +- **Buat tanda tangan digital** dengan Aspose.PDF (`PdfSignatureBuilder`). + +## Kesimpulan + +Anda kini memiliki metode praktis, end‑to‑end untuk **memvalidasi tanda tangan PDF** dan **mendaftar tanda tangan PDF** menggunakan Aspose.PDF untuk .NET. Kode tersebut menunjukkan secara tepat cara memuat dokumen, mengenumerasi setiap tanda tangan, memeriksa flag `IsCompromised`, dan bertindak berdasarkan hasilnya—semua dalam format yang jelas dan ramah konsol. + +Cobalah dengan PDF yang Anda tandatangani, bereksperimen dengan beberapa tanda tangan, dan integrasikan logika ini ke dalam pipeline pemrosesan dokumen yang lebih besar. PDF yang aman hanya sekuat validasi yang Anda lakukan, jadi pertahankan pemeriksaan yang ketat dan log yang lengkap. + +Punya pertanyaan atau ingin berbagi kasus penggunaan menarik? Tinggalkan komentar di bawah atau hubungi saya di GitHub. Selamat coding! + +![Validate PDF Signature](/images/validate-pdf-signature.png "Screenshot of a C# console app validating a PDF signature with Aspose.PDF") + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang dapat dijalankan dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Memverifikasi PDF – Validasi Tanda Tangan PDF dengan Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Cara Mengekstrak Informasi Tanda Tangan PDF Menggunakan Aspose.PDF .NET: Panduan Langkah demi Langkah](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Cara Mengekstrak Gambar dari Kolom Tanda Tangan PDF menggunakan Aspose.PDF untuk .NET: Panduan Langkah demi Langkah](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/indonesian/net/programming-with-operators/_index.md b/pdf/indonesian/net/programming-with-operators/_index.md index 0539c962ff..9ee0052ccc 100644 --- a/pdf/indonesian/net/programming-with-operators/_index.md +++ b/pdf/indonesian/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Bahasa Indonesia: --- | --- Bahasa Indonesia: | [Menggambar XForm Di Halaman](./draw-xform-on-page/) | pelajari cara menggambar XForms dalam PDF menggunakan Aspose.PDF untuk .NET dengan panduan langkah demi langkah yang komprehensif ini. Bahasa Indonesia: | [Operator PDF](./pdf-operators/) | Panduan langkah demi langkah untuk menggunakan operator PDF dengan Aspose.PDF untuk .NET. Tambahkan gambar ke halaman PDF dan tentukan posisinya. Bahasa Indonesia: | [Hapus Objek Grafik Dalam File PDF](./remove-graphics-objects/) Pelajari cara menghapus objek grafik dari berkas PDF menggunakan Aspose.PDF untuk .NET dalam panduan langkah demi langkah ini. Sederhanakan tugas manipulasi PDF Anda. | +| [Buat Kamus PDF Kosong di C# – Panduan Lengkap Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Panduan lengkap untuk membuat kamus PDF kosong menggunakan Aspose.PDF untuk .NET di C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/indonesian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/indonesian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..c70f34a56a --- /dev/null +++ b/pdf/indonesian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-26 +description: Buat kamus PDF kosong dengan Aspose.Pdf di C#. Pelajari langkah demi + langkah cara menambahkan state grafis ke kamus ExtGState untuk manipulasi PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: id +lastmod: 2026-07-26 +og_description: Buat kamus PDF kosong menggunakan Aspose.Pdf untuk C#. Ikuti panduan + praktis ini untuk memodifikasi status grafis dalam PDF Anda. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Buat Kamus PDF Kosong di C# – Tutorial Lengkap Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Buat Kamus PDF Kosong di C# – Panduan Lengkap Aspose.Pdf +url: /id/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat Kamus PDF Kosong di C# – Panduan Lengkap Aspose.Pdf + +Pernah bertanya-tanya bagaimana cara **create empty PDF dictionary** ketika menyesuaikan state grafis PDF? Anda tidak sendirian—banyak pengembang mengalami masalah ini saat mencoba mengatur opacity atau mode pencampuran secara programatis. Dalam tutorial ini kami akan membahas solusi konkret menggunakan Aspose.Pdf untuk C#, menunjukkan secara tepat cara menyuntikkan state grafis baru ke dalam kamus *ExtGState* pada PDF yang ada. + +Kami akan membahas semua yang Anda butuhkan: memuat PDF, mengakses kamus sumber dayanya, membangun **CosPdfDictionary** baru, dan akhirnya menyimpan perubahan. Pada akhir tutorial Anda akan memiliki pola yang dapat digunakan kembali untuk setiap penyesuaian *PDF graphics state* yang Anda perlukan. + +--- + +## Apa yang Akan Anda Pelajari + +- Cara **create empty PDF dictionary** objek dengan API tingkat‑rendah Aspose.Pdf. +- Peran **ExtGState dictionary** dalam mengontrol opacity garis/pengisian dan mode pencampuran. +- Tips praktis untuk manipulasi PDF dengan C#, termasuk penanganan kasus tepi ketika kamus tidak ada. +- Contoh kode lengkap yang dapat dijalankan dan Anda dapat copy‑paste ke dalam proyek Anda. + +### Prasyarat + +- .NET 6.0 atau yang lebih baru (kode ini juga berfungsi dengan .NET Framework 4.6+). +- Salinan berlisensi **Aspose.Pdf for .NET** (versi percobaan gratis dapat digunakan untuk pengujian). +- Pemahaman dasar tentang C# dan konsep PDF seperti resources dan graphics states. + +Jika ada yang terdengar tidak familiar, jangan panik—Anda dapat menginstal Aspose.Pdf melalui NuGet (`Install-Package Aspose.Pdf`) dan sisanya hanyalah C# biasa. + +--- + +## Langkah 1 – Muat Dokumen PDF + +Pertama-tama, Anda memerlukan objek `Document` yang mewakili file yang ingin Anda edit. Membungkusnya dalam blok `using` menjamin pembuangan yang tepat. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Mengapa ini penting*: Membuka file memberi Anda akses ke objek internal COS (Canonical Object Structure), tempat **CosPdfDictionary** berada. Tanpa objek dokumen, Anda tidak dapat mengakses kamus resources yang menyimpan entri **ExtGState**. + +--- + +## Langkah 2 – Akses Kamus Resource Halaman Pertama + +Halaman PDF menyimpan resources mereka (font, gambar, graphics states, dll.) dalam kamus khusus. Kami akan mengambil halaman pertama untuk kesederhanaan, tetapi logika yang sama berlaku untuk indeks halaman manapun. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Tips profesional*: Jika PDF Anda memiliki beberapa halaman dengan set resource yang berbeda, ulangi blok ini untuk setiap halaman yang perlu dimodifikasi. Kelas `DictionaryEditor` adalah pembungkus yang nyaman yang memungkinkan Anda memperlakukan kamus COS seperti .NET `Dictionary`. + +--- + +## Langkah 3 – Ambil atau Inisialisasi Kamus ExtGState + +**Kamus ExtGState** menyimpan objek graphics state yang diberi nama (`GS0`, `GS1`, …). Beberapa PDF sudah memilikinya; yang lain tidak. Kami akan mengambilnya dengan aman, membuat kamus kosong baru bila diperlukan. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Mengapa kami melakukannya*: Mencoba menambahkan graphics state ke **ExtGState dictionary** yang tidak ada akan menyebabkan pengecualian. Pemeriksaan defensif ini membuat kode menjadi kuat untuk PDF apa pun. + +--- + +## Langkah 4 – Bangun Graphics State Baru dengan CosPdfDictionary + +Sekarang masuk ke inti tutorial: **creating an empty PDF dictionary** yang mendefinisikan graphics state khusus. Kami akan mengatur opacity garis (`CA`), opacity isi (`ca`), dan mode pencampuran (`BM`). Anda dapat menambahkan lebih banyak entri nanti—ini hanya set awal. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Penjelasan*: +- `CA` dan `ca` adalah kunci PDF standar yang mengontrol opacity garis dan isi, masing‑masing. +- `BM` memilih mode pencampuran; “Normal” adalah default tetapi Anda dapat menggunakan “Multiply”, “Screen”, dll., tergantung pada kebutuhan desain Anda. +- Dengan menggunakan `CosPdfDictionary.CreateEmptyDictionary`, kami **create empty PDF dictionary** objek yang kemudian kami isi dengan pasangan kunci/nilai. + +--- + +## Langkah 5 – Sisipkan Graphics State Baru ke dalam ExtGState + +Dengan graphics state yang siap, kami cukup menambahkannya ke **ExtGState dictionary** dengan nama unik (misalnya, `GS0`). Jika Anda berencana menambahkan beberapa state, cukup tingkatkan sufiksnya. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tip*: Sebelum menambahkan, Anda mungkin ingin memeriksa apakah `GS0` sudah ada untuk menghindari penimpaan. Guard `if (!extGState.ContainsKey("GS0"))` singkat akan menyelesaikannya. + +--- + +## Langkah 6 – Simpan PDF yang Dimodifikasi + +Semua perubahan berada di memori sampai Anda menyimpannya. Pilih jalur output yang sesuai dengan alur kerja Anda. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Hasil*: Buka `output.pdf` di penampil PDF apa pun, lalu periksa resources halaman (misalnya, dengan alat inspeksi PDF). Anda akan melihat entri baru di bawah **ExtGState** bernama `GS0` dengan parameter yang kami definisikan. + +--- + +## Contoh Kerja Lengkap + +Menggabungkan semuanya, berikut program lengkap yang siap untuk copy‑and‑paste: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Output yang diharapkan**: `output.pdf` akan ditampilkan persis seperti aslinya, tetapi konten apa pun yang kemudian merujuk ke `GS0` (misalnya melalui operator `gs` dalam aliran konten) akan menggunakan opacity dan blend mode yang telah didefinisikan. Jika Anda belum memiliki referensi tersebut, Anda dapat menambahkannya secara manual atau melalui API tingkat‑tinggi Aspose. + +--- + +## Pertanyaan yang Sering Diajukan & Kasus Tepi + +| Pertanyaan | Jawaban | +|------------|---------| +| *Bagaimana jika PDF sudah memiliki entri `ExtGState` bernama `GS0`?* | Periksa `extGState.ContainsKey("GS0")` sebelum menambahkan. Jika sudah ada, Anda dapat menimpa secara sengaja (`extGState["GS0"] = newGraphicsState`) atau memilih nama baru seperti `GS1`. | +| *Apakah saya dapat menambahkan parameter lain, seperti lebar garis (`LW`) atau pola dash (`D`)?* | Tentu saja. Cukup perpanjang array `parameters` dengan entri `KeyValuePair` tambahan. | +| *Apakah pendekatan ini kompatibel dengan PDF yang terenkripsi?* | Ya, selama Anda memberikan kata sandi yang benar saat membuat `Document` (`new Document(path, password)`). | +| *Apakah saya perlu menutup dokumen secara manual?* | Pernyataan `using` menangani pembuangan, yang juga menuliskan semua perubahan yang tertunda. | +| *Bagaimana perbedaannya dengan menggunakan kelas `Graphics` tingkat‑tinggi?* | API tingkat‑tinggi menyembunyikan detail kamus di bawahnya, yang sangat cocok untuk tugas sederhana. Namun, ketika Anda memerlukan kontrol detail atas graphics state—seperti blend mode khusus—Anda harus bekerja dengan **CosPdfDictionary** tingkat‑rendah, yaitu objek **create empty PDF dictionary** secara langsung. | + +--- + +## Kesimpulan + +Kami baru saja mendemonstrasikan cara **create empty PDF dictionary** objek dengan Aspose.Pdf, menyuntikkan graphics state khusus ke dalam **ExtGState dictionary**, dan menyimpan file yang dimodifikasi—semuanya dalam C# yang bersih dan idiomatik. Pola ini membuka kontrol presisi atas opacity, blend mode, dan parameter graphics‑state lainnya yang didefinisikan oleh spesifikasi PDF. + +Dari sini Anda dapat: +- Terapkan graphics state baru ke konten halaman yang ada menggunakan operator `gs`. +- Bangun pustaka graphics state yang dapat digunakan kembali untuk branding atau watermarking. +- + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Membuat Garis Putus-Putus dalam PDF Menggunakan Aspose.PDF untuk .NET: Panduan Langkah demi Langkah](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Buat & Isi Persegi Panjang dalam PDF Menggunakan Aspose.PDF untuk .NET: Panduan Langkah demi Langkah](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/italian/net/digital-signatures/_index.md b/pdf/italian/net/digital-signatures/_index.md index 6d828e3587..3741d2724b 100644 --- a/pdf/italian/net/digital-signatures/_index.md +++ b/pdf/italian/net/digital-signatures/_index.md @@ -62,6 +62,9 @@ Scopri come caricare un PDF in C#, convertirlo in PDF/X‑4 e elencare le firme ### [Convalida firma PDF con Aspose – Converti PDF in HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Scopri come convalidare le firme PDF e convertire i PDF in HTML con Aspose, garantendo l'integrità dei documenti durante la trasformazione. +### [Convalida la firma PDF e elenca le firme PDF con Aspose.PDF – Guida completa](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Scopri come convalidare le firme PDF e elencare tutte le firme presenti usando Aspose.PDF per .NET. + ## Risorse aggiuntive - [Aspose.PDF per la documentazione di rete](https://docs.aspose.com/pdf/net/) diff --git a/pdf/italian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/italian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..8b6d84657a --- /dev/null +++ b/pdf/italian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Convalida la firma PDF ed elenca le firme PDF usando Aspose.PDF in C#. + Codice passo‑passo, insidie e migliori pratiche per la gestione sicura dei documenti. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: it +lastmod: 2026-07-26 +og_description: Convalida la firma PDF ed elenca le firme PDF con Aspose.PDF. Segui + questa guida pratica per proteggere i PDF in C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Convalida firma PDF e elenca firme PDF – Guida Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Convalida la firma PDF e elenca le firme PDF con Aspose.PDF – Guida completa +url: /it/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convalida la firma PDF e elenca le firme PDF con Aspose.PDF – Guida completa + +Ti sei mai chiesto come **convalidare la firma PDF** in un'app .NET senza impazzire? Non sei l'unico. Che tu stia costruendo una piattaforma di firma elettronica o semplicemente debba assicurarti che un contratto ricevuto non sia stato manomesso, la capacità di **elencare le firme PDF** e verificare ciascuna è una competenza indispensabile. + +In questo tutorial percorreremo un esempio completamente eseguibile che carica un PDF firmato, elenca ogni firma incorporata, verifica se qualcuna è stata compromessa e stampa un risultato chiaro sulla console. Niente riferimenti vaghi—solo il codice che puoi copiare‑incollare, più il “perché” dietro ogni passaggio. + +## Prerequisiti + +Prima di immergerci, assicurati di avere: + +- **Aspose.PDF for .NET** versione 25.3 o successiva (la proprietà `IsCompromised` è comparsa nella 25.3). +- Un ambiente di sviluppo .NET (Visual Studio 2022, Rider o la CLI `dotnet`). +- Un file PDF firmato con cui fare dei test (puoi crearne uno con Adobe Acrobat o qualsiasi strumento di firma elettronica). + +Se manca qualcosa, installa prima il pacchetto NuGet: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Consiglio pratico:** Mira a .NET 6 o versioni successive per ottenere le migliori prestazioni e il supporto a lungo termine. + +## Passo 1: Carica il documento PDF + +La prima cosa da fare è aprire il file PDF. La classe `Document` di Aspose.PDF gestisce tutto, dalla lettura al rendering. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Perché è importante:* Il caricamento del file crea una rappresentazione in memoria che ti permette di interrogare le firme senza toccare nuovamente il file system. Inoltre valida la struttura del PDF subito, così otterrai un’eccezione immediata se il file è corrotto. + +## Passo 2: **Elenca le firme PDF** – Enumerare tutte le firme incorporate + +Un PDF firmato può contenere più firme (pensa a un contratto a più pagine dove ogni parte firma una pagina diversa). Aspose.PDF le espone tramite la collezione `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Cosa vedi:* Il ciclo stampa i dettagli delle **firme PDF** come il nome del firmatario, la motivazione, la posizione e il timestamp. È utile per i log di audit o per visualizzazioni UI. + +## Passo 3: **Convalida la firma PDF** – Verifica la compromissione + +Ora arriva la parte critica per la sicurezza: confermare che nessuna delle firme sia stata modificata dopo la firma. A partire dalla versione 25.3, Aspose.PDF fornisce il flag `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Perché usare `IsCompromised`*: La convalida tradizionale controlla solo la catena crittografica (validità del certificato, revoca, ecc.). `IsCompromised` aggiunge un livello extra rilevando eventuali modifiche al documento post‑firma—esattamente ciò di cui hai bisogno quando **convalidi la firma PDF** per verificare manomissioni. + +## Passo 4: Gestione dei risultati di convalida + +A seconda del risultato, potresti voler intraprendere azioni diverse. Ecco un rapido schema che puoi adattare: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Nota su casi limite:* Se un PDF contiene una firma **certificata** (la prima firma che blocca il documento), una modifica successiva può invalidare l’intero file, anche se le firme successive sembrano corrette. Tratta sempre qualsiasi valore `true` restituito da `IsCompromised` come un segnale di allarme. + +## Esempio completo funzionante + +Mettendo tutto insieme, ecco un programma unico, autonomo, che puoi compilare ed eseguire: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Output previsto** (supponendo una firma valida e una manomessa): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Problemi comuni e come evitarli + +| Problema | Perché accade | Soluzione | +|----------|---------------|-----------| +| **Versione Aspose.PDF mancante** | `IsCompromised` è stato introdotto nella 25.3. Le versioni più vecchie compilano ma generano `MissingMethodException`. | Assicurati che il riferimento NuGet sia `>= 25.3`. | +| **`SignatureInfo` nullo** | Alcuni PDF hanno slot di firma vuoti che compaiono comunque nella collezione. | Verifica con `if (signatureInfo != null)` prima della convalida. | +| **Impatto sulle prestazioni con PDF di grandi dimensioni** | Convalidare ogni firma legge l’intero file ogni volta. | Metti in cache il `PdfSignatureValidator` o elabora le firme in batch se ti serve solo un riepilogo booleano. | +| **Revoca del certificato non controllata** | `IsCompromised` indica solo modifiche al documento, non lo stato del certificato. | Usa `PdfSignatureValidator.Validate()` oltre a `IsCompromised` per controlli PKI completi. | + +## Estendere la soluzione + +Se devi **elencare le firme PDF** in una UI, basta passare gli oggetti `SignatureInfo` a una griglia dati. Vuoi memorizzare i risultati della convalida in un database? Serializza il booleano `isCompromised` insieme al nome del firmatario e al timestamp. + +Altri argomenti correlati da esplorare: + +- **Convalida la firma PDF contro una CA radice attendibile** (usa `validator.Validate()`). +- **Estrai i dettagli del certificato incorporato** (`validator.Certificate`). +- **Crea firme digitali** con Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusione + +Ora disponi di un metodo pratico, end‑to‑end, per **convalidare la firma PDF** e **elencare le firme PDF** usando Aspose.PDF per .NET. Il codice mostra esattamente come caricare un documento, enumerare ogni firma, controllare il flag `IsCompromised` e reagire al risultato—tutto in un formato chiaro e adatto alla console. + +Provalo con i tuoi PDF firmati, sperimenta con firme multiple e integra la logica nel tuo più ampio flusso di elaborazione documenti. I PDF sicuri sono forti quanto le convalide che esegui, quindi mantieni i controlli rigorosi e i log completi. + +Hai domande o vuoi condividere un caso d'uso interessante? Lascia un commento qui sotto o contattami su GitHub. Buona programmazione! + +![Convalida firma PDF](/images/validate-pdf-signature.png "Screenshot di un'app console C# che convalida una firma PDF con Aspose.PDF") + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità aggiuntive dell'API ed esplorare approcci alternativi nei tuoi progetti. + +- [Come verificare un PDF – Convalida la firma PDF con Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Come estrarre le informazioni della firma PDF usando Aspose.PDF .NET: Guida passo‑passo](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Come estrarre le immagini dai campi firma PDF usando Aspose.PDF per .NET: Guida passo‑passo](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/italian/net/programming-with-operators/_index.md b/pdf/italian/net/programming-with-operators/_index.md index 0bc8780b31..397faed113 100644 --- a/pdf/italian/net/programming-with-operators/_index.md +++ b/pdf/italian/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ tutorial "Programmazione con operatori" di Aspose.PDF per .NET ti guideranno att | [Disegna XForm sulla pagina](./draw-xform-on-page/) | Impara a disegnare XForms in PDF usando Aspose.PDF per .NET con questa guida completa passo dopo passo. | | [Operatori PDF](./pdf-operators/) | Guida passo passo all'utilizzo degli operatori PDF con Aspose.PDF per .NET. Aggiungi un'immagine a una pagina PDF e specificane la posizione. | | [Rimuovi oggetti grafici nel file PDF](./remove-graphics-objects/) Scopri come rimuovere oggetti grafici da un file PDF utilizzando Aspose.PDF per .NET in questa guida passo passo. Semplifica le tue attività di manipolazione PDF. | +| [Crea dizionario PDF vuoto in C# – Guida completa Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Scopri come creare un dizionario PDF vuoto in C# con Aspose.PDF per .NET in questa guida dettagliata passo passo. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/italian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/italian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..92503c7123 --- /dev/null +++ b/pdf/italian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-07-26 +description: Crea un dizionario PDF vuoto con Aspose.Pdf in C#. Impara passo passo + come aggiungere uno stato grafico al dizionario ExtGState per la manipolazione dei + PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: it +lastmod: 2026-07-26 +og_description: Crea un dizionario PDF vuoto usando Aspose.Pdf per C#. Segui questa + guida pratica per modificare gli stati grafici nei tuoi PDF. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Crea un dizionario PDF vuoto in C# – Tutorial completo di Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Crea un dizionario PDF vuoto in C# – Guida completa a Aspose.Pdf +url: /it/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea un Dizionario PDF Vuoto in C# – Guida Completa a Aspose.Pdf + +Ti sei mai chiesto come **creare voci di dizionario PDF vuote** quando modifichi lo stato grafico di un PDF? Non sei solo—molti sviluppatori incontrano questo ostacolo cercando di regolare l'opacità o le modalità di fusione in modo programmatico. In questo tutorial percorreremo una soluzione concreta usando Aspose.Pdf per C#, mostrando esattamente come inserire un nuovo stato grafico nel dizionario *ExtGState* di un PDF esistente. + +Copriamo tutto ciò di cui hai bisogno: caricare un PDF, accedere al suo dizionario delle risorse, costruire un nuovo **CosPdfDictionary** e, infine, salvare le modifiche. Alla fine avrai un modello riutilizzabile per qualsiasi modifica allo *stato grafico PDF* di cui potresti aver bisogno. + +## Cosa Imparerai + +- Come **creare oggetti dizionario PDF vuoti** con l'API low‑level di Aspose.Pdf. +- Il ruolo del **dizionario ExtGState** nel controllare l'opacità del tratto/riempimento e le modalità di fusione. +- Consigli pratici per la manipolazione di PDF in C#, inclusa la gestione dei casi limite quando il dizionario è assente. +- Un esempio di codice completo e eseguibile che puoi copiare‑incollare nel tuo progetto. + +### Prerequisiti + +- .NET 6.0 o successivo (il codice funziona anche con .NET Framework 4.6+). +- Una copia con licenza di **Aspose.Pdf for .NET** (la versione di prova gratuita è sufficiente per i test). +- Familiarità di base con C# e i concetti PDF come risorse e stati grafici. + +Se qualcuno di questi ti è poco familiare, non preoccuparti—puoi installare Aspose.Pdf tramite NuGet (`Install-Package Aspose.Pdf`) e il resto è semplicemente C#. + +## Passo 1 – Carica il Documento PDF + +Prima di tutto, hai bisogno di un oggetto `Document` che rappresenti il file che vuoi modificare. Avvolgerlo in un blocco `using` garantisce una corretta gestione delle risorse. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Perché è importante*: Aprire il file ti dà accesso agli oggetti COS (Canonical Object Structure) interni, dove risiede il **CosPdfDictionary**. Senza l'oggetto documento, non puoi raggiungere i dizionari delle risorse che contengono le voci **ExtGState**. + +## Passo 2 – Accedi al Dizionario delle Risorse della Prima Pagina + +Le pagine PDF memorizzano le loro risorse (font, immagini, stati grafici, ecc.) in un dizionario dedicato. Preleveremo la prima pagina per semplicità, ma la stessa logica si applica a qualsiasi indice di pagina. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Consiglio professionale*: Se il tuo PDF ha più pagine con set di risorse diversi, ripeti questo blocco per ogni pagina che devi modificare. La classe `DictionaryEditor` è un wrapper comodo che ti permette di trattare il dizionario COS come un .NET `Dictionary`. + +## Passo 3 – Recupera o Inizializza il Dizionario ExtGState + +Il **dizionario ExtGState** contiene oggetti di stato grafico nominati (`GS0`, `GS1`, …). Alcuni PDF lo contengono già; altri no. Lo recupereremo in modo sicuro, creando uno nuovo vuoto se necessario. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Perché lo facciamo*: Tentare di aggiungere uno stato grafico a un **dizionario ExtGState** inesistente genererebbe un'eccezione. Questo controllo difensivo rende il codice robusto per qualsiasi PDF di input. + +## Passo 4 – Costruisci un Nuovo Stato Grafico con CosPdfDictionary + +Ora arriva il cuore del tutorial: **creare un dizionario PDF vuoto** che definisce uno stato grafico personalizzato. Imposteremo l'opacità del tratto (`CA`), l'opacità del riempimento (`ca`) e la modalità di fusione (`BM`). Puoi aggiungere altre voci in seguito—questo è solo un set di base. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Spiegazione*: +- `CA` e `ca` sono chiavi PDF standard che controllano rispettivamente l'opacità del tratto e del riempimento. +- `BM` seleziona la modalità di fusione; “Normal” è il valore predefinito ma potresti usare “Multiply”, “Screen”, ecc., a seconda delle esigenze del tuo design. +- Utilizzando `CosPdfDictionary.CreateEmptyDictionary`, **creiamo oggetti dizionario PDF vuoti** che successivamente riempiamo con coppie chiave/valore. + +## Passo 5 – Inserisci il Nuovo Stato Grafico in ExtGState + +Con lo stato grafico pronto, lo aggiungiamo semplicemente al **dizionario ExtGState** sotto un nome unico (ad esempio `GS0`). Se prevedi di aggiungere più stati, incrementa semplicemente il suffisso. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Suggerimento*: Prima di aggiungere, potresti voler verificare se `GS0` esiste già per evitare di sovrascrivere. Una semplice guardia `if (!extGState.ContainsKey("GS0"))` risolve il problema. + +## Passo 6 – Salva il PDF Modificato + +Tutte le modifiche sono in memoria finché non le salvi. Scegli un percorso di output che abbia senso per il tuo flusso di lavoro. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Risultato*: Apri `output.pdf` in qualsiasi visualizzatore PDF, quindi ispeziona le risorse della pagina (ad esempio con uno strumento di ispezione PDF). Vedrai una nuova voce sotto **ExtGState** chiamata `GS0` con i parametri che abbiamo definito. + +## Esempio Completo Funzionante + +Mettendo tutto insieme, ecco il programma completo, pronto per il copia‑incolla: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Output previsto**: Il `output.pdf` verrà visualizzato esattamente come l'originale, ma qualsiasi contenuto che in seguito faccia riferimento a `GS0` (ad esempio tramite l'operatore `gs` in uno stream di contenuto) adotterà l'opacità e la modalità di fusione definite. Se non hai ancora un tale riferimento, puoi aggiungerne uno manualmente o tramite le API di livello superiore di Aspose. + +## Domande Frequenti & Casi Limite + +| Domanda | Risposta | +|----------|--------| +| *E se il PDF ha già una voce `ExtGState` denominata `GS0`?* | Verifica `extGState.ContainsKey("GS0")` prima di aggiungere. Se esiste, sovrascrivi deliberatamente (`extGState["GS0"] = newGraphicsState`) oppure scegli un nuovo nome come `GS1`. | +| *Posso aggiungere più parametri, come lo spessore della linea (`LW`) o il pattern di tratteggio (`D`)?* | Assolutamente. Basta estendere l'array `parameters` con ulteriori voci `KeyValuePair`. | +| *Questo approccio è compatibile con PDF crittografati?* | Sì, purché fornisci la password corretta quando crei il `Document` (`new Document(path, password)`). | +| *Devo chiudere manualmente il documento?* | L'istruzione `using` si occupa della chiusura, che svuota anche eventuali modifiche in sospeso. | +| *In che modo questo differisce dall'uso della classe `Graphics` di alto livello?* | L'API di alto livello astrae i dizionari sottostanti, il che è ottimo per compiti semplici. Tuttavia, quando hai bisogno di un controllo fine sugli stati grafici—come modalità di fusione personalizzate—devi lavorare con il **CosPdfDictionary** di basso livello, cioè creare direttamente oggetti **create empty PDF dictionary**. | + +## Conclusione + +Abbiamo appena dimostrato come **creare oggetti dizionario PDF vuoti** con Aspose.Pdf, inserire uno stato grafico personalizzato nel **dizionario ExtGState** e salvare il file modificato—tutto in C# pulito e idiomatico. Questo modello consente un controllo preciso su opacità, modalità di fusione e qualsiasi altro parametro di stato grafico definito dalla specifica PDF. + +Da qui potresti: + +- Applicare il nuovo stato grafico al contenuto della pagina esistente usando l'operatore `gs`. +- Costruire una libreria di stati grafici riutilizzabili per branding o filigrane. +- + +## Cosa Dovresti Imparare Dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell'API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/japanese/net/digital-signatures/_index.md b/pdf/japanese/net/digital-signatures/_index.md index cdbd9f70da..5ba67a15e5 100644 --- a/pdf/japanese/net/digital-signatures/_index.md +++ b/pdf/japanese/net/digital-signatures/_index.md @@ -56,9 +56,12 @@ C# を使用して PDF のデジタル署名を検証する手順を詳細に解 ### [PDF ドキュメントの読み込み C# – PDF/X‑4 へ変換 & 署名の一覧表示](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) PDF ドキュメントを読み込み、PDF/X‑4 に変換し、署名情報を一覧表示する方法を学びます。 -### [Aspose を使用した PDF 署名の検証 – PDF を HTML に変換](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) +### [Aspose.PDF を使用した PDF 署名の検証 – PDF を HTML に変換](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Aspose を利用して PDF の署名を検証し、PDF を HTML に変換する手順を解説します。 +### [Aspose.PDF を使用した PDF 署名の検証と署名一覧表示 – 完全ガイド](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Aspose.PDF を使用して PDF 署名を検証し、署名情報を一覧表示する方法を学びます。 + ## 追加リソース - [Aspose.PDF for Net ドキュメント](https://docs.aspose.com/pdf/net/) diff --git a/pdf/japanese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/japanese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..8a27902381 --- /dev/null +++ b/pdf/japanese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Aspose.PDF を使用して C# で PDF 署名を検証し、PDF 署名の一覧を取得する。ステップバイステップのコード、落とし穴、そして安全な文書取り扱いのベストプラクティス。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: ja +lastmod: 2026-07-26 +og_description: Aspose.PDF を使用して PDF 署名を検証し、PDF 署名の一覧を取得します。この実用的なガイドに従って C# で PDF + を保護しましょう。 +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: PDF 署名の検証と署名一覧 – Aspose.PDF ハウツー +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Aspose.PDFでPDF署名を検証し、PDF署名を一覧表示する完全ガイド +url: /ja/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.PDF を使用した PDF 署名の検証と PDF 署名の一覧表示 – 完全ガイド + +.NET アプリで **validate PDF signature**(PDF 署名の検証)を、髪の毛を抜かずに行いたいと思ったことはありませんか? あなただけではありません。e‑sign プラットフォームを構築している場合でも、受領した契約書が改ざんされていないか確認したいだけの場合でも、**list PDF signatures**(PDF 署名の一覧表示)して各署名を検証できることは必須スキルです。 + +このチュートリアルでは、署名済み PDF を読み込み、埋め込まれたすべての署名を列挙し、いずれかが改ざんされていないかチェックし、結果をコンソールに明確に出力する、完全に実行可能なサンプルを順を追って解説します。曖昧な説明は一切なく、コピー&ペーストできるコードと、各ステップの「なぜ」を併せて提供します。 + +## 前提条件 + +作業を始める前に、以下が揃っていることを確認してください。 + +- **Aspose.PDF for .NET** バージョン 25.3 以上(`IsCompromised` プロパティは 25.3 で追加) +- .NET 開発環境(Visual Studio 2022、Rider、または `dotnet` CLI) +- テスト用の署名済み PDF ファイル(Adobe Acrobat や任意の e‑signature ツールで作成可能) + +上記が不足している場合は、まず NuGet パッケージをインストールしてください。 + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **プロのコツ:** .NET 6 以降をターゲットにすると、最高のパフォーマンスと長期サポートが得られます。 + +## 手順 1: PDF ドキュメントの読み込み + +最初に行うべきことは PDF ファイルを開くことです。Aspose.PDF の `Document` クラスは、解析からレンダリングまでをすべて処理します。 + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*このステップが重要な理由:* ファイルを読み込むことで、ファイルシステムに再度アクセスすることなく署名を照会できるインメモリ表現が作成されます。また、PDF 構造が早期に検証されるため、破損している場合はすぐに例外がスローされます。 + +## 手順 2: **List PDF Signatures** – 埋め込まれたすべての署名を列挙 + +署名済み PDF には複数の署名が含まれることがあります(例: 各当事者が別ページに署名するマルチページ契約書)。Aspose.PDF は `Signatures` コレクションでこれらを公開しています。 + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*出力内容の説明:* ループは **list PDF signatures** の詳細(署名者名、理由、場所、タイムスタンプ)をコンソールに出力します。監査ログや UI 表示に便利です。 + +## 手順 3: **Validate PDF Signature** – 改ざんの有無をチェック + +ここからがセキュリティ上重要な部分です。署名後にドキュメントが変更されていないことを確認します。バージョン 25.3 以降、Aspose.PDF は `PdfSignatureValidator.IsCompromised` フラグを提供しています。 + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*`IsCompromised` を使用すべき理由:* 従来の検証は暗号チェーン(証明書の有効性、失効チェックなど)だけを確認します。`IsCompromised` は署名後のドキュメント変更を検出する追加レイヤーを提供し、**validate PDF signature**(PDF 署名の検証)に最適です。 + +## 手順 4: 検証結果の処理 + +結果に応じて異なるアクションを取る必要があります。以下は簡易的なパターン例です。 + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*エッジケースの注意点:* PDF に **certified** 署名(ドキュメント全体をロックする最初の署名)が含まれている場合、後からの変更はその署名が有効でもファイル全体を無効にします。`IsCompromised` が `true` を返したら必ず警告として扱いましょう。 + +## 完全動作サンプル + +すべてをまとめた、単一ファイルで完結するプログラム例です。コンパイルして実行できます。 + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**期待される出力**(正常な署名が 1 つ、改ざんされた署名が 1 つある場合): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## よくある落とし穴と回避策 + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Missing Aspose.PDF version** | `IsCompromised` は 25.3 で導入されました。古いパッケージはコンパイルは通りますが `MissingMethodException` が発生します。 | NuGet 参照を `>= 25.3` にしてください。 | +| **Null `SignatureInfo`** | 一部の PDF では、コレクションに空の署名スロットが含まれることがあります。 | 検証前に `if (signatureInfo != null)` でガードしてください。 | +| **Performance hit on large PDFs** | 各署名を検証するたびにファイル全体を読み込むため、処理が重くなります。 | `PdfSignatureValidator` をキャッシュするか、ブールサマリだけが必要な場合は一括処理してください。 | +| **Certificate revocation not checked** | `IsCompromised` は文書変更のみを示し、証明書の状態はチェックしません。 | 完全な PKI 検証が必要な場合は `PdfSignatureValidator.Validate()` と併用してください。 | + +## ソリューションの拡張 + +UI に **list PDF signatures** を表示したい場合は、`SignatureInfo` オブジェクトをデータグリッドにバインドすれば完了です。検証結果をデータベースに保存したい場合は、`isCompromised` の真偽値と署名者名・タイムスタンプをシリアライズして保存します。 + +次に検討できる関連トピック: + +- **Validate PDF signature against a trusted root CA**(`validator.Validate()` を使用) +- **Extract embedded certificate details**(`validator.Certificate`) +- **Create digital signatures** with Aspose.PDF(`PdfSignatureBuilder`) + +## 結論 + +これで Aspose.PDF for .NET を使って **validate PDF signature** と **list PDF signatures** を行う、ハンズオンのエンドツーエンド手法が身につきました。コードは、ドキュメントの読み込み、各署名の列挙、`IsCompromised` フラグのチェック、結果に応じた処理を、コンソール向けに分かりやすく示しています。 + +自分の署名済み PDF で試し、複数署名のシナリオを実験し、ロジックをドキュメント処理パイプラインに組み込んでみてください。PDF の安全性は検証の徹底度に依存しますので、チェックは厳格に、ログは詳細に残すようにしましょう。 + +質問や面白いユースケースがあれば、コメントや GitHub でお気軽にどうぞ。Happy coding! + +![Validate PDF Signature](/images/validate-pdf-signature.png "Aspose.PDF を使用した C# コンソール アプリでの PDF 署名検証のスクリーンショット") + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基に、さらに関連するトピックを深掘りできる内容です。各リソースは完全なコード例とステップバイステップの解説を含んでおり、API の追加機能習得や代替実装アプローチの検証に役立ちます。 + +- [How to Verify PDF – Validate PDF Signature with Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [How to Extract PDF Signature Information Using Aspose.PDF .NET: A Step-by-Step Guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [How to Extract Images from PDF Signature Fields using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/japanese/net/programming-with-operators/_index.md b/pdf/japanese/net/programming-with-operators/_index.md index fd024c4109..b7092aa0a9 100644 --- a/pdf/japanese/net/programming-with-operators/_index.md +++ b/pdf/japanese/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Aspose.PDF for .NET の「演算子を使ったプログラミング」チュー | [ページにXFormを描く](./draw-xform-on-page/) この包括的なステップバイステップ ガイドで、Aspose.PDF for .NET を使用して PDF に XForms を描画する方法を学びます。 | | [PDF演算子](./pdf-operators/) Aspose.PDF for .NET で PDF 演算子を使用するためのステップバイステップガイド。PDF ページに画像を追加し、その位置を指定します。 | | [PDFファイル内のグラフィックオブジェクトを削除する](./remove-graphics-objects/) このステップバイステップガイドでは、Aspose.PDF for .NET を使用してPDFファイルからグラフィックオブジェクトを削除する方法を学びます。PDF操作タスクを簡素化します。 | +| [C# で空の PDF 辞書を作成する – 完全 Aspose.Pdf ガイド](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) Aspose.PDF for .NET を使用して、C# で空の PDF 辞書を作成し、カスタム PDF 構造を管理する方法を学びます。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/japanese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/japanese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..441287b357 --- /dev/null +++ b/pdf/japanese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-07-26 +description: C# で Aspose.Pdf を使用して空の PDF 辞書を作成する。PDF 操作のために ExtGState 辞書にグラフィックスステートを追加する方法をステップバイステップで学ぶ。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: ja +lastmod: 2026-07-26 +og_description: Aspose.Pdf for C# を使用して空の PDF 辞書を作成します。このハンズオン ガイドに従って、PDF のグラフィックス状態を変更してください。 +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: C#で空のPDFディクショナリを作成 – 完全なAspose.Pdfチュートリアル +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: C#で空のPDFディクショナリを作成 – 完全なAspose.Pdfガイド +url: /ja/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で空の PDF 辞書を作成 – 完全な Aspose.Pdf ガイド + +PDF のグラフィックスステートを調整するときに **空の PDF 辞書** エントリを作成する方法を考えたことがありますか? あなた一人ではありません—多くの開発者が不透明度やブレンドモードをプログラムで調整しようとしてこの問題に直面しています。このチュートリアルでは、Aspose.Pdf for C# を使用した具体的な解決策を示し、既存の PDF の *ExtGState* 辞書に新しいグラフィックスステートを注入する方法を詳しく解説します。 + +PDF の読み込み、リソース辞書へのアクセス、新しい **CosPdfDictionary** の構築、そして最終的な保存まで、必要なすべてを網羅します。最後まで読めば、任意の *PDF graphics state* の調整に再利用できるパターンが手に入ります。 + +--- + +## 学べること + +- Aspose.Pdf の低レベル API を使用して **空の PDF 辞書** オブジェクトを **create empty PDF dictionary** する方法。 +- ストローク/塗りの不透明度やブレンドモードを制御する **ExtGState 辞書** の役割。 +- 辞書が存在しない場合のエッジケース処理を含む、C# PDF 操作の実践的なヒント。 +- プロジェクトにコピーペーストできる、完全な実行可能コードサンプル。 + +### 前提条件 + +- .NET 6.0 以上(.NET Framework 4.6+ でも動作します)。 +- **Aspose.Pdf for .NET** のライセンス版(無料トライアルでもテスト可能)。 +- C# と、リソースやグラフィックスステートといった PDF の概念に関する基本的な知識。 + +これらのいずれかが馴染みがない場合でも心配はいりません。NuGet で Aspose.Pdf をインストールできます(`Install-Package Aspose.Pdf`)し、残りは普通の C# です。 + +--- + +## ステップ 1 – PDF ドキュメントの読み込み + +まず最初に、編集したいファイルを表す `Document` オブジェクトが必要です。`using` ブロックでラップすれば、適切に破棄されます。 + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Why this matters*: ファイルを開くことで内部の COS(Canonical Object Structure)オブジェクトにアクセスでき、**CosPdfDictionary** が格納されている場所へたどり着きます。`Document` オブジェクトがなければ、**ExtGState** エントリを保持するリソース辞書に到達できません。 + +--- + +## ステップ 2 – 最初のページのリソース辞書にアクセス + +PDF ページはリソース(フォント、画像、グラフィックスステートなど)を専用の辞書に保持しています。ここではシンプルに最初のページを取得しますが、任意のページインデックスでも同様のロジックが適用できます。 + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Pro tip*: PDF に複数ページがあり、ページごとにリソースが異なる場合は、変更したい各ページに対してこのブロックを繰り返してください。`DictionaryEditor` クラスは COS 辞書を .NET の `Dictionary` のように扱える便利なラッパーです。 + +--- + +## ステップ 3 – ExtGState 辞書の取得または初期化 + +**ExtGState 辞書** には名前付きグラフィックスステートオブジェクト(`GS0`, `GS1`, …)が格納されます。PDF に既に存在する場合もあれば、存在しない場合もあります。ここでは安全に取得し、必要なら空の辞書を新規作成します。 + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Why we do this*: 存在しない **ExtGState 辞書** にグラフィックスステートを追加しようとすると例外がスローされます。この防御的チェックにより、任意の入力 PDF に対してコードが堅牢になります。 + +--- + +## ステップ 4 – CosPdfDictionary で新しいグラフィックスステートを構築 + +本チュートリアルの核心です:カスタムグラフィックスステートを定義する **空の PDF 辞書** を作成します。ここではストローク不透明度(`CA`)、塗り不透明度(`ca`)、ブレンドモード(`BM`)を設定します。後からエントリを追加すれば、さらに拡張可能です。 + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Explanation*: +- `CA` と `ca` はそれぞれストロークと塗りの不透明度を制御する標準 PDF キーです。 +- `BM` はブレンドモードを選択します。デフォルトは “Normal” ですが、デザイン要件に応じて “Multiply” や “Screen” なども使用できます。 +- `CosPdfDictionary.CreateEmptyDictionary` を使用することで、後でキー/バリューのペアを埋め込む **create empty PDF dictionary** オブジェクトを作成しています。 + +--- + +## ステップ 5 – 新しいグラフィックスステートを ExtGState に挿入 + +グラフィックスステートが準備できたら、ユニークな名前(例: `GS0`)で **ExtGState 辞書** に追加します。複数のステートを追加したい場合はサフィックスをインクリメントすれば OK です。 + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tip*: 追加する前に `GS0` が既に存在しないか確認すると、上書きを防げます。`if (!extGState.ContainsKey("GS0"))` のようなガードを入れるだけです。 + +--- + +## ステップ 6 – 変更後の PDF を保存 + +すべての変更はメモリ上に保持されているので、永続化が必要です。ワークフローに合った出力パスを指定してください。 + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Result*: 任意の PDF ビューアで `output.pdf` を開き、ページリソース(例: PDF インスペクターツール)を確認すると、**ExtGState** に `GS0` という新エントリが追加され、定義したパラメータが表示されます。 + +--- + +## 完全動作サンプル + +すべてをまとめた、コピー&ペースト可能なプログラムはこちらです: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Expected output**: `output.pdf` は元の PDF と同じように表示されますが、後から `GS0`(例: コンテンツストリーム内の `gs` 演算子)を参照すると、設定した不透明度とブレンドモードが適用されます。まだ参照が無い場合は手動で追加するか、Aspose の上位レベル API を使って追加してください。 + +--- + +## Frequently Asked Questions & Edge Cases + +| Question | Answer | +|----------|--------| +| *What if the PDF already has an `ExtGState` entry named `GS0`?* | `extGState.ContainsKey("GS0")` を追加前に確認してください。既に存在する場合は意図的に上書きする(`extGState["GS0"] = newGraphicsState`)か、`GS1` など新しい名前を選択します。 | +| *Can I add more parameters, like line width (`LW`) or dash pattern (`D`)?* | もちろんです。`parameters` 配列に `KeyValuePair` エントリを追加すれば OK です。 | +| *Is this approach compatible with encrypted PDFs?* | はい、`Document` を構築する際に正しいパスワードを渡せば(`new Document(path, password)`)対応できます。 | +| *Do I need to close the document manually?* | `using` 文が破棄を自動で行い、保留中の変更もフラッシュします。 | +| *How does this differ from using the high‑level `Graphics` class?* | 高レベル API は内部辞書を抽象化してくれるため簡単なタスクには便利ですが、カスタムブレンドモードのように細かいグラフィックスステート制御が必要な場合は、低レベルの **CosPdfDictionary**、すなわち **create empty PDF dictionary** オブジェクトを直接操作する必要があります。 | + +--- + +## Conclusion + +本稿では Aspose.Pdf を使って **空の PDF 辞書** オブジェクトを作成し、カスタムグラフィックスステートを **ExtGState 辞書** に注入し、変更後のファイルを保存する手順を、クリーンで慣用的な C# コードで示しました。このパターンを利用すれば、不透明度やブレンドモード、PDF 仕様で定義されたその他のグラフィックスステートパラメータを正確にコントロールできます。 + +ここからは次のような応用が考えられます。 +- `gs` 演算子を使って既存ページコンテンツに新しいグラフィックスステートを適用する。 +- ブランドや透かし用に再利用可能なグラフィックスステートのライブラリを構築する。 +- + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには完全なコード例とステップバイステップの解説が含まれており、API の追加機能習得や別実装アプローチの探求に役立ちます。 + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/korean/net/digital-signatures/_index.md b/pdf/korean/net/digital-signatures/_index.md index b7d4931cd4..1d7a42be99 100644 --- a/pdf/korean/net/digital-signatures/_index.md +++ b/pdf/korean/net/digital-signatures/_index.md @@ -59,6 +59,9 @@ C#을 사용해 PDF 문서를 로드하고 PDF/X‑4 형식으로 변환한 뒤, ### [Aspose를 사용하여 PDF 서명 검증 – PDF를 HTML로 변환](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Aspose를 사용해 PDF 서명을 검증하고 PDF를 HTML로 변환하는 방법을 단계별로 안내합니다. +### [Aspose.PDF를 사용한 PDF 서명 검증 및 서명 목록 확인 – 완전 가이드](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Aspose.PDF를 활용해 PDF 서명을 검증하고 문서에 포함된 모든 서명 목록을 추출하는 방법을 단계별로 안내합니다. + ## 추가 자료 - [Net 문서용 Aspose.PDF](https://docs.aspose.com/pdf/net/) diff --git a/pdf/korean/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/korean/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..7c0af0eb91 --- /dev/null +++ b/pdf/korean/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-26 +description: C#에서 Aspose.PDF를 사용하여 PDF 서명을 검증하고 PDF 서명을 나열합니다. 단계별 코드, 주의사항 및 보안 문서 + 처리를 위한 모범 사례. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: ko +lastmod: 2026-07-26 +og_description: Aspose.PDF를 사용하여 PDF 서명을 검증하고 PDF 서명을 나열하세요. C#에서 PDF를 보호하는 실용적인 가이드를 + 따라보세요. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: PDF 서명 검증 및 PDF 서명 목록 – Aspose.PDF 사용법 +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Aspose.PDF를 사용한 PDF 서명 검증 및 PDF 서명 목록 보기 – 완전 가이드 +url: /ko/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.PDF를 사용한 PDF 서명 검증 및 PDF 서명 목록 확인 – 완전 가이드 + +.NET 앱에서 **PDF 서명 검증**을 머리카락을 뽑지 않고도 할 수 있는 방법이 궁금했나요? 당신만 그런 것이 아닙니다. 전자 서명 플랫폼을 구축하든, 단순히 수신한 계약서가 변조되지 않았는지 확인하든, **PDF 서명 목록**을 확인하고 각각을 검증할 수 있는 능력은 필수적인 기술입니다. + +이 튜토리얼에서는 서명된 PDF를 로드하고, 포함된 모든 서명을 열거하며, 어느 것이 손상되었는지 확인하고, 콘솔에 명확한 결과를 출력하는 완전 실행 가능한 예제를 단계별로 살펴봅니다. 모호한 설명은 없습니다—복사‑붙여넣기 할 수 있는 코드와 각 단계 뒤에 숨은 “왜”를 제공합니다. + +## 사전 요구 사항 + +- **Aspose.PDF for .NET** 버전 25.3 이상 (`IsCompromised` 속성이 25.3에 도입되었습니다). +- .NET 개발 환경 (Visual Studio 2022, Rider, 또는 `dotnet` CLI). +- 테스트용 서명된 PDF 파일 (Adobe Acrobat이나 기타 전자 서명 도구로 만들 수 있습니다). + +위 항목 중 하나라도 없으면 먼저 NuGet 패키지를 설치하세요: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** .NET 6 이상을 대상으로 하면 최고의 성능과 장기 지원을 받을 수 있습니다. + +## 단계 1: PDF 문서 로드 + +가장 먼저 해야 할 일은 PDF 파일을 여는 것입니다. Aspose.PDF의 `Document` 클래스는 파싱부터 렌더링까지 모든 작업을 처리합니다. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Why this matters:* 파일을 로드하면 메모리 내에 문서 표현이 생성되어 파일 시스템에 다시 접근하지 않고도 서명을 조회할 수 있습니다. 또한 PDF 구조를 초기에 검증하므로 파일이 손상된 경우 즉시 예외가 발생합니다. + +## 단계 2: **PDF 서명 목록** – 모든 포함된 서명 열거 + +서명된 PDF는 여러 서명을 포함할 수 있습니다(예: 각 당사자가 다른 페이지에 서명하는 다중 페이지 계약). Aspose.PDF는 `Signatures` 컬렉션을 통해 이를 제공합니다. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*What you’re seeing:* 루프는 서명자의 이름, 이유, 위치, 타임스탬프와 같은 **PDF 서명 목록** 상세 정보를 출력합니다. 감사 로그나 UI 표시용으로 유용합니다. + +## 단계 3: **PDF 서명 검증** – 손상 여부 확인 + +이제 보안에 가장 중요한 단계입니다: 서명 후 문서가 변경되지 않았는지 확인합니다. 버전 25.3부터 Aspose.PDF는 `PdfSignatureValidator.IsCompromised` 플래그를 제공합니다. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Why you should use `IsCompromised`*: 기존 검증은 인증서 유효성, 폐기 여부 등 암호학적 체인만 확인합니다. `IsCompromised`는 서명 후 문서에 발생한 모든 변경을 감지하여 **PDF 서명 검증** 시 변조 여부를 정확히 파악할 수 있게 해줍니다. + +## 단계 4: 검증 결과 처리 + +결과에 따라 다른 작업을 수행할 수 있습니다. 아래 패턴을 필요에 맞게 조정해 보세요: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Edge case note:* PDF에 **인증된** 서명(문서를 잠그는 첫 번째 서명)이 포함된 경우, 이후 수정은 전체 파일을 무효화할 수 있습니다. `IsCompromised`가 `true`이면 언제나 위험 신호로 간주하세요. + +## 전체 작동 예제 + +모든 내용을 하나로 합친, 단일 프로그램 예제는 다음과 같습니다. 컴파일하고 실행하면 됩니다: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**예상 출력** (정상 서명 하나와 변조된 서명 하나가 있을 경우): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## 일반적인 함정 및 회피 방법 + +| 함정 | 발생 원인 | 해결 방법 | +|------|----------|----------| +| **Missing Aspose.PDF version** | `IsCompromised`가 25.3에 도입되었습니다. 오래된 패키지는 컴파일되지만 `MissingMethodException`을 발생시킵니다. | NuGet 참조를 `>= 25.3`으로 설정하세요. | +| **Null `SignatureInfo`** | 일부 PDF는 컬렉션에 나타나지만 실제 서명이 없는 빈 슬롯을 포함합니다. | 검증 전에 `if (signatureInfo != null)` 로 방어하세요. | +| **Performance hit on large PDFs** | 모든 서명을 검증할 때마다 전체 파일을 읽습니다. | `PdfSignatureValidator`를 캐시하거나, 불리언 요약만 필요할 경우 서명을 일괄 처리하세요. | +| **Certificate revocation not checked** | `IsCompromised`는 문서 변경만 알려주며 인증서 상태는 확인하지 않습니다. | 전체 PKI 검증을 위해 `PdfSignatureValidator.Validate()`를 `IsCompromised`와 함께 사용하세요. | + +## 솔루션 확장 + +UI에 **PDF 서명 목록**을 표시해야 한다면 `SignatureInfo` 객체를 데이터 그리드에 바인딩하면 됩니다. 검증 결과를 데이터베이스에 저장하고 싶나요? `isCompromised` 불리언 값을 서명자 이름 및 타임스탬프와 함께 직렬화하세요. + +다음과 같은 관련 주제도 살펴볼 수 있습니다: + +- **신뢰할 수 있는 루트 CA에 대한 PDF 서명 검증** (`validator.Validate()` 사용) +- **내장 인증서 상세 정보 추출** (`validator.Certificate` 사용) +- **Aspose.PDF로 디지털 서명 생성** (`PdfSignatureBuilder` 사용) + +## 결론 + +이제 Aspose.PDF for .NET을 사용해 **PDF 서명 검증**과 **PDF 서명 목록**을 손쉽게 수행하는 실전 엔드‑투‑엔드 방법을 갖추었습니다. 코드는 문서를 로드하고, 각 서명을 열거하며, `IsCompromised` 플래그를 확인하고, 결과에 따라 동작하는 과정을 명확하고 콘솔 친화적인 형식으로 보여줍니다. + +직접 서명된 PDF로 시도해 보고, 다중 서명을 실험하며, 로직을 문서 처리 파이프라인에 통합해 보세요. PDF 보안은 검증 수준에 달려 있으니, 체크를 철저히 하고 로그를 꼼꼼히 남기세요. + +질문이 있거나 멋진 사용 사례를 공유하고 싶다면 아래 댓글을 남기거나 GitHub에서 저에게 ping 주세요. 즐거운 코딩 되세요! + +![Validate PDF Signature](/images/validate-pdf-signature.png "Aspose.PDF를 사용해 C# 콘솔 앱으로 PDF 서명을 검증하는 스크린샷") + + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하며, 완전한 코드 예제와 단계별 설명을 제공해 추가 API 기능을 마스터하고 다양한 구현 방식을 탐색할 수 있도록 도와줍니다. + +- [PDF 검증 방법 – Aspose를 사용한 PDF 서명 검증](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Aspose.PDF .NET을 사용한 PDF 서명 정보 추출 – 단계별 가이드](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Aspose.PDF for .NET을 사용한 PDF 서명 필드에서 이미지 추출 – 단계별 가이드](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/korean/net/programming-with-operators/_index.md b/pdf/korean/net/programming-with-operators/_index.md index b7f4480864..bcb36e5147 100644 --- a/pdf/korean/net/programming-with-operators/_index.md +++ b/pdf/korean/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Aspose.PDF for .NET의 "연산자를 사용한 프로그래밍" 튜토리얼은 | [페이지에 XForm 그리기](./draw-xform-on-page/) | 이 포괄적인 단계별 가이드를 통해 Aspose.PDF for .NET을 사용하여 PDF로 XForms를 그리는 방법을 알아보세요. | | [PDF 연산자](./pdf-operators/) | Aspose.PDF for .NET에서 PDF 연산자를 사용하는 단계별 가이드입니다. PDF 페이지에 이미지를 추가하고 위치를 지정합니다. | | [PDF 파일에서 그래픽 개체 제거](./remove-graphics-objects/) Aspose.PDF for .NET을 사용하여 PDF 파일에서 그래픽 객체를 제거하는 방법을 단계별 가이드에서 알아보세요. PDF 조작 작업을 간소화하세요. | +| [C#에서 빈 PDF 사전 만들기 – 완전한 Aspose.Pdf 가이드](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Aspose.PDF for .NET을 사용하여 C#에서 빈 PDF 사전을 만드는 방법을 단계별로 안내합니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/korean/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/korean/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..1dcd9080af --- /dev/null +++ b/pdf/korean/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: C#에서 Aspose.Pdf를 사용하여 빈 PDF 사전을 생성합니다. PDF 조작을 위해 ExtGState 사전에 그래픽 상태를 + 추가하는 방법을 단계별로 배웁니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: ko +lastmod: 2026-07-26 +og_description: Aspose.Pdf for C#를 사용하여 빈 PDF 사전을 생성합니다. PDF에서 그래픽 상태를 수정하는 실습 가이드를 + 따라보세요. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: C#에서 빈 PDF 사전 만들기 – 전체 Aspose.Pdf 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: C#에서 빈 PDF 사전 만들기 – 완전한 Aspose.Pdf 가이드 +url: /ko/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 빈 PDF 사전 만들기 – 완전한 Aspose.Pdf 가이드 + +PDF의 그래픽 상태를 조정할 때 **빈 PDF 사전** 항목을 어떻게 만들 수 있을지 궁금했던 적 있나요? 당신만 그런 것이 아닙니다—많은 개발자들이 투명도나 블렌드 모드를 프로그래밍 방식으로 조정하려다 이 문제에 부딪힙니다. 이 튜토리얼에서는 Aspose.Pdf for C#을 사용한 구체적인 해결책을 단계별로 안내하며, 기존 PDF의 *ExtGState* 사전에 새로운 그래픽 상태를 삽입하는 방법을 정확히 보여드립니다. + +우리는 PDF 로드, 리소스 사전 접근, 새로운 **CosPdfDictionary** 생성, 그리고 변경 사항 저장까지 필요한 모든 과정을 다룰 것입니다. 최종적으로 PDF 그래픽 상태를 조정할 때 재사용 가능한 패턴을 얻게 됩니다. + +--- + +## 배울 내용 + +- Aspose.Pdf의 저수준 API를 사용해 **빈 PDF 사전** 객체를 **create empty PDF dictionary** 하는 방법. +- 스트로크/채우기 투명도와 블렌드 모드를 제어하는 **ExtGState 사전**의 역할. +- 사전이 없을 때를 포함한 엣지 케이스 처리를 포함한 C# PDF 조작 실전 팁. +- 프로젝트에 바로 복사‑붙여넣기 할 수 있는 완전한 실행 코드 샘플. + +### 사전 요구 사항 + +- .NET 6.0 이상 (코드는 .NET Framework 4.6+에서도 동작합니다). +- **Aspose.Pdf for .NET** 라이선스 사본 (무료 체험판으로 테스트 가능). +- C# 및 PDF 리소스·그래픽 상태와 같은 기본 개념에 대한 기본 지식. + +위 항목 중 익숙하지 않은 것이 있다면 걱정 마세요—NuGet(`Install-Package Aspose.Pdf`)을 통해 Aspose.Pdf를 설치하고 나머지는 일반 C# 코드만 있으면 됩니다. + +--- + +## 1단계 – PDF 문서 로드 + +먼저 편집하려는 파일을 나타내는 `Document` 객체가 필요합니다. `using` 블록으로 감싸면 올바른 해제가 보장됩니다. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*왜 중요한가*: 파일을 열면 내부 COS(Canonical Object Structure) 객체에 접근할 수 있게 되며, 여기서 **CosPdfDictionary**가 존재합니다. 문서 객체가 없으면 **ExtGState** 항목을 담고 있는 리소스 사전에 도달할 수 없습니다. + +--- + +## 2단계 – 첫 번째 페이지의 리소스 사전 접근 + +PDF 페이지는 폰트, 이미지, 그래픽 상태 등 리소스를 전용 사전에 저장합니다. 여기서는 간단히 첫 번째 페이지를 사용하지만, 어떤 페이지 인덱스에도 동일한 로직을 적용할 수 있습니다. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Pro tip*: PDF에 페이지마다 다른 리소스 세트가 있다면 수정이 필요한 각 페이지에 대해 이 블록을 반복하세요. `DictionaryEditor` 클래스는 COS 사전을 .NET `Dictionary`처럼 다룰 수 있게 해주는 편리한 래퍼입니다. + +--- + +## 3단계 – ExtGState 사전 가져오기 또는 초기화 + +**ExtGState 사전**은 이름이 지정된 그래픽 상태 객체(`GS0`, `GS1`, …)를 보관합니다. 일부 PDF에는 이미 존재하고, 일부는 없습니다. 우리는 안전하게 이를 가져오고, 필요하면 새로운 빈 사전을 생성합니다. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*왜 이렇게 하는가*: 존재하지 않는 **ExtGState 사전**에 그래픽 상태를 추가하려 하면 예외가 발생합니다. 이 방어적 검사는 어떤 입력 PDF에도 코드를 견고하게 만들어 줍니다. + +--- + +## 4단계 – CosPdfDictionary 로 새로운 그래픽 상태 만들기 + +이제 튜토리얼의 핵심 단계입니다: **빈 PDF 사전**을 만들어 맞춤형 그래픽 상태를 정의합니다. 스트로크 투명도(`CA`), 채우기 투명도(`ca`), 그리고 블렌드 모드(`BM`)를 설정합니다. 나중에 항목을 더 추가할 수 있도록 기본 세트만 제공합니다. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*설명*: +- `CA`와 `ca`는 각각 스트로크와 채우기 투명도를 제어하는 표준 PDF 키입니다. +- `BM`은 블렌드 모드를 선택합니다; 기본값은 “Normal”이지만 디자인 요구에 따라 “Multiply”, “Screen” 등을 사용할 수 있습니다. +- `CosPdfDictionary.CreateEmptyDictionary`를 사용해 **create empty PDF dictionary** 객체를 만든 뒤, 키/값 쌍을 채워 넣습니다. + +--- + +## 5단계 – 새로운 그래픽 상태를 ExtGState에 삽입 + +그래픽 상태가 준비되면 고유 이름(예: `GS0`)으로 **ExtGState 사전**에 추가하기만 하면 됩니다. 여러 상태를 추가하려면 접미사를 증가시키면 됩니다. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tip*: 추가하기 전에 `GS0`이 이미 존재하는지 확인해 덮어쓰는 것을 방지하세요. `if (!extGState.ContainsKey("GS0"))`와 같은 간단한 검사로 해결할 수 있습니다. + +--- + +## 6단계 – 수정된 PDF 저장 + +모든 변경 사항은 메모리 상에만 존재합니다. 작업 흐름에 맞는 출력 경로를 선택해 영구 저장하세요. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Result*: `output.pdf`를 어떤 PDF 뷰어에서 열고 페이지 리소스를 검사하면(예: PDF 인스펙터 도구 사용) **ExtGState** 아래에 `GS0`이라는 새 항목이 정의한 파라미터와 함께 나타납니다. + +--- + +## 전체 작업 예제 + +모든 코드를 합치면 아래와 같이 복사‑붙여넣기 가능한 완전한 프로그램이 됩니다: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**예상 출력**: `output.pdf`는 원본과 동일하게 렌더링되지만, 이후에 `GS0`을 참조하는 콘텐츠(예: 콘텐츠 스트림의 `gs` 연산자)가 정의된 투명도와 블렌드 모드를 적용받게 됩니다. 아직 해당 참조가 없다면 수동으로 추가하거나 Aspose의 고수준 API를 통해 삽입할 수 있습니다. + +--- + +## 자주 묻는 질문 및 엣지 케이스 + +| 질문 | 답변 | +|----------|--------| +| *PDF에 이미 `GS0`이라는 `ExtGState` 항목이 존재한다면 어떻게 하나요?* | 추가하기 전에 `extGState.ContainsKey("GS0")`를 확인하세요. 존재한다면 의도적으로 덮어쓰기(`extGState["GS0"] = newGraphicsState`)하거나 `GS1`과 같은 새 이름을 선택하면 됩니다. | +| *라인 두께(`LW`)나 대시 패턴(`D`) 같은 파라미터를 더 추가할 수 있나요?* | 물론 가능합니다. `parameters` 배열에 추가 `KeyValuePair` 항목을 넣어 확장하면 됩니다. | +| *암호화된 PDF에도 이 방법을 사용할 수 있나요?* | 네, `Document`를 생성할 때 올바른 비밀번호를 제공하면 됩니다(`new Document(path, password)`). | +| *문서를 수동으로 닫아야 하나요?* | `using` 구문이 자동으로 해제를 처리하므로 별도 닫기가 필요 없습니다. 이는 보류 중인 변경 사항도 플러시합니다. | +| *고수준 `Graphics` 클래스를 사용하는 것과는 어떻게 다른가요?* | 고수준 API는 내부 사전을 추상화해 간단한 작업에 편리합니다. 그러나 맞춤 블렌드 모드와 같이 그래픽 상태를 세밀하게 제어해야 할 경우, 저수준 **CosPdfDictionary**를 직접 다루어 **create empty PDF dictionary** 객체를 만들어야 합니다. | + +--- + +## 결론 + +우리는 Aspose.Pdf를 사용해 **빈 PDF 사전** 객체를 **create empty PDF dictionary** 하고, 맞춤 그래픽 상태를 **ExtGState 사전**에 삽입한 뒤, 수정된 파일을 저장하는 전체 과정을 깔끔하고 관용적인 C# 코드로 시연했습니다. 이 패턴을 통해 투명도, 블렌드 모드 및 PDF 사양에 정의된 기타 그래픽 상태 파라미터를 정밀하게 제어할 수 있습니다. + +다음과 같은 활용이 가능합니다: + +- `gs` 연산자를 사용해 기존 페이지 콘텐츠에 새로운 그래픽 상태 적용. +- 브랜드 또는 워터마크용 재사용 가능한 그래픽 상태 라이브러리 구축. +- + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하여 관련 주제를 깊이 있게 다룹니다. 각 자료는 완전한 코드 예제와 단계별 설명을 포함해 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Aspose.PDF for .NET을 사용해 PDF에서 점선 만들기: 단계별 가이드](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Aspose.PDF for .NET을 사용해 PDF에 사각형 만들기 및 채우기: 단계별 가이드](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/polish/net/digital-signatures/_index.md b/pdf/polish/net/digital-signatures/_index.md index 38fd2f4ad4..982a8897ac 100644 --- a/pdf/polish/net/digital-signatures/_index.md +++ b/pdf/polish/net/digital-signatures/_index.md @@ -64,6 +64,9 @@ Dowiedz się, jak wczytać dokument PDF w C#, przekonwertować go do formatu PDF ### [Weryfikacja podpisu PDF za pomocą Aspose – konwersja PDF do HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Dowiedz się, jak zweryfikować podpis PDF i jednocześnie przekonwertować dokument do formatu HTML przy użyciu Aspose.PDF. +### [Walidacja podpisu PDF i lista podpisów PDF przy użyciu Aspose.PDF – Kompletny przewodnik](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Dowiedz się, jak zweryfikować podpis PDF oraz wyświetlić listę podpisów w dokumencie przy użyciu Aspose.PDF dla .NET. + ## Dodatkowe zasoby - [Aspose.PDF dla dokumentacji sieciowej](https://docs.aspose.com/pdf/net/) diff --git a/pdf/polish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/polish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..100a4a739a --- /dev/null +++ b/pdf/polish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-07-26 +description: Sprawdź podpis PDF i wyświetl listę podpisów PDF przy użyciu Aspose.PDF + w C#. Krok po kroku kod, pułapki oraz najlepsze praktyki w bezpiecznym zarządzaniu + dokumentami. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: pl +lastmod: 2026-07-26 +og_description: Sprawdź podpis PDF i wyświetl listę podpisów PDF za pomocą Aspose.PDF. + Skorzystaj z tego praktycznego przewodnika, aby zabezpieczyć pliki PDF w C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Sprawdź podpis PDF i wyświetl listę podpisów PDF – Aspose.PDF How‑to +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Walidacja podpisu PDF i lista podpisów PDF w Aspose.PDF – Kompletny przewodnik +url: /pl/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Walidacja podpisu PDF i lista podpisów PDF przy użyciu Aspose.PDF – Kompletny przewodnik + +Zastanawiałeś się kiedyś, jak **zweryfikować podpis PDF** w aplikacji .NET bez utraty włosów? Nie jesteś jedyny. Niezależnie od tego, czy budujesz platformę e‑sign, czy po prostu musisz upewnić się, że otrzymany kontrakt nie został podrobiony, możliwość **wyświetlenia listy podpisów PDF** i weryfikacji każdego z nich to niezbędna umiejętność. + +W tym samouczku przeprowadzimy Cię przez w pełni działający przykład, który ładuje podpisany PDF, wylicza wszystkie osadzone podpisy, sprawdza, czy którykolwiek z nich został naruszony, i wypisuje czytelny wynik w konsoli. Bez niejasnych odniesień — tylko kod, który możesz skopiować i wkleić, oraz wyjaśnienie „dlaczego” każdego kroku. + +## Wymagania wstępne + +- **Aspose.PDF for .NET** version 25.3 lub nowszy (właściwość `IsCompromised` pojawiła się w wersji 25.3). +- Środowisko programistyczne .NET (Visual Studio 2022, Rider lub interfejs wiersza poleceń `dotnet`). +- Plik PDF z podpisem, którym możesz przetestować (możesz go utworzyć w Adobe Acrobat lub dowolnym narzędziu e‑signature). + +Jeśli którekolwiek z powyższych jest nieobecne, najpierw zainstaluj pakiet NuGet: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Wskazówka:** Ustaw docelową wersję .NET 6 lub nowszą, aby uzyskać najlepszą wydajność i długoterminowe wsparcie. + +## Krok 1: Załaduj dokument PDF + +Pierwszą rzeczą, którą musisz zrobić, jest otwarcie pliku PDF. Klasa `Document` z Aspose.PDF obsługuje wszystko, od parsowania po renderowanie. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Dlaczego to ważne:* Ładowanie pliku tworzy reprezentację w pamięci, co pozwala na zapytania o podpisy bez ponownego odwoływania się do systemu plików. Dodatkowo wczesna walidacja struktury PDF powoduje, że od razu otrzymasz wyjątek, jeśli plik jest uszkodzony. + +## Krok 2: **Lista podpisów PDF** – Wylicz wszystkie osadzone podpisy + +Podpisany PDF może zawierać wiele podpisów (np. wielostronicowy kontrakt, w którym każda ze stron podpisuje inną stronę). Aspose.PDF udostępnia je poprzez kolekcję `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Co widzisz:* Pętla wypisuje szczegóły **list PDF signatures**, takie jak imię i nazwisko podpisującego, powód, lokalizacja i znacznik czasu. Jest to przydatne do logów audytu lub wyświetlania w interfejsie użytkownika. + +## Krok 3: **Walidacja podpisu PDF** – Sprawdź, czy został naruszony + +Teraz nadchodzi krytyczna pod względem bezpieczeństwa część: potwierdzenie, że żaden z podpisów nie został zmieniony po podpisaniu. Od wersji 25.3 Aspose.PDF udostępnia flagę `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Dlaczego warto używać `IsCompromised`*: Tradycyjna walidacja sprawdza tylko łańcuch kryptograficzny (ważność certyfikatu, odwołanie itp.). `IsCompromised` dodaje dodatkową warstwę, wykrywając wszelkie zmiany w dokumencie po podpisaniu — dokładnie to, czego potrzebujesz przy **walidacji podpisu PDF** pod kątem manipulacji. + +## Krok 4: Obsługa wyników walidacji + +W zależności od wyniku możesz podjąć różne działania. Oto szybki wzorzec, który możesz dostosować: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Uwaga o przypadkach brzegowych:* Jeśli PDF zawiera **certyfikowany** podpis (pierwszy podpis, który blokuje dokument), późniejsza modyfikacja może unieważnić cały plik, nawet jeśli kolejne podpisy wydają się poprawne. Zawsze traktuj wartość `true` zwróconą przez `IsCompromised` jako sygnał alarmowy. + +## Pełny działający przykład + +Łącząc wszystko razem, oto pojedynczy, samodzielny program, który możesz skompilować i uruchomić: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Oczekiwany wynik** (zakładając jeden prawidłowy podpis i jeden zmodyfikowany): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Typowe pułapki i jak ich uniknąć + +| Pułapka | Dlaczego się dzieje | Rozwiązanie | +|---------|----------------------|-------------| +| **Brak wersji Aspose.PDF** | `IsCompromised` zostało wprowadzone w wersji 25.3. Starsze pakiety kompilują się, ale rzucają `MissingMethodException`. | Upewnij się, że odwołanie NuGet ma wersję `>= 25.3`. | +| **Null `SignatureInfo`** | Niektóre PDF-y mają puste miejsca na podpis, które nadal pojawiają się w kolekcji. | Sprawdź `if (signatureInfo != null)` przed walidacją. | +| **Spadek wydajności przy dużych PDF-ach** | Walidacja każdego podpisu odczytuje cały plik przy każdym wywołaniu. | Zachowaj w pamięci (cache) `PdfSignatureValidator` lub przetwarzaj podpisy partiami, jeśli potrzebujesz tylko podsumowania boolean. | +| **Brak sprawdzania odwołania certyfikatu** | `IsCompromised` informuje jedynie o zmianach w dokumencie, nie o statusie certyfikatu. | Użyj `PdfSignatureValidator.Validate()` oprócz `IsCompromised` dla pełnych kontroli PKI. | + +## Rozszerzanie rozwiązania + +Jeśli potrzebujesz **list PDF signatures** w interfejsie użytkownika, po prostu przekaz `SignatureInfo` do siatki danych. Chcesz przechowywać wyniki walidacji w bazie danych? Serializuj wartość boolean `isCompromised` razem z nazwą podpisującego i znacznikiem czasu. + +Inne powiązane tematy, które możesz zbadać dalej: + +- [Jak zweryfikować PDF – Walidacja podpisu PDF przy użyciu Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Jak wyodrębnić informacje o podpisie PDF przy użyciu Aspose.PDF .NET: Przewodnik krok po kroku](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Jak wyodrębnić obrazy z pól podpisu PDF przy użyciu Aspose.PDF dla .NET: Przewodnik krok po kroku](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +![Walidacja podpisu PDF](/images/validate-pdf-signature.png "Zrzut ekranu aplikacji konsolowej C# walidującej podpis PDF przy użyciu Aspose.PDF") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/polish/net/programming-with-operators/_index.md b/pdf/polish/net/programming-with-operators/_index.md index 29f5701327..b5f5679265 100644 --- a/pdf/polish/net/programming-with-operators/_index.md +++ b/pdf/polish/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ Samouczki „Programowanie z operatorami” Aspose.PDF for .NET przeprowadzą Ci | --- | --- | | [Narysuj XForm na stronie](./draw-xform-on-page/) | dowiedz się, jak rysować formularze XForm w formacie PDF za pomocą Aspose.PDF dla platformy .NET dzięki temu kompleksowemu przewodnikowi krok po kroku. | | [Operatorzy PDF](./pdf-operators/) | Przewodnik krok po kroku dotyczący korzystania z operatorów PDF w Aspose.PDF dla platformy .NET. Dodaj obraz do strony PDF i określ jego pozycję. | -| [Usuń obiekty graficzne w pliku PDF](./remove-graphics-objects/) Dowiedz się, jak usuwać obiekty graficzne z pliku PDF za pomocą Aspose.PDF dla .NET w tym przewodniku krok po kroku. Uprość swoje zadania związane z manipulacją PDF. | +| [Usuń obiekty graficzne w pliku PDF](./remove-graphics-objects/) | Dowiedz się, jak usuwać obiekty graficzne z pliku PDF za pomocą Aspose.PDF dla .NET w tym przewodniku krok po kroku. Uprość swoje zadania związane z manipulacją PDF. | +| [Utwórz pusty słownik PDF w C# – Kompletny przewodnik Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Kompletny przewodnik, jak w C# utworzyć pusty słownik PDF przy użyciu Aspose.PDF dla .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/polish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/polish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..1faaa9e95d --- /dev/null +++ b/pdf/polish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-26 +description: Utwórz pusty słownik PDF przy użyciu Aspose.Pdf w C#. Dowiedz się krok + po kroku, jak dodać stan graficzny do słownika ExtGState w celu manipulacji PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: pl +lastmod: 2026-07-26 +og_description: Utwórz pusty słownik PDF przy użyciu Aspose.Pdf dla C#. Skorzystaj + z tego praktycznego przewodnika, aby modyfikować stany graficzne w swoich plikach + PDF. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Utwórz pusty słownik PDF w C# – Pełny poradnik Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Utwórz pusty słownik PDF w C# – Kompletny przewodnik Aspose.Pdf +url: /pl/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tworzenie pustego słownika PDF w C# – Kompletny przewodnik Aspose.Pdf + +Zastanawiałeś się kiedyś, jak **utworzyć puste wpisy słownika PDF** podczas modyfikacji stanu graficznego PDF? Nie jesteś sam — wielu programistów napotyka ten problem, próbując programowo dostosować przezroczystość lub tryby mieszania. W tym tutorialu przeprowadzimy Cię przez konkretne rozwiązanie z użyciem Aspose.Pdf dla C#, pokazując dokładnie, jak wstrzyknąć nowy stan graficzny do słownika *ExtGState* istniejącego PDF‑a. + +Omówimy wszystko, czego potrzebujesz: wczytanie PDF‑a, dostęp do jego słownika zasobów, budowanie nowego **CosPdfDictionary**, a na końcu zapisanie zmian. Po zakończeniu będziesz mieć gotowy wzorzec do dowolnych modyfikacji *stanu graficznego PDF*. + +--- + +## Czego się nauczysz + +- Jak **tworzyć puste słowniki PDF** przy użyciu niskopoziomowego API Aspose.Pdf. +- Rolę słownika **ExtGState** w kontrolowaniu przezroczystości linii/wypełnienia oraz trybów mieszania. +- Praktyczne wskazówki dotyczące manipulacji PDF w C#, w tym obsługę sytuacji brzegowych, gdy słownik nie istnieje. +- Kompletny, gotowy do uruchomienia przykład kodu, który możesz skopiować i wkleić do swojego projektu. + +### Wymagania wstępne + +- .NET 6.0 lub nowszy (kod działa także z .NET Framework 4.6+). +- Licencjonowana kopia **Aspose.Pdf for .NET** (bezpłatna wersja próbna wystarczy do testów). +- Podstawowa znajomość C# oraz koncepcji PDF, takich jak zasoby i stany graficzne. + +Jeśli któryś z tych punktów jest Ci nieznany, nie panikuj — możesz zainstalować Aspose.Pdf przez NuGet (`Install-Package Aspose.Pdf`), a reszta to czysty C#. + +--- + +## Krok 1 – Wczytaj dokument PDF + +Na początek potrzebujesz obiektu `Document`, który reprezentuje plik, który chcesz edytować. Umieszczenie go w bloku `using` zapewnia prawidłowe zwolnienie zasobów. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Dlaczego to ważne*: Otwarcie pliku daje dostęp do wewnętrznych obiektów COS (Canonical Object Structure), w których znajduje się **CosPdfDictionary**. Bez obiektu dokumentu nie możesz dotrzeć do słowników zasobów, w których przechowywane są wpisy **ExtGState**. + +--- + +## Krok 2 – Uzyskaj słownik zasobów pierwszej strony + +Strony PDF przechowują swoje zasoby (czcionki, obrazy, stany graficzne itp.) w dedykowanym słowniku. Dla uproszczenia pobierzemy pierwszą stronę, ale ta sama logika działa dla dowolnego indeksu strony. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Wskazówka*: Jeśli Twój PDF ma wiele stron z różnymi zestawami zasobów, powtórz ten blok dla każdej strony, którą musisz zmodyfikować. Klasa `DictionaryEditor` jest wygodnym wrapperem, który pozwala traktować słownik COS jak .NET‑owy `Dictionary`. + +--- + +## Krok 3 – Pobierz lub zainicjuj słownik ExtGState + +Słownik **ExtGState** przechowuje nazwane obiekty stanu graficznego (`GS0`, `GS1`, …). Niektóre PDF‑y już go zawierają; inne nie. Bezpiecznie go pobierzemy, tworząc nowy pusty, jeśli będzie to konieczne. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Dlaczego to robimy*: Próba dodania stanu graficznego do nieistniejącego słownika **ExtGState** spowodowałaby wyjątek. Ten defensywny sprawdzian czyni kod odpornym na każdy wejściowy PDF. + +--- + +## Krok 4 – Zbuduj nowy stan graficzny przy użyciu CosPdfDictionary + +Teraz najważniejsza część tutorialu: **tworzenie pustego słownika PDF**, który definiuje własny stan graficzny. Ustawimy przezroczystość linii (`CA`), przezroczystość wypełnienia (`ca`) oraz tryb mieszania (`BM`). Później możesz dodać kolejne wpisy — to tylko podstawowy zestaw. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Wyjaśnienie*: +- `CA` i `ca` to standardowe klucze PDF kontrolujące odpowiednio przezroczystość linii i wypełnienia. +- `BM` wybiera tryb mieszania; „Normal” jest domyślny, ale możesz użyć „Multiply”, „Screen” itp., w zależności od potrzeb projektu. +- Używając `CosPdfDictionary.CreateEmptyDictionary`, **tworzymy puste słowniki PDF**, które później wypełniamy parami klucz/wartość. + +--- + +## Krok 5 – Wstaw nowy stan graficzny do ExtGState + +Gdy stan graficzny jest gotowy, po prostu dodajemy go do słownika **ExtGState** pod unikalną nazwą (np. `GS0`). Jeśli planujesz dodać wiele stanów, po prostu zwiększaj sufiks. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Wskazówka*: Przed dodaniem warto sprawdzić, czy `GS0` już istnieje, aby nie nadpisać istniejącego wpisu. Proste zabezpieczenie `if (!extGState.ContainsKey("GS0"))` rozwiązuje problem. + +--- + +## Krok 6 – Zapisz zmodyfikowany PDF + +Wszystkie zmiany istnieją w pamięci, dopóki ich nie zapiszesz. Wybierz ścieżkę wyjściową, która pasuje do Twojego workflow. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Rezultat*: Otwórz `output.pdf` w dowolnym przeglądarce PDF, a następnie sprawdź zasoby strony (np. przy pomocy narzędzia do inspekcji PDF). Zobaczysz nowy wpis w **ExtGState** o nazwie `GS0` z zdefiniowanymi parametrami. + +--- + +## Pełny działający przykład + +Łącząc wszystko razem, oto kompletny program gotowy do skopiowania i wklejenia: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Oczekiwany wynik**: `output.pdf` będzie wyglądał dokładnie tak samo jak oryginał, ale każdy element, który później odwoła się do `GS0` (np. operator `gs` w strumieniu zawartości), przyjmie zdefiniowaną przezroczystość i tryb mieszania. Jeśli jeszcze nie masz takiego odwołania, możesz dodać je ręcznie lub przy użyciu wyższopoziomowych API Aspose. + +--- + +## Najczęściej zadawane pytania i przypadki brzegowe + +| Pytanie | Odpowiedź | +|----------|-----------| +| *Co zrobić, gdy PDF już zawiera wpis ExtGState o nazwie `GS0`?* | Sprawdź `extGState.ContainsKey("GS0")` przed dodaniem. Jeśli istnieje, możesz celowo nadpisać (`extGState["GS0"] = newGraphicsState`) lub wybrać nową nazwę, np. `GS1`. | +| *Czy mogę dodać więcej parametrów, np. grubość linii (`LW`) lub wzór kreski (`D`)?* | Oczywiście. Po prostu rozbuduj tablicę `parameters` o dodatkowe elementy `KeyValuePair`. | +| *Czy to podejście działa z zaszyfrowanymi PDF‑ami?* | Tak, pod warunkiem podania prawidłowego hasła przy tworzeniu obiektu `Document` (`new Document(path, password)`). | +| *Czy muszę ręcznie zamykać dokument?* | Instrukcja `using` zajmuje się zwolnieniem zasobów, co jednocześnie zapisuje ewentualne zmiany. | +| *Czym różni się to od użycia wysokopoziomowej klasy `Graphics`?* | API wysokiego poziomu ukrywa szczegóły słowników, co jest wygodne przy prostych zadaniach. Gdy potrzebna jest precyzyjna kontrola nad stanami graficznymi — np. własne tryby mieszania — musisz pracować z niskopoziomowym **CosPdfDictionary**, czyli **tworzyć puste słowniki PDF** bezpośrednio. | + +--- + +## Zakończenie + +Pokazaliśmy, jak **tworzyć puste słowniki PDF** przy pomocy Aspose.Pdf, wstrzyknąć własny stan graficzny do **słownika ExtGState** i zapisać zmodyfikowany plik — wszystko w czystym, idiomatycznym C#. Ten wzorzec otwiera precyzyjną kontrolę nad przezroczystością, trybami mieszania i innymi parametrami stanu graficznego określonymi w specyfikacji PDF. + +Od tego momentu możesz: + +- Zastosować nowy stan graficzny do istniejącej zawartości strony przy użyciu operatora `gs`. +- Zbudować bibliotekę wielokrotnego użytku stanów graficznych dla brandingu lub znaków wodnych. +- + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu oraz szczegółowe wyjaśnienia, pomagające opanować dodatkowe funkcje API i eksplorować alternatywne podejścia w własnych projektach. + +- [Jak tworzyć przerywane linie w PDF‑ach przy użyciu Aspose.PDF dla .NET: przewodnik krok po kroku](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Tworzenie i wypełnianie prostokątów w PDF‑ach przy użyciu Aspose.PDF dla .NET: przewodnik krok po kroku](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/portuguese/net/digital-signatures/_index.md b/pdf/portuguese/net/digital-signatures/_index.md index 2a6e4f62c0..c55f8b7c1e 100644 --- a/pdf/portuguese/net/digital-signatures/_index.md +++ b/pdf/portuguese/net/digital-signatures/_index.md @@ -64,6 +64,9 @@ Aprenda a carregar um PDF em C#, convertê‑lo para o padrão PDF/X‑4 e lista ### [Validar assinatura PDF com Aspose – Converter PDF para HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Aprenda a validar assinaturas PDF e converter documentos PDF para HTML usando Aspose.PDF. +### [Validar assinatura de PDF e listar assinaturas de PDF com Aspose.PDF – Guia completo](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Aprenda a validar assinaturas de PDF e listar todas as assinaturas presentes usando Aspose.PDF para .NET. + ## Recursos adicionais - [Aspose.PDF para documentação da Net](https://docs.aspose.com/pdf/net/) diff --git a/pdf/portuguese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/portuguese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..d97b88dbb7 --- /dev/null +++ b/pdf/portuguese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-07-26 +description: Validar assinatura de PDF e listar assinaturas de PDF usando Aspose.PDF + em C#. Código passo a passo, armadilhas e melhores práticas para o manuseio seguro + de documentos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: pt +lastmod: 2026-07-26 +og_description: Valide a assinatura de PDF e liste assinaturas de PDF com Aspose.PDF. + Siga este guia prático para proteger PDFs em C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Validar assinatura PDF e listar assinaturas PDF – Como fazer no Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Validar assinatura de PDF e listar assinaturas de PDF com Aspose.PDF – Guia + completo +url: /pt/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Validar Assinatura PDF e Listar Assinaturas PDF com Aspose.PDF – Guia Completo + +Já se perguntou como **validar assinatura PDF** em um aplicativo .NET sem perder a cabeça? Você não está sozinho. Seja você quem está construindo uma plataforma de assinatura eletrônica ou apenas precisa garantir que um contrato recebido não foi adulterado, ser capaz de **listar assinaturas PDF** e verificar cada uma delas é uma habilidade indispensável. + +Neste tutorial vamos percorrer um exemplo totalmente executável que carrega um PDF assinado, enumera todas as assinaturas incorporadas, verifica se alguma delas foi comprometida e imprime um resultado claro no console. Sem referências vagas — apenas o código que você pode copiar‑colar, além do “porquê” de cada passo. + +## Pré‑requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +- **Aspose.PDF for .NET** versão 25.3 ou mais recente (a propriedade `IsCompromised` apareceu na 25.3). +- Um ambiente de desenvolvimento .NET (Visual Studio 2022, Rider ou a CLI `dotnet`). +- Um arquivo PDF assinado para testar (você pode criar um com o Adobe Acrobat ou qualquer ferramenta de assinatura eletrônica). + +Se algum desses itens estiver faltando, instale o pacote NuGet primeiro: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Dica de especialista:** Alvo .NET 6 ou superior para obter o melhor desempenho e suporte de longo prazo. + +## Etapa 1: Carregar o Documento PDF + +A primeira coisa que você precisa fazer é abrir o arquivo PDF. A classe `Document` do Aspose.PDF cuida de tudo, desde a análise até a renderização. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Por que isso importa:* Carregar o arquivo cria uma representação em memória que permite consultar assinaturas sem tocar novamente no sistema de arquivos. Também valida a estrutura do PDF logo no início, de modo que você receberá uma exceção imediatamente se o arquivo estiver corrompido. + +## Etapa 2: **Listar Assinaturas PDF** – Enumerar Todas as Assinaturas Incorporadas + +Um PDF assinado pode conter várias assinaturas (pense em um contrato de várias páginas onde cada parte assina uma página diferente). O Aspose.PDF as expõe através da coleção `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*O que você está vendo:* O loop imprime os detalhes da **lista de assinaturas PDF**, como o nome do assinante, motivo, local e carimbo de data/hora. Isso é útil para logs de auditoria ou exibições em UI. + +## Etapa 3: **Validar Assinatura PDF** – Verificar Comprometimento + +Agora vem a parte crítica de segurança: confirmar que nenhuma das assinaturas foi alterada após a assinatura. A partir da versão 25.3, o Aspose.PDF fornece a flag `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Por que usar `IsCompromised`*: A validação tradicional verifica apenas a cadeia criptográfica (validade do certificado, revogação etc.). `IsCompromised` adiciona uma camada extra detectando quaisquer alterações pós‑assinatura no documento — exatamente o que você precisa ao **validar assinatura PDF** contra adulteração. + +## Etapa 4: Tratamento dos Resultados da Validação + +Dependendo do resultado, você pode querer tomar ações diferentes. Aqui está um padrão rápido que você pode adaptar: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Observação de caso extremo:* Se um PDF contém uma assinatura **certificada** (a primeira assinatura que bloqueia o documento), uma modificação posterior pode invalidar todo o arquivo, mesmo que assinaturas subsequentes pareçam corretas. Sempre trate qualquer `true` de `IsCompromised` como um sinal de alerta. + +## Exemplo Completo Funcionando + +Juntando tudo, aqui está um programa único, autocontido, que você pode compilar e executar: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Saída esperada** (supondo uma assinatura boa e uma adulterada): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Armadilhas Comuns & Como Evitá‑las + +| Armadilha | Por que acontece | Solução | +|-----------|------------------|---------| +| **Versão do Aspose.PDF ausente** | `IsCompromised` foi introduzido na 25.3. Pacotes mais antigos compilam, mas lançam `MissingMethodException`. | Garanta que sua referência NuGet seja `>= 25.3`. | +| **`SignatureInfo` nulo** | Alguns PDFs têm slots de assinatura vazios que ainda aparecem na coleção. | Proteja com `if (signatureInfo != null)` antes da validação. | +| **Impacto de desempenho em PDFs grandes** | Validar cada assinatura lê o arquivo inteiro a cada vez. | Cache o `PdfSignatureValidator` ou processe assinaturas em lote se precisar apenas de um resumo booleano. | +| **Revogação de certificado não verificada** | `IsCompromised` informa apenas sobre alterações no documento, não sobre o status do certificado. | Use `PdfSignatureValidator.Validate()` além de `IsCompromised` para verificações PKI completas. | + +## Expandindo a Solução + +Se precisar **listar assinaturas PDF** em uma UI, basta alimentar os objetos `SignatureInfo` em um grid de dados. Quer armazenar resultados de validação em um banco? Serialize o booleano `isCompromised` junto com o nome do assinante e o carimbo de data/hora. + +Outros tópicos relacionados que você pode explorar a seguir: + +- **Validar assinatura PDF contra uma CA raiz confiável** (use `validator.Validate()`). +- **Extrair detalhes do certificado incorporado** (`validator.Certificate`). +- **Criar assinaturas digitais** com Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusão + +Agora você tem um método prático, de ponta a ponta, para **validar assinatura PDF** e **listar assinaturas PDF** usando Aspose.PDF para .NET. O código mostra exatamente como carregar um documento, enumerar cada assinatura, checar a flag `IsCompromised` e agir com base no resultado — tudo em um formato claro e amigável ao console. + +Experimente com seus próprios PDFs assinados, teste múltiplas assinaturas e integre a lógica ao seu pipeline maior de processamento de documentos. PDFs seguros são tão fortes quanto a validação que você realiza, então mantenha as verificações rigorosas e os logs detalhados. + +Tem dúvidas ou quer compartilhar um caso de uso interessante? Deixe um comentário abaixo ou me chame no GitHub. Boa codificação! + +![Validate PDF Signature](/images/validate-pdf-signature.png "Screenshot of a C# console app validating a PDF signature with Aspose.PDF") + + +## O Que Você Deve Aprender a Seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [How to Verify PDF – Validate PDF Signature with Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [How to Extract PDF Signature Information Using Aspose.PDF .NET: A Step-by-Step Guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [How to Extract Images from PDF Signature Fields using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/portuguese/net/programming-with-operators/_index.md b/pdf/portuguese/net/programming-with-operators/_index.md index ad752bd34d..514d0e0cec 100644 --- a/pdf/portuguese/net/programming-with-operators/_index.md +++ b/pdf/portuguese/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Os tutoriais "Programação com Operadores" do Aspose.PDF para .NET guiam você | [Desenhar XForm na página](./draw-xform-on-page/) | Aprenda a desenhar XForms em PDF usando Aspose.PDF para .NET com este guia passo a passo abrangente. | | [Operadores de PDF](./pdf-operators/) | Guia passo a passo para usar operadores PDF com Aspose.PDF para .NET. Adicione uma imagem a uma página PDF e especifique sua posição. | | [Remover objetos gráficos em arquivo PDF](./remove-graphics-objects/) Aprenda a remover objetos gráficos de um arquivo PDF usando o Aspose.PDF para .NET neste guia passo a passo. Simplifique suas tarefas de manipulação de PDF. | +| [Criar Dicionário PDF Vazio em C# – Guia Completo Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Aprenda a criar um dicionário PDF vazio usando Aspose.PDF para .NET em C# neste guia completo. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/portuguese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/portuguese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..ca734e7c5b --- /dev/null +++ b/pdf/portuguese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: Crie um dicionário PDF vazio com Aspose.Pdf em C#. Aprenda passo a passo + como adicionar um estado gráfico ao dicionário ExtGState para manipulação de PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: pt +lastmod: 2026-07-26 +og_description: Crie um dicionário PDF vazio usando Aspose.Pdf para C#. Siga este + guia prático para modificar os estados gráficos em seus PDFs. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Criar Dicionário PDF Vazio em C# – Tutorial Completo do Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Criar Dicionário PDF Vazio em C# – Guia Completo do Aspose.Pdf +url: /pt/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar Dicionário PDF Vazio em C# – Guia Completo do Aspose.Pdf + +Já se perguntou como **create empty PDF dictionary** entradas ao ajustar o estado gráfico de um PDF? Você não está sozinho — muitos desenvolvedores encontram esse obstáculo ao tentar modificar opacidade ou modos de mesclagem programaticamente. Neste tutorial vamos percorrer uma solução concreta usando Aspose.Pdf para C#, mostrando exatamente como inserir um novo estado gráfico no dicionário *ExtGState* de um PDF existente. + +Cobriremos tudo o que você precisa: carregar um PDF, acessar seu dicionário de recursos, construir um novo **CosPdfDictionary**, e finalmente persistir as alterações. Ao final, você terá um padrão reutilizável para quaisquer ajustes de *PDF graphics state* que precisar. + +--- + +## O que Você Vai Aprender + +- Como **create empty PDF dictionary** objetos com a API de baixo nível do Aspose.Pdf. +- O papel do dicionário **ExtGState** no controle da opacidade de traço/preenchimento e dos modos de mesclagem. +- Dicas práticas para manipulação de PDFs em C#, incluindo tratamento de casos extremos quando o dicionário está ausente. +- Um exemplo completo e executável que você pode copiar‑colar no seu projeto. + +### Pré‑requisitos + +- .NET 6.0 ou superior (o código também funciona com .NET Framework 4.6+). +- Uma cópia licenciada do **Aspose.Pdf for .NET** (a versão de avaliação gratuita serve para testes). +- Familiaridade básica com C# e conceitos de PDF como recursos e estados gráficos. + +Se algum desses itens lhe for desconhecido, não entre em pânico — você pode instalar o Aspose.Pdf via NuGet (`Install-Package Aspose.Pdf`) e o resto é apenas C# puro. + +--- + +## Etapa 1 – Carregar o Documento PDF + +Primeiro de tudo, você precisa de um objeto `Document` que represente o arquivo que deseja editar. Envolvê‑lo em um bloco `using` garante a liberação correta dos recursos. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Por que isso importa*: Abrir o arquivo lhe dá acesso aos objetos internos COS (Canonical Object Structure), onde o **CosPdfDictionary** reside. Sem o objeto de documento, você não consegue alcançar os dicionários de recursos que contêm as entradas **ExtGState**. + +--- + +## Etapa 2 – Acessar o Dicionário de Recursos da Primeira Página + +As páginas PDF armazenam seus recursos (fonts, imagens, estados gráficos, etc.) em um dicionário dedicado. Vamos pegar a primeira página para simplificar, mas a mesma lógica se aplica a qualquer índice de página. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Dica de especialista*: Se o seu PDF tem várias páginas com conjuntos de recursos diferentes, repita este bloco para cada página que precisar modificar. A classe `DictionaryEditor` é um wrapper conveniente que permite tratar o dicionário COS como um `Dictionary` do .NET. + +--- + +## Etapa 3 – Recuperar ou Inicializar o Dicionário ExtGState + +O dicionário **ExtGState** contém objetos de estado gráfico nomeados (`GS0`, `GS1`, …). Alguns PDFs já o possuem; outros não. Vamos buscá‑lo com segurança, criando um novo vazio se necessário. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Por que fazemos isso*: Tentar adicionar um estado gráfico a um **ExtGState** inexistente lançaria uma exceção. Essa verificação defensiva torna o código robusto para qualquer PDF de entrada. + +--- + +## Etapa 4 – Construir um Novo Estado Gráfico com CosPdfDictionary + +Agora vem o coração do tutorial: **create empty PDF dictionary** que define um estado gráfico personalizado. Definiremos a opacidade de traço (`CA`), a opacidade de preenchimento (`ca`) e o modo de mesclagem (`BM`). Você pode adicionar mais entradas depois — este é apenas um conjunto inicial. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Explicação*: +- `CA` e `ca` são chaves PDF padrão que controlam, respectivamente, a opacidade de traço e de preenchimento. +- `BM` seleciona o modo de mesclagem; “Normal” é o padrão, mas você pode usar “Multiply”, “Screen”, etc., conforme as necessidades do seu design. +- Ao usar `CosPdfDictionary.CreateEmptyDictionary`, nós **create empty PDF dictionary** objetos que posteriormente preenchermos com pares chave/valor. + +--- + +## Etapa 5 – Inserir o Novo Estado Gráfico no ExtGState + +Com o estado gráfico pronto, basta adicioná‑lo ao dicionário **ExtGState** sob um nome único (por exemplo, `GS0`). Se planeja adicionar múltiplos estados, basta incrementar o sufixo. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Dica*: Antes de inserir, pode ser interessante verificar se `GS0` já existe para evitar sobrescrita. Uma simples verificação `if (!extGState.ContainsKey("GS0"))` resolve isso. + +--- + +## Etapa 6 – Salvar o PDF Modificado + +Todas as alterações permanecem em memória até que você as persista. Escolha um caminho de saída que faça sentido para o seu fluxo de trabalho. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Resultado*: Abra `output.pdf` em qualquer visualizador de PDF e inspecione os recursos da página (por exemplo, com uma ferramenta de inspeção de PDF). Você verá uma nova entrada em **ExtGState** chamada `GS0` com os parâmetros que definimos. + +--- + +## Exemplo Completo Funcional + +Juntando tudo, aqui está o programa completo, pronto para copiar‑e‑colar: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Saída esperada**: O `output.pdf` será renderizado exatamente como o original, mas qualquer conteúdo que posteriormente referenciar `GS0` (por exemplo, via o operador `gs` em um fluxo de conteúdo) adotará a opacidade e o modo de mesclagem definidos. Se ainda não houver tal referência, você pode adicioná‑la manualmente ou através das APIs de nível mais alto do Aspose. + +--- + +## Perguntas Frequentes & Casos de Borda + +| Pergunta | Resposta | +|----------|----------| +| *E se o PDF já possuir uma entrada `ExtGState` chamada `GS0`?* | Verifique `extGState.ContainsKey("GS0")` antes de adicionar. Se existir, sobrescreva deliberadamente (`extGState["GS0"] = newGraphicsState`) ou escolha um novo nome, como `GS1`. | +| *Posso adicionar mais parâmetros, como largura de linha (`LW`) ou padrão de traço (`D`)?* | Claro. Basta estender o array `parameters` com entradas adicionais `KeyValuePair`. | +| *Esta abordagem funciona com PDFs criptografados?* | Sim, contanto que você forneça a senha correta ao construir o `Document` (`new Document(path, password)`). | +| *Preciso fechar o documento manualmente?* | A instrução `using` cuida da liberação, que também grava quaisquer alterações pendentes. | +| *Como isso difere do uso da classe de alto nível `Graphics`?* | A API de alto nível abstrai os dicionários subjacentes, o que é ótimo para tarefas simples. Contudo, quando você precisa de controle fino sobre estados gráficos — como modos de mesclagem personalizados — é necessário trabalhar com o **CosPdfDictionary** de baixo nível, ou seja, **create empty PDF dictionary** objetos diretamente. | + +--- + +## Conclusão + +Acabamos de demonstrar como **create empty PDF dictionary** objetos com Aspose.Pdf, inserir um estado gráfico personalizado no dicionário **ExtGState** e salvar o arquivo modificado — tudo em C# limpo e idiomático. Esse padrão desbloqueia controle preciso sobre opacidade, modos de mesclagem e quaisquer outros parâmetros de estado gráfico definidos pela especificação PDF. + +A partir daqui você pode: + +- Aplicar o novo estado gráfico ao conteúdo de página existente usando o operador `gs`. +- Construir uma biblioteca de estados gráficos reutilizáveis para branding ou marca d'água. +- + +## O Que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/russian/net/digital-signatures/_index.md b/pdf/russian/net/digital-signatures/_index.md index 4550fdd125..28c7141adf 100644 --- a/pdf/russian/net/digital-signatures/_index.md +++ b/pdf/russian/net/digital-signatures/_index.md @@ -33,7 +33,7 @@ ### [Как удалить цифровые подписи PDF с помощью Aspose.PDF .NET | Полное руководство](./remove-pdf-digital-signatures-aspose-pdf-net/) -### [Как проверить подписи PDF с помощью Aspose.PDF для .NET: подробное руководство](./verify-pdf-signatures-aspose-pdf-net/) +### [Как проверить подписи PDF с помощью Aspose.PDF для .NET: подробное руководство](./verify-pdf-signatures-aspose-net/) ### [Проверка подписи PDF в C# – пошаговое руководство](./verify-pdf-signature-in-c-step-by-step-guide/) Узнайте, как проверять цифровые подписи PDF-файлов в C# с помощью Aspose.PDF, следуя пошаговым инструкциям. @@ -50,6 +50,9 @@ ### [Загрузка PDF‑документа C# – Конвертация в PDF/X‑4 и список подписей](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) Узнайте, как загрузить PDF‑документ, преобразовать его в формат PDF/X‑4 и получить список цифровых подписей с помощью Aspose.PDF для .NET. +### [Проверка подписи PDF и список подписей PDF с Aspose.PDF – Полное руководство](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Узнайте, как проверять подписи PDF и получать список всех подписей в документе с помощью Aspose.PDF для .NET. + ### [Проверка подписи PDF с Aspose – конвертация PDF в HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Узнайте, как проверить подпись PDF и преобразовать документ в HTML с помощью Aspose.PDF для .NET. diff --git a/pdf/russian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/russian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..d1e8baabff --- /dev/null +++ b/pdf/russian/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-07-26 +description: Проверка подписи PDF и перечисление подписей PDF с использованием Aspose.PDF + в C#. Пошаговый код, подводные камни и лучшие практики безопасного обращения с документами. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: ru +lastmod: 2026-07-26 +og_description: Проверьте подпись PDF и получите список подписей PDF с помощью Aspose.PDF. + Следуйте этому практическому руководству, чтобы обеспечить безопасность PDF в C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Проверка подписи PDF и список подписей PDF – Aspose.PDF How‑to +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Проверка подписи PDF и список подписей PDF с Aspose.PDF – Полное руководство +url: /ru/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Проверка подписи PDF и список подписей PDF с Aspose.PDF – Полное руководство + +Когда‑то задумывались, как **проверить подпись PDF** в приложении .NET, не теряя волосы? Вы не одиноки. Будь то создание платформы электронных подписей или просто необходимость убедиться, что полученный контракт не был подделан, умение **вывести список подписей PDF** и проверить каждую из них — обязательный навык. + +В этом руководстве мы пройдем полностью готовый пример, который загружает подписанный PDF, перечисляет все встроенные подписи, проверяет, не были ли они скомпрометированы, и выводит понятный результат в консоль. Никаких расплывчатых ссылок — только код, который можно скопировать‑вставить, плюс объяснение «почему» каждого шага. + +## Предварительные требования + +Прежде чем погрузиться в детали, убедитесь, что у вас есть: + +- **Aspose.PDF for .NET** версии 25.3 или новее (свойство `IsCompromised` появилось в 25.3). +- Среда разработки .NET (Visual Studio 2022, Rider или `dotnet` CLI). +- Подписанный PDF‑файл для тестов (его можно создать в Adobe Acrobat или любом инструменте электронных подписей). + +Если чего‑то не хватает, сначала установите пакет NuGet: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** Выбирайте .NET 6 или новее, чтобы получить лучшую производительность и долгосрочную поддержку. + +## Шаг 1: Загрузка PDF‑документа + +Первое, что нужно сделать — открыть PDF‑файл. Класс `Document` из Aspose.PDF обрабатывает всё: от парсинга до рендеринга. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Почему это важно:* Загрузка файла создаёт представление в памяти, позволяющее запрашивать подписи без повторного обращения к файловой системе. Кроме того, структура PDF проверяется сразу, и вы получаете исключение, если файл повреждён. + +## Шаг 2: **Список подписей PDF** – перечисление всех встроенных подписей + +Подписанный PDF может содержать несколько подписей (например, многостраничный контракт, где каждая сторона подписывает свою страницу). Aspose.PDF предоставляет их через коллекцию `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Что вы видите:* Цикл выводит детали **списка подписей PDF**, такие как имя подписанта, причина, место и метка времени. Это удобно для журналов аудита или отображения в UI. + +## Шаг 3: **Проверка подписи PDF** – проверка на компрометацию + +Теперь часть, критически важная для безопасности: убедиться, что ни одна из подписей не была изменена после подписания. Начиная с версии 25.3, Aspose.PDF предоставляет флаг `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Зачем использовать `IsCompromised`*: Традиционная проверка оценивает только криптографическую цепочку (валидность сертификата, отозванность и т.д.). `IsCompromised` добавляет слой, обнаруживая любые изменения документа после подписи — именно то, что нужно, когда вы **проверяете подпись PDF** на предмет подделки. + +## Шаг 4: Обработка результатов проверки + +В зависимости от результата вы можете выполнить разные действия. Ниже быстрый шаблон, который можно адаптировать: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Примечание о граничных случаях:* Если PDF содержит **сертифицированную** подпись (первая подпись, блокирующая документ), последующее изменение может сделать файл недействительным, даже если последующие подписи выглядят корректными. Всегда рассматривайте любой `true` от `IsCompromised` как тревожный сигнал. + +## Полный рабочий пример + +Объединив всё вместе, получаем единый, самодостаточный пример программы, который можно собрать и запустить: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Ожидаемый вывод** (при одной корректной подписи и одной поддельной): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Распространённые подводные камни и как их избежать + +| Проблема | Почему возникает | Как исправить | +|----------|------------------|---------------| +| **Отсутствует нужная версия Aspose.PDF** | `IsCompromised` появился в 25.3. Более старые пакеты компилируются, но бросают `MissingMethodException`. | Убедитесь, что ссылка на NuGet `>= 25.3`. | +| **Null `SignatureInfo`** | В некоторых PDF есть пустые слоты подписи, которые всё равно попадают в коллекцию. | Добавьте проверку `if (signatureInfo != null)` перед валидацией. | +| **Снижение производительности на больших PDF** | Проверка каждой подписи читает весь файл каждый раз. | Кешируйте `PdfSignatureValidator` или обрабатывайте подписи пакетно, если нужен лишь общий булевый результат. | +| **Не проверяется статус отзыва сертификата** | `IsCompromised` сообщает только о изменениях документа, а не о статусе сертификата. | Используйте `PdfSignatureValidator.Validate()` вместе с `IsCompromised` для полной PKI‑проверки. | + +## Расширение решения + +Если нужно **вывести список подписей PDF** в пользовательском интерфейсе, просто передайте объекты `SignatureInfo` в таблицу данных. Хотите сохранять результаты проверки в базе? Сериализуйте булево `isCompromised` вместе с именем подписанта и меткой времени. + +Другие связанные темы, которые стоит изучить дальше: + +- **Проверка подписи PDF против доверенного корневого CA** (используйте `validator.Validate()`). +- **Извлечение сведений о встроенном сертификате** (`validator.Certificate`). +- **Создание цифровых подписей** с Aspose.PDF (`PdfSignatureBuilder`). + +## Заключение + +Теперь у вас есть практический, сквозной метод **проверки подписи PDF** и **вывода списка подписей PDF** с помощью Aspose.PDF для .NET. Код показывает, как загрузить документ, перечислить каждую подпись, проверить флаг `IsCompromised` и реагировать на результат — всё в понятном, консольном формате. + +Попробуйте на своих подписанных PDF, поэкспериментируйте с несколькими подписями и интегрируйте логику в более крупный конвейер обработки документов. Защищённые PDF настолько надёжны, насколько надёжна их проверка, поэтому держите проверки жёсткими, а журналы — полными. + +Есть вопросы или хотите поделиться интересным кейсом? Оставляйте комментарий ниже или пишите мне на GitHub. Счастливого кодинга! + +![Проверка подписи PDF](/images/validate-pdf-signature.png "Скриншот консольного приложения C# , проверяющего подпись PDF с помощью Aspose.PDF") + + +## Что изучать дальше? + + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом гайде. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [How to Verify PDF – Validate PDF Signature with Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [How to Extract PDF Signature Information Using Aspose.PDF .NET: A Step-by-Step Guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [How to Extract Images from PDF Signature Fields using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/russian/net/programming-with-operators/_index.md b/pdf/russian/net/programming-with-operators/_index.md index 23208c3db4..1e93107bd8 100644 --- a/pdf/russian/net/programming-with-operators/_index.md +++ b/pdf/russian/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ | [Нарисовать XForm на странице](./draw-xform-on-page/) | узнайте, как рисовать XForms в PDF с помощью Aspose.PDF для .NET с помощью этого подробного пошагового руководства. | | [Операторы PDF](./pdf-operators/) | Пошаговое руководство по использованию операторов PDF с Aspose.PDF для .NET. Добавьте изображение на страницу PDF и укажите его положение. | | [Удалить графические объекты в PDF-файле](./remove-graphics-objects/) Узнайте, как удалить графические объекты из файла PDF с помощью Aspose.PDF для .NET в этом пошаговом руководстве. Упростите свои задачи по обработке PDF. | +| [Создать пустой PDF-словарь в C# – Полное руководство Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Узнайте, как создать пустой словарь PDF в C# с помощью Aspose.PDF для .NET в этом полном руководстве. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/russian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/russian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..b9af9c682b --- /dev/null +++ b/pdf/russian/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: Создайте пустой словарь PDF с помощью Aspose.Pdf в C#. Узнайте пошагово, + как добавить графическое состояние в словарь ExtGState для работы с PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: ru +lastmod: 2026-07-26 +og_description: Создайте пустой PDF‑словарь с помощью Aspose.Pdf для C#. Следуйте + этому практическому руководству, чтобы изменять графические состояния в ваших PDF‑файлах. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Создание пустого словаря PDF в C# – Полный учебник по Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Создание пустого словаря PDF в C# – Полное руководство по Aspose.Pdf +url: /ru/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание пустого PDF‑словаря в C# – Полное руководство по Aspose.Pdf + +Когда‑то задавались вопросом, как **создать пустой PDF‑словарь** при настройке графического состояния PDF? Вы не одиноки — многие разработчики сталкиваются с этой проблемой, пытаясь программно изменить непрозрачность или режимы наложения. В этом руководстве мы пройдем конкретное решение с использованием Aspose.Pdf для C#, показывая, как внедрить новое графическое состояние в словарь *ExtGState* существующего PDF. + +Мы охватим всё, что вам нужно: загрузку PDF, доступ к словарю ресурсов, создание нового **CosPdfDictionary** и, наконец, сохранение изменений. К концу вы получите переиспользуемый шаблон для любых настроек *PDF graphics state*, которые вам могут понадобиться. + +--- + +## Что вы узнаете + +- Как **создать пустой PDF‑словарь** с помощью низкоуровневого API Aspose.Pdf. +- Роль **словаря ExtGState** в управлении непрозрачностью обводки/заполнения и режимами наложения. +- Практические советы по работе с PDF в C#, включая обработку крайних случаев, когда словарь отсутствует. +- Полный, готовый к запуску пример кода, который можно скопировать и вставить в свой проект. + +### Предварительные требования + +- .NET 6.0 или новее (код также работает с .NET Framework 4.6+). +- Лицензированная копия **Aspose.Pdf for .NET** (бесплатная пробная версия подходит для тестирования). +- Базовые знания C# и концепций PDF, таких как ресурсы и графические состояния. + +Если что‑то из этого вам незнакомо, не паникуйте — установите Aspose.Pdf через NuGet (`Install-Package Aspose.Pdf`), а остальное — обычный C#. + +--- + +## Шаг 1 – Загрузка PDF‑документа + +Первым делом нужен объект `Document`, представляющий файл, который вы хотите изменить. Оборачивание его в блок `using` гарантирует корректное освобождение ресурсов. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Почему это важно*: Открывая файл, вы получаете доступ к внутренним объектам COS (Canonical Object Structure), где находится **CosPdfDictionary**. Без объекта документа вы не сможете достать словари ресурсов, содержащие записи **ExtGState**. + +--- + +## Шаг 2 – Доступ к словарю ресурсов первой страницы + +Страницы PDF хранят свои ресурсы (шрифты, изображения, графические состояния и т.д.) в отдельном словаре. Мы возьмём первую страницу для простоты, но тот же подход работает для любой страницы. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Совет*: Если ваш PDF содержит несколько страниц с разными наборами ресурсов, повторите этот блок для каждой страницы, которую нужно изменить. Класс `DictionaryEditor` — удобный обёртка, позволяющая работать с COS‑словарем как с .NET‑словарем `Dictionary`. + +--- + +## Шаг 3 – Получение или инициализация словаря ExtGState + +**Словарь ExtGState** хранит именованные объекты графических состояний (`GS0`, `GS1`, …). В некоторых PDF он уже присутствует, в других — нет. Мы безопасно получим его, создав новый пустой, если потребуется. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Зачем это делаем*: Попытка добавить графическое состояние в несуществующий **словарь ExtGState** вызовет исключение. Эта проверка делает код надёжным для любого входного PDF. + +--- + +## Шаг 4 – Создание нового графического состояния с CosPdfDictionary + +Теперь к делу: **создание пустого PDF‑словаря**, определяющего пользовательское графическое состояние. Мы зададим непрозрачность обводки (`CA`), непрозрачность заливки (`ca`) и режим наложения (`BM`). Позже можно добавить и другие параметры — это лишь базовый набор. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Пояснение*: +- `CA` и `ca` — стандартные ключи PDF, управляющие непрозрачностью обводки и заливки соответственно. +- `BM` выбирает режим наложения; «Normal» — значение по умолчанию, но можно использовать «Multiply», «Screen» и т.д., в зависимости от потребностей дизайна. +- С помощью `CosPdfDictionary.CreateEmptyDictionary` мы **создаём пустой PDF‑словарь**, который затем заполняем парами ключ/значение. + +--- + +## Шаг 5 – Вставка нового графического состояния в ExtGState + +Когда графическое состояние готово, просто добавляем его в **словарь ExtGState** под уникальным именем (например, `GS0`). Если планируется добавить несколько состояний, просто увеличьте суффикс. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Подсказка*: Перед добавлением стоит проверить, существует ли уже `GS0`, чтобы не перезаписать его. Быстрая проверка `if (!extGState.ContainsKey("GS0"))` решит задачу. + +--- + +## Шаг 6 – Сохранение изменённого PDF + +Все изменения находятся в памяти, пока вы их не сохраните. Выберите путь вывода, который подходит вашему рабочему процессу. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Результат*: Откройте `output.pdf` в любом просмотрщике PDF и проверьте ресурсы страницы (например, с помощью инструмента‑инспектора PDF). Вы увидите новую запись в **ExtGState** под именем `GS0` с заданными параметрами. + +--- + +## Полный рабочий пример + +Объединив всё вместе, получаем полностью готовую к копированию и вставке программу: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Ожидаемый результат**: `output.pdf` будет выглядеть точно так же, как оригинал, но любой контент, который позже сослётся на `GS0` (например, через оператор `gs` в потоке содержимого), получит заданные непрозрачность и режим наложения. Если такой ссылки пока нет, её можно добавить вручную или через более высокоуровневые API Aspose. + +--- + +## Часто задаваемые вопросы и крайние случаи + +| Вопрос | Ответ | +|----------|--------| +| *Что делать, если в PDF уже существует запись ExtGState с именем `GS0`?* | Проверьте `extGState.ContainsKey("GS0")` перед добавлением. Если она существует, либо намеренно перезапишите её (`extGState["GS0"] = newGraphicsState`), либо выберите новое имя, например `GS1`. | +| *Можно ли добавить больше параметров, например толщину линии (`LW`) или шаблон штриховки (`D`)?* | Конечно. Просто расширьте массив `parameters`, добавив дополнительные `KeyValuePair` записи. | +| *Совместим ли этот подход с зашифрованными PDF?* | Да, при условии, что вы передадите правильный пароль при создании `Document` (`new Document(path, password)`). | +| *Нужно ли закрывать документ вручную?* | Блок `using` автоматически освобождает ресурсы, что также сбрасывает все ожидающие изменения. | +| *Чем этот метод отличается от использования высокоуровневого класса `Graphics`?* | Высокоуровневый API скрывает детали словарей, что удобно для простых задач. Однако когда требуется точный контроль над графическими состояниями — например, пользовательские режимы наложения — необходимо работать с низкоуровневым **CosPdfDictionary**, то есть напрямую **создавать пустой PDF‑словарь**. | + +--- + +## Заключение + +Мы продемонстрировали, как **создать пустой PDF‑словарь** с помощью Aspose.Pdf, внедрить пользовательское графическое состояние в **словарь ExtGState** и сохранить изменённый файл — всё это в чистом, идиоматическом C#. Этот шаблон открывает точный контроль над непрозрачностью, режимами наложения и другими параметрами графического состояния, определёнными спецификацией PDF. + +Дальше вы можете: + +- Применить новое графическое состояние к существующему содержимому страницы с помощью оператора `gs`. +- Построить библиотеку переиспользуемых графических состояний для брендинга или водяных знаков. +- + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/spanish/net/digital-signatures/_index.md b/pdf/spanish/net/digital-signatures/_index.md index ff2ccf3a48..619af466bd 100644 --- a/pdf/spanish/net/digital-signatures/_index.md +++ b/pdf/spanish/net/digital-signatures/_index.md @@ -61,6 +61,9 @@ Aprenda a validar la firma de un PDF con Aspose, paso a paso y con ejemplos de c ### [Cargar documento PDF C# – Convertir a PDF/X‑4 y listar firmas](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) Aprenda a cargar un PDF en C#, convertirlo a PDF/X‑4 y listar sus firmas digitales usando Aspose.PDF. +### [Validar la firma de PDF y listar firmas PDF con Aspose.PDF – Guía completa](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Aprenda a validar la firma de un PDF y a enumerar todas sus firmas usando Aspose.PDF en .NET. + ### [Validar firma PDF con Aspose – Convertir PDF a HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Aprenda a validar firmas PDF y convertir documentos a HTML usando Aspose.PDF para .NET. diff --git a/pdf/spanish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/spanish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..b416448ce0 --- /dev/null +++ b/pdf/spanish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-07-26 +description: Validar la firma PDF y enumerar las firmas PDF usando Aspose.PDF en C#. + Código paso a paso, trampas y mejores prácticas para el manejo seguro de documentos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: es +lastmod: 2026-07-26 +og_description: Valide la firma PDF y enumere las firmas PDF con Aspose.PDF. Siga + esta guía práctica para asegurar los PDFs en C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Validar firma PDF y listar firmas PDF – Cómo hacerlo con Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Validar la firma PDF y listar firmas PDF con Aspose.PDF – Guía completa +url: /es/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Validar firma PDF y listar firmas PDF con Aspose.PDF – Guía completa + +¿Alguna vez te has preguntado cómo **validar la firma PDF** en una aplicación .NET sin volverte loco? No eres el único. Ya sea que estés construyendo una plataforma de firma electrónica o simplemente necesites asegurarte de que un contrato recibido no haya sido manipulado, poder **listar firmas PDF** y verificar cada una es una habilidad imprescindible. + +En este tutorial recorreremos un ejemplo completamente ejecutable que carga un PDF firmado, enumera cada firma incrustada, comprueba si alguna ha sido comprometida y muestra un resultado claro en la consola. Sin referencias vagas—solo el código que puedes copiar‑pegar, más el “por qué” detrás de cada paso. + +## Prerrequisitos + +Antes de sumergirnos, asegúrate de contar con: + +- **Aspose.PDF for .NET** versión 25.3 o superior (la propiedad `IsCompromised` apareció en la 25.3). +- Un entorno de desarrollo .NET (Visual Studio 2022, Rider o la CLI `dotnet`). +- Un archivo PDF firmado con el que puedas probar (puedes crear uno con Adobe Acrobat o cualquier herramienta de firma electrónica). + +Si falta alguno de estos, instala primero el paquete NuGet: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Consejo profesional:** Apunta a .NET 6 o posterior para obtener el mejor rendimiento y soporte a largo plazo. + +## Paso 1: Cargar el documento PDF + +Lo primero que debes hacer es abrir el archivo PDF. La clase `Document` de Aspose.PDF se encarga de todo, desde el análisis hasta la renderización. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Por qué es importante:* Cargar el archivo crea una representación en memoria que te permite consultar las firmas sin volver a tocar el sistema de archivos. Además valida la estructura del PDF al inicio, de modo que obtendrás una excepción de inmediato si el archivo está corrupto. + +## Paso 2: **Listar firmas PDF** – Enumerar todas las firmas incrustadas + +Un PDF firmado puede contener varias firmas (piensa en un contrato de varias páginas donde cada parte firma una página distinta). Aspose.PDF las expone a través de la colección `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Lo que estás viendo:* El bucle imprime los detalles de **listado de firmas PDF** como el nombre del firmante, motivo, ubicación y marca de tiempo. Esto es útil para registros de auditoría o para mostrar en una interfaz de usuario. + +## Paso 3: **Validar firma PDF** – Comprobar compromisos + +Ahora llega la parte crítica de seguridad: confirmar que ninguna de las firmas haya sido alterada después de la firma. A partir de la versión 25.3, Aspose.PDF ofrece la bandera `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Por qué deberías usar `IsCompromised`*: La validación tradicional solo verifica la cadena criptográfica (validez del certificado, revocación, etc.). `IsCompromised` añade una capa extra detectando cualquier cambio posterior a la firma en el documento—exactamente lo que necesitas al **validar la firma PDF** contra manipulaciones. + +## Paso 4: Manejo de los resultados de validación + +Según el resultado, puede que quieras tomar acciones diferentes. Aquí tienes un patrón rápido que puedes adaptar: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Nota de caso límite:* Si un PDF contiene una firma **certificada** (la primera firma que bloquea el documento), una modificación posterior puede invalidar todo el archivo, aunque las firmas subsecuentes parezcan correctas. Siempre trata cualquier `true` de `IsCompromised` como una señal de alerta. + +## Ejemplo completo y funcional + +Juntando todo, aquí tienes un programa único, autocontenido, que puedes compilar y ejecutar: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Salida esperada** (suponiendo una firma correcta y una alterada): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Errores comunes y cómo evitarlos + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| **Falta la versión de Aspose.PDF** | `IsCompromised` se introdujo en la 25.3. Paquetes más antiguos compilan pero lanzan `MissingMethodException`. | Asegúrate de que la referencia NuGet sea `>= 25.3`. | +| **`SignatureInfo` nulo** | Algunos PDFs tienen ranuras de firma vacías que aún aparecen en la colección. | Protege con `if (signatureInfo != null)` antes de validar. | +| **Impacto de rendimiento en PDFs grandes** | Validar cada firma lee todo el archivo cada vez. | Cachea el `PdfSignatureValidator` o procesa firmas en lote si solo necesitas un resumen booleano. | +| **No se verifica la revocación del certificado** | `IsCompromised` solo indica cambios en el documento, no el estado del certificado. | Usa `PdfSignatureValidator.Validate()` además de `IsCompromised` para comprobaciones PKI completas. | + +## Extender la solución + +Si necesitas **listar firmas PDF** en una UI, simplemente pasa los objetos `SignatureInfo` a una tabla de datos. ¿Quieres almacenar los resultados de validación en una base de datos? Serializa el booleano `isCompromised` junto con el nombre del firmante y la marca de tiempo. + +Otros temas relacionados que podrías explorar a continuación: + +- **Validar firma PDF contra una CA raíz de confianza** (usa `validator.Validate()`). +- **Extraer detalles del certificado incrustado** (`validator.Certificate`). +- **Crear firmas digitales** con Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusión + +Ahora dispones de un método práctico, de extremo a extremo, para **validar la firma PDF** y **listar firmas PDF** usando Aspose.PDF para .NET. El código muestra exactamente cómo cargar un documento, enumerar cada firma, comprobar la bandera `IsCompromised` y actuar según el resultado, todo en un formato claro y amigable para la consola. + +Pruébalo con tus propios PDFs firmados, experimenta con múltiples firmas e integra la lógica en tu pipeline de procesamiento de documentos. Los PDFs seguros son tan fuertes como la validación que realices, así que mantén los controles estrictos y los registros completos. + +¿Tienes preguntas o quieres compartir un caso de uso interesante? Deja un comentario abajo o envíame un mensaje en GitHub. ¡Feliz codificación! + +![Validate PDF Signature](/images/validate-pdf-signature.png "Screenshot of a C# console app validating a PDF signature with Aspose.PDF") + + +## ¿Qué deberías aprender a continuación? + + +Los tutoriales siguientes cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques alternativos en tus propios proyectos. + +- [How to Verify PDF – Validate PDF Signature with Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [How to Extract PDF Signature Information Using Aspose.PDF .NET: A Step-by-Step Guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [How to Extract Images from PDF Signature Fields using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/spanish/net/programming-with-operators/_index.md b/pdf/spanish/net/programming-with-operators/_index.md index 20ff762b0b..c60a033c95 100644 --- a/pdf/spanish/net/programming-with-operators/_index.md +++ b/pdf/spanish/net/programming-with-operators/_index.md @@ -21,8 +21,9 @@ Los tutoriales "Programación con Operadores" de Aspose.PDF para .NET le guiará | Título | Descripción | | --- | --- | | [Dibujar XForm en la página](./draw-xform-on-page/) | Aprenda a dibujar XForms en PDF usando Aspose.PDF para .NET con esta completa guía paso a paso. | -| [Operadores de PDF](./pdf-operators/) Guía paso a paso para usar operadores PDF con Aspose.PDF para .NET. Agregue una imagen a una página PDF y especifique su posición. -| [Eliminar objetos gráficos en un archivo PDF](./remove-graphics-objects/) Aprenda a eliminar objetos gráficos de un archivo PDF con Aspose.PDF para .NET con esta guía paso a paso. Simplifique la manipulación de PDF. +| [Operadores de PDF](./pdf-operators/) | Guía paso a paso para usar operadores PDF con Aspose.PDF para .NET. Agregue una imagen a una página PDF y especifique su posición. | +| [Eliminar objetos gráficos en un archivo PDF](./remove-graphics-objects/) | Aprenda a eliminar objetos gráficos de un archivo PDF con Aspose.PDF para .NET con esta guía paso a paso. Simplifique la manipulación de PDF. | +| [Crear diccionario PDF vacío en C# – Guía completa de Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Aprenda a crear un diccionario PDF vacío en C# usando Aspose.PDF con esta guía paso a paso. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/spanish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/spanish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..54b38d3974 --- /dev/null +++ b/pdf/spanish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-07-26 +description: Crea un diccionario PDF vacío con Aspose.Pdf en C#. Aprende paso a paso + cómo agregar un estado gráfico al diccionario ExtGState para la manipulación de + PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: es +lastmod: 2026-07-26 +og_description: Crea un diccionario PDF vacío usando Aspose.Pdf para C#. Sigue esta + guía práctica para modificar los estados gráficos en tus PDFs. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Crear un diccionario PDF vacío en C# – Tutorial completo de Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Crear un diccionario PDF vacío en C# – Guía completa de Aspose.Pdf +url: /es/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear un Diccionario PDF Vacío en C# – Guía Completa de Aspose.Pdf + +¿Alguna vez te has preguntado cómo **crear un diccionario PDF vacío** al ajustar el estado gráfico de un PDF? No estás solo—muchos desarrolladores se encuentran con este problema al intentar modificar la opacidad o los modos de fusión de forma programática. En este tutorial recorreremos una solución concreta usando Aspose.Pdf para C#, mostrando exactamente cómo inyectar un nuevo estado gráfico en el diccionario *ExtGState* de un PDF existente. + +Cubrirémos todo lo que necesitas: cargar un PDF, acceder a su diccionario de recursos, crear un nuevo **CosPdfDictionary**, y finalmente persistir los cambios. Al final tendrás un patrón reutilizable para cualquier ajuste del *estado gráfico PDF* que necesites. + +--- + +## Lo que aprenderás + +- Cómo **crear objetos de diccionario PDF vacío** con la API de bajo nivel de Aspose.Pdf. +- El papel del **diccionario ExtGState** en el control de la opacidad de trazo/relleno y los modos de fusión. +- Consejos prácticos para la manipulación de PDFs en C#, incluyendo el manejo de casos límite cuando falta el diccionario. +- Un ejemplo de código completo y ejecutable que puedes copiar y pegar en tu proyecto. + +### Requisitos previos + +- .NET 6.0 o posterior (el código también funciona con .NET Framework 4.6+). +- Una copia con licencia de **Aspose.Pdf for .NET** (la prueba gratuita sirve para pruebas). +- Familiaridad básica con C# y conceptos de PDF como recursos y estados gráficos. + +Si alguno de estos te resulta desconocido, no te alarmes—puedes instalar Aspose.Pdf vía NuGet (`Install-Package Aspose.Pdf`) y el resto es simplemente C# puro. + +--- + +## Paso 1 – Cargar el Documento PDF + +Lo primero, necesitas un objeto `Document` que represente el archivo que deseas editar. Envolverlo en un bloque `using` garantiza una correcta liberación de recursos. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Por qué es importante*: Abrir el archivo te da acceso a los objetos internos COS (Canonical Object Structure), donde reside el **CosPdfDictionary**. Sin el objeto documento, no puedes alcanzar los diccionarios de recursos que contienen las entradas **ExtGState**. + +## Paso 2 – Acceder al Diccionario de Recursos de la Primera Página + +Las páginas PDF almacenan sus recursos (fuentes, imágenes, estados gráficos, etc.) en un diccionario dedicado. Obtendremos la primera página por simplicidad, pero la misma lógica se aplica a cualquier índice de página. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Consejo profesional*: Si tu PDF tiene varias páginas con diferentes conjuntos de recursos, repite este bloque para cada página que necesites modificar. La clase `DictionaryEditor` es un contenedor conveniente que te permite tratar el diccionario COS como un `Dictionary` de .NET. + +## Paso 3 – Recuperar o Inicializar el Diccionario ExtGState + +El **diccionario ExtGState** contiene objetos de estado gráfico nombrados (`GS0`, `GS1`, …). Algunos PDFs ya lo incluyen; otros no. Lo obtendremos de forma segura, creando uno nuevo vacío si es necesario. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Por qué lo hacemos*: Intentar agregar un estado gráfico a un **diccionario ExtGState** inexistente lanzaría una excepción. Esta verificación defensiva hace que el código sea robusto para cualquier PDF de entrada. + +## Paso 4 – Construir un Nuevo Estado Gráfico con CosPdfDictionary + +Ahora llega el corazón del tutorial: **crear un diccionario PDF vacío** que define un estado gráfico personalizado. Estableceremos la opacidad del trazo (`CA`), la opacidad del relleno (`ca`) y el modo de fusión (`BM`). Puedes añadir más entradas más adelante—esto es solo un conjunto inicial. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Explicación*: +- `CA` y `ca` son claves PDF estándar que controlan la opacidad del trazo y del relleno, respectivamente. +- `BM` selecciona el modo de fusión; “Normal” es el predeterminado pero podrías usar “Multiply”, “Screen”, etc., según las necesidades de tu diseño. +- Al usar `CosPdfDictionary.CreateEmptyDictionary`, **creamos objetos de diccionario PDF vacío** que luego rellenamos con pares clave/valor. + +## Paso 5 – Insertar el Nuevo Estado Gráfico en ExtGState + +Con el estado gráfico listo, simplemente lo añadimos al **diccionario ExtGState** bajo un nombre único (p.ej., `GS0`). Si planeas agregar varios estados, solo incrementa el sufijo. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Consejo*: Antes de añadir, podrías verificar si `GS0` ya existe para evitar sobrescribir. Una simple comprobación `if (!extGState.ContainsKey("GS0"))` hace el truco. + +## Paso 6 – Guardar el PDF Modificado + +Todos los cambios están en memoria hasta que los persistas. Elige una ruta de salida que tenga sentido para tu flujo de trabajo. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Resultado*: Abre `output.pdf` en cualquier visor de PDF, luego inspecciona los recursos de la página (p.ej., con una herramienta de inspección de PDF). Verás una nueva entrada bajo **ExtGState** llamada `GS0` con los parámetros que definimos. + +## Ejemplo Completo Funcional + +Juntando todo, aquí tienes el programa completo, listo para copiar y pegar: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Salida esperada**: El `output.pdf` se renderizará exactamente como el original, pero cualquier contenido que luego haga referencia a `GS0` (por ejemplo mediante el operador `gs` en un flujo de contenido) adoptará la opacidad y el modo de fusión definidos. Si aún no tienes tal referencia, puedes añadir una manualmente o a través de las APIs de alto nivel de Aspose. + +## Preguntas Frecuentes y Casos Límite + +| Pregunta | Respuesta | +|----------|-----------| +| *¿Qué pasa si el PDF ya tiene una entrada `ExtGState` llamada `GS0`?* | Verifica `extGState.ContainsKey("GS0")` antes de añadir. Si existe, puedes sobrescribir deliberadamente (`extGState["GS0"] = newGraphicsState`) o elegir un nombre nuevo como `GS1`. | +| *¿Puedo añadir más parámetros, como ancho de línea (`LW`) o patrón de guiones (`D`)?* | Absolutamente. Simplemente extiende el arreglo `parameters` con entradas adicionales de `KeyValuePair`. | +| *¿Este enfoque es compatible con PDFs encriptados?* | Sí, siempre que proporciones la contraseña correcta al crear el `Document` (`new Document(path, password)`). | +| *¿Necesito cerrar el documento manualmente?* | La sentencia `using` se encarga de la liberación, lo que también vacía cualquier cambio pendiente. | +| *¿En qué se diferencia esto de usar la clase `Graphics` de alto nivel?* | La API de alto nivel abstrae los diccionarios subyacentes, lo cual es excelente para tareas simples. Sin embargo, cuando necesitas un control fino sobre los estados gráficos—como modos de fusión personalizados—debes trabajar con el **CosPdfDictionary** de bajo nivel, es decir, crear objetos **de diccionario PDF vacío** directamente. | + +## Conclusión + +Acabamos de demostrar cómo **crear objetos de diccionario PDF vacío** con Aspose.Pdf, inyectar un estado gráfico personalizado en el **diccionario ExtGState**, y guardar el archivo modificado—todo en C# limpio e idiomático. Este patrón brinda un control preciso sobre la opacidad, los modos de fusión y cualquier otro parámetro de estado gráfico definido por la especificación PDF. + +Desde aquí podrías: + +- Aplicar el nuevo estado gráfico al contenido de página existente usando el operador `gs`. +- Construir una biblioteca de estados gráficos reutilizables para branding o marcas de agua. +- + +## ¿Qué Deberías Aprender a Continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo crear líneas discontinuas en PDFs usando Aspose.PDF para .NET: Guía paso a paso](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Crear y rellenar rectángulos en PDFs usando Aspose.PDF para .NET: Guía paso a paso](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/swedish/net/digital-signatures/_index.md b/pdf/swedish/net/digital-signatures/_index.md index 777d04f05e..a6d2582a31 100644 --- a/pdf/swedish/net/digital-signatures/_index.md +++ b/pdf/swedish/net/digital-signatures/_index.md @@ -59,6 +59,9 @@ Lär dig hur du laddar en PDF, konverterar den till PDF/X‑4 och listar befintl ### [Validera PDF-signatur med Aspose – Konvertera PDF till HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Lär dig hur du validerar PDF-signaturer och konverterar PDF till HTML med Aspose.PDF för .NET. +### [Validera PDF-signatur och lista PDF-signaturer med Aspose.PDF – Komplett guide](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Lär dig hur du validerar PDF-signaturer och listar befintliga signaturer med Aspose.PDF för .NET i en komplett guide. + ## Ytterligare resurser - [Aspose.PDF för nätdokumentation](https://docs.aspose.com/pdf/net/) diff --git a/pdf/swedish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/swedish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..346e2edbd6 --- /dev/null +++ b/pdf/swedish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-07-26 +description: Validera PDF‑signatur och lista PDF‑signaturer med Aspose.PDF i C#. Steg‑för‑steg‑kod, + fallgropar och bästa praxis för säker dokumenthantering. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: sv +lastmod: 2026-07-26 +og_description: Validera PDF‑signatur och lista PDF‑signaturer med Aspose.PDF. Följ + den här praktiska guiden för att säkra PDF‑filer i C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Validera PDF‑signatur & lista PDF‑signaturer – Aspose.PDF How‑to +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Validera PDF‑signatur och lista PDF‑signaturer med Aspose.PDF – Komplett guide +url: /sv/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Validera PDF‑signatur och lista PDF‑signaturer med Aspose.PDF – Komplett guide + +Har du någonsin undrat hur du **validerar PDF‑signatur** i en .NET‑app utan att dra i håret? Du är inte ensam. Oavsett om du bygger en e‑sign‑plattform eller bara behöver försäkra dig om att ett mottaget kontrakt inte har manipulerats, är förmågan att **lista PDF‑signaturer** och verifiera var och en en nödvändig färdighet. + +I den här handledningen går vi igenom ett fullt körbart exempel som laddar en signerad PDF, räknar upp varje inbäddad signatur, kontrollerar om någon av dem har komprometterats och skriver ut ett tydligt resultat i konsolen. Inga vaga referenser – bara koden du kan kopiera‑klistra in, plus “varför” bakom varje steg. + +## Förutsättningar + +- **Aspose.PDF for .NET** version 25.3 eller nyare (egenskapen `IsCompromised` introducerades i 25.3). +- En .NET‑utvecklingsmiljö (Visual Studio 2022, Rider eller `dotnet`‑CLI). +- En signerad PDF‑fil som du kan testa med (du kan skapa en med Adobe Acrobat eller något e‑signaturverktyg). + +Om någon av dessa saknas, installera NuGet‑paketet först: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Proffstips:** Sikta på .NET 6 eller senare för bästa prestanda och långsiktigt stöd. + +## Steg 1: Ladda PDF‑dokumentet + +Det allra första du måste göra är att öppna PDF‑filen. Aspose.PDF:s `Document`‑klass hanterar allt från parsning till rendering. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Varför detta är viktigt:* Att ladda filen skapar en minnesrepresentation som låter dig fråga efter signaturer utan att behöva läsa filsystemet igen. Den validerar också PDF‑strukturen tidigt, så du får ett undantag omedelbart om filen är korrupt. + +## Steg 2: **Lista PDF‑signaturer** – Enumerera alla inbäddade signaturer + +En signerad PDF kan innehålla flera signaturer (tänk på ett flersidigt kontrakt där varje part signerar en annan sida). Aspose.PDF exponerar dem via samlingen `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Vad du ser:* Loopen skriver ut detaljer för **lista PDF‑signaturer** såsom signatärens namn, anledning, plats och tidsstämpel. Detta är praktiskt för revisionsloggar eller UI‑visningar. + +## Steg 3: **Validera PDF‑signatur** – Kontrollera kompromettering + +Nu kommer den säkerhetskritiska delen: att bekräfta att ingen av signaturerna har ändrats efter signering. Från och med version 25.3 erbjuder Aspose.PDF flaggan `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Varför du bör använda `IsCompromised`*: Traditionell validering kontrollerar bara den kryptografiska kedjan (certifikatets giltighet, återkallelse osv.). `IsCompromised` lägger till ett extra lager genom att upptäcka eventuella förändringar i dokumentet efter signering – exakt vad du behöver när du **validerar PDF‑signatur** för manipulation. + +## Steg 4: Hantera valideringsresultat + +Beroende på resultatet kan du vilja vidta olika åtgärder. Här är ett snabbt mönster du kan anpassa: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Obs om kantfall:* Om en PDF innehåller en **certifierad** signatur (den första signaturen som låser dokumentet) kan en senare ändring ogiltigförklara hela filen, även om efterföljande signaturer verkar vara i ordning. Behandla alltid ett `true` från `IsCompromised` som en varningssignal. + +## Fullt fungerande exempel + +När allt sätts ihop, här är ett enda, självständigt program som du kan kompilera och köra: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Förväntad output** (förutsatt en god signatur och en manipulerad): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Vanliga fallgropar & hur du undviker dem + +| Fallgropar | Varför det händer | Lösning | +|------------|-------------------|---------| +| **Saknad Aspose.PDF‑version** | `IsCompromised` introducerades i 25.3. Äldre paket kompilerar men kastar `MissingMethodException`. | Se till att ditt NuGet‑referens är `>= 25.3`. | +| **Null `SignatureInfo`** | Vissa PDF‑filer har tomma signaturslottar som fortfarande visas i samlingen. | Skydda med `if (signatureInfo != null)` innan validering. | +| **Prestandaproblem på stora PDF‑filer** | Att validera varje signatur läser hela filen varje gång. | Cacha `PdfSignatureValidator` eller batch‑processa signaturer om du bara behöver en boolesk sammanfattning. | +| **Certifikatåterkallelse kontrolleras inte** | `IsCompromised` visar bara dokumentändringar, inte certifikatstatus. | Använd `PdfSignatureValidator.Validate()` utöver `IsCompromised` för fullständiga PKI‑kontroller. | + +## Utöka lösningen + +Om du behöver **lista PDF‑signaturer** i ett UI, mata helt enkelt `SignatureInfo`‑objekten i ett datagrid. Vill du lagra valideringsresultat i en databas? Serialisera den booleska `isCompromised` tillsammans med signatärens namn och tidsstämpel. + +Andra relaterade ämnen du kan utforska härnäst: + +- **Validera PDF‑signatur mot en betrodd rot‑CA** (använd `validator.Validate()`). +- **Extrahera inbäddade certifikatdetaljer** (`validator.Certificate`). +- **Skapa digitala signaturer** med Aspose.PDF (`PdfSignatureBuilder`). + +## Slutsats + +Du har nu en praktisk, end‑to‑end‑metod för att **validera PDF‑signatur** och **lista PDF‑signaturer** med Aspose.PDF för .NET. Koden visar exakt hur du laddar ett dokument, räknar upp varje signatur, kontrollerar flaggan `IsCompromised` och agerar på resultatet – allt i ett tydligt, konsolvänligt format. + +Prova det med dina egna signerade PDF‑filer, experimentera med flera signaturer och integrera logiken i din större dokument‑behandlingspipeline. Säkra PDF‑filer är bara så starka som den validering du utför, så håll kontrollerna strama och loggarna grundliga. + +Har du frågor eller vill dela ett coolt användningsfall? Lämna en kommentar nedan eller kontakta mig på GitHub. Lycka till med kodandet! + +![Validera PDF‑signatur](/images/validate-pdf-signature.png "Skärmbild av en C#‑konsolapp som validerar en PDF‑signatur med Aspose.PDF") + + +## Vad bör du lära dig härnäst? + + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man verifierar PDF – Validera PDF‑signatur med Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Hur man extraherar PDF‑signaturinformation med Aspose.PDF .NET: En steg‑för‑steg‑guide](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Hur man extraherar bilder från PDF‑signaturfält med Aspose.PDF för .NET: En steg‑för‑steg‑guide](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/swedish/net/programming-with-operators/_index.md b/pdf/swedish/net/programming-with-operators/_index.md index 24b4881502..984a919432 100644 --- a/pdf/swedish/net/programming-with-operators/_index.md +++ b/pdf/swedish/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Aspose.PDF för .NET:s handledningar "Programmering med operatorer" guidar dig g | [Rita XForm på sidan](./draw-xform-on-page/) | lär dig hur man ritar XForms i PDF med Aspose.PDF för .NET med den här omfattande steg-för-steg-guiden. | | [PDF-operatorer](./pdf-operators/) | Steg-för-steg-guide för att använda PDF-operatorer med Aspose.PDF för .NET. Lägg till en bild på en PDF-sida och ange dess position. | | [Ta bort grafikobjekt i PDF-fil](./remove-graphics-objects/) Lär dig hur du tar bort grafikobjekt från en PDF-fil med Aspose.PDF för .NET i den här steg-för-steg-guiden. Förenkla dina PDF-manipulationsuppgifter. | +| [Skapa en tom PDF-ordbok i C# – Komplett Aspose.Pdf-guide](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Lär dig hur du skapar en tom PDF-ordbok i C# med Aspose.PDF för .NET i denna steg-för-steg-guide. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/swedish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/swedish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..ebe9b02307 --- /dev/null +++ b/pdf/swedish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-26 +description: Skapa en tom PDF‑ordbok med Aspose.Pdf i C#. Lär dig steg för steg hur + du lägger till ett grafikstatus i ExtGState‑ordboken för PDF‑manipulering. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: sv +lastmod: 2026-07-26 +og_description: Skapa en tom PDF‑ordbok med Aspose.Pdf för C#. Följ den här praktiska + guiden för att ändra grafiklägen i dina PDF‑filer. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Skapa tom PDF-ordbok i C# – Fullständig Aspose.Pdf-handledning +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Skapa tom PDF-ordbok i C# – Komplett guide för Aspose.Pdf +url: /sv/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa tom PDF-ordbok i C# – Komplett Aspose.Pdf-guide + +Har du någonsin funderat på hur man **skapar tom PDF-ordbok**-poster när man justerar en PDFs grafikstatus? Du är inte ensam—många utvecklare stöter på detta problem när de försöker justera opacitet eller blandningslägen programmässigt. I den här handledningen går vi igenom en konkret lösning med Aspose.Pdf för C#, och visar exakt hur man injicerar ett nytt grafikstatus i *ExtGState*-ordboken i en befintlig PDF. + +Vi kommer att gå igenom allt du behöver: ladda en PDF, komma åt dess resursordbok, bygga en ny **CosPdfDictionary**, och slutligen spara ändringarna. När du är klar har du ett återanvändbart mönster för alla *PDF graphics state*-justeringar du kan behöva. + +## Vad du kommer att lära dig + +- Hur man **skapar tom PDF-ordbok**-objekt med Aspose.Pdf:s låg‑nivå‑API. +- Rollen för **ExtGState dictionary** när man styr linje‑/fyllningsopacitet och blandningslägen. +- Praktiska tips för C# PDF-manipulation, inklusive hantering av kantfall när ordboken saknas. +- Ett komplett, körbart kodexempel som du kan kopiera‑och‑klistra in i ditt projekt. + +### Förutsättningar + +- .NET 6.0 eller senare (koden fungerar även med .NET Framework 4.6+). +- En licensierad kopia av **Aspose.Pdf for .NET** (gratis provversion fungerar för testning). +- Grundläggande kunskap om C# och PDF‑koncept som resurser och grafikstatusar. + +Om något av detta känns obekant, panik inte—du kan installera Aspose.Pdf via NuGet (`Install-Package Aspose.Pdf`) och resten är bara ren C#. + +## Steg 1 – Ladda PDF-dokumentet + +Först och främst behöver du ett `Document`‑objekt som representerar filen du vill redigera. Att omsluta det i ett `using`‑block garanterar korrekt resurshantering. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Varför detta är viktigt*: Att öppna filen ger dig åtkomst till de interna COS‑objekten (Canonical Object Structure), där **CosPdfDictionary** finns. Utan dokumentobjektet kan du inte nå resursordböckerna som innehåller **ExtGState**‑poster. + +## Steg 2 – Kom åt den första sidans resursordbok + +PDF‑sidor lagrar sina resurser (typsnitt, bilder, grafikstatusar osv.) i en dedikerad ordbok. Vi hämtar den första sidan för enkelhetens skull, men samma logik gäller för vilket sidindex som helst. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Proffstips*: Om din PDF har flera sidor med olika resursuppsättningar, upprepa detta block för varje sida du behöver ändra. Klassen `DictionaryEditor` är ett bekvämt omslag som låter dig behandla COS‑ordboken som en .NET `Dictionary`. + +## Steg 3 – Hämta eller initiera ExtGState‑ordboken + +**ExtGState‑ordboken** innehåller namngivna grafikstatus‑objekt (`GS0`, `GS1`, …). Vissa PDF‑filer har den redan; andra har den inte. Vi hämtar den på ett säkert sätt och skapar en ny tom om det behövs. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Varför vi gör detta*: Att försöka lägga till en grafikstatus i en icke‑existerande **ExtGState‑ordbok** skulle kasta ett undantag. Denna defensiva kontroll gör koden robust för vilken indata‑PDF som helst. + +## Steg 4 – Bygg ett nytt grafikstatus med CosPdfDictionary + +Nu kommer kärnan i handledningen: **skapa en tom PDF-ordbok** som definierar ett anpassat grafikstatus. Vi sätter linjeopacitet (`CA`), fyllningsopacitet (`ca`) och blandningsläge (`BM`). Du kan lägga till fler poster senare—detta är bara ett startpaket. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Förklaring*: +- `CA` och `ca` är standard‑PDF‑nycklar som styr linje‑ respektive fyllningsopacitet. +- `BM` väljer blandningsläget; “Normal” är standard men du kan använda “Multiply”, “Screen” osv., beroende på dina designbehov. +- Genom att använda `CosPdfDictionary.CreateEmptyDictionary` **skapar vi tomma PDF-ordbok**‑objekt som vi senare fyller med nyckel/värde‑par. + +## Steg 5 – Infoga det nya grafikstatuset i ExtGState + +När grafikstatuset är klart lägger vi helt enkelt till det i **ExtGState‑ordboken** under ett unikt namn (t.ex. `GS0`). Om du planerar att lägga till flera statusar, öka bara suffixet. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Tips*: Innan du lägger till kan du vilja kontrollera om `GS0` redan finns för att undvika överskrivning. En snabb `if (!extGState.ContainsKey("GS0"))`‑kontroll löser det. + +## Steg 6 – Spara den modifierade PDF‑filen + +Alla ändringar finns i minnet tills du sparar dem. Välj en utskrivningssökväg som passar ditt arbetsflöde. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Resultat*: Öppna `output.pdf` i någon PDF‑visare och inspektera sidresurserna (t.ex. med ett PDF‑inspektionsverktyg). Du kommer att se en ny post under **ExtGState** kallad `GS0` med de parametrar vi definierade. + +## Fullt fungerande exempel + +När vi sätter ihop allt, här är det kompletta, kopiera‑och‑klistra‑klara programmet: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Förväntat resultat**: `output.pdf` kommer att renderas exakt som originalet, men allt innehåll som senare refererar till `GS0` (t.ex. via `gs`‑operatorn i ett innehållsflöde) kommer att använda den definierade opaciteten och blandningsläget. Om du ännu inte har en sådan referens kan du lägga till en manuellt eller via Asposes högre‑nivå‑API:er. + +## Vanliga frågor & kantfall + +| Fråga | Svar | +|----------|--------| +| *Vad händer om PDF‑filen redan har en `ExtGState`‑post med namnet `GS0`?* | Kontrollera `extGState.ContainsKey("GS0")` innan du lägger till. Om den finns, antingen skriv över medvetet (`extGState["GS0"] = newGraphicsState`) eller välj ett nytt namn som `GS1`. | +| *Kan jag lägga till fler parametrar, som linjebredd (`LW`) eller streckmönster (`D`)?* | Absolut. Utöka bara `parameters`‑arrayen med ytterligare `KeyValuePair`‑poster. | +| *Är detta tillvägagångssätt kompatibelt med krypterade PDF‑filer?* | Ja, så länge du anger rätt lösenord när du skapar `Document` (`new Document(path, password)`). | +| *Behöver jag stänga dokumentet manuellt?* | `using`‑satsen tar hand om avyttring, vilket också spolar ut eventuella väntande ändringar. | +| *Hur skiljer sig detta från att använda den hög‑nivå `Graphics`‑klassen?* | Den hög‑nivå API:n abstraherar bort de underliggande ordböckerna, vilket är bra för enkla uppgifter. Men när du behöver fin‑kontroll över grafikstatusar—som anpassade blandningslägen—måste du arbeta med den låg‑nivå **CosPdfDictionary**, dvs. **skapa tom PDF-ordbok**‑objekt direkt. | + +## Slutsats + +Vi har just visat hur man **skapar tom PDF-ordbok**‑objekt med Aspose.Pdf, injicerar ett anpassat grafikstatus i **ExtGState‑ordboken**, och sparar den modifierade filen—allt i ren, idiomatisk C#. Detta mönster ger exakt kontroll över opacitet, blandningslägen och andra grafikstatus‑parametrar som definieras i PDF‑specifikationen. + +Från och med nu kan du: + +- Tillämpa det nya grafikstatuset på befintligt sidinnehåll med `gs`‑operatorn. +- Bygg ett bibliotek med återanvändbara grafikstatusar för varumärkesprofilering eller vattenstämpling. +- + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man skapar streckade linjer i PDF‑filer med Aspose.PDF för .NET: En steg‑för‑steg‑guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Skapa och fyll rektanglar i PDF‑filer med Aspose.PDF för .NET: En steg‑för‑steg‑guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/thai/net/digital-signatures/_index.md b/pdf/thai/net/digital-signatures/_index.md index 18d6010aee..0c63b6e267 100644 --- a/pdf/thai/net/digital-signatures/_index.md +++ b/pdf/thai/net/digital-signatures/_index.md @@ -64,6 +64,9 @@ ### [ตรวจสอบลายเซ็น PDF ด้วย Aspose – แปลง PDF เป็น HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) เรียนรู้วิธีตรวจสอบลายเซ็น PDF แล้วแปลงไฟล์เป็น HTML ด้วย Aspose.PDF สำหรับ .NET +### [ตรวจสอบลายเซ็น PDF และแสดงรายการลายเซ็น PDF ด้วย Aspose.PDF – คู่มือฉบับสมบูรณ์](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +เรียนรู้วิธีตรวจสอบความถูกต้องของลายเซ็น PDF และดึงรายการลายเซ็นทั้งหมดจากเอกสารด้วย Aspose.PDF อย่างละเอียด + ## แหล่งข้อมูลเพิ่มเติม - [Aspose.PDF สำหรับเอกสารประกอบ Net](https://docs.aspose.com/pdf/net/) diff --git a/pdf/thai/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/thai/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..a106b1bad6 --- /dev/null +++ b/pdf/thai/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: ตรวจสอบลายเซ็น PDF และแสดงรายการลายเซ็น PDF ด้วย Aspose.PDF ใน C# โค้ดทีละขั้นตอน + ข้อควรระวัง และแนวปฏิบัติที่ดีที่สุดสำหรับการจัดการเอกสารอย่างปลอดภัย +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: th +lastmod: 2026-07-26 +og_description: ตรวจสอบลายเซ็น PDF และแสดงรายการลายเซ็น PDF ด้วย Aspose.PDF ปฏิบัติตามคู่มือเชิงปฏิบัตินี้เพื่อรักษาความปลอดภัยของ + PDF ใน C# +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: ตรวจสอบลายเซ็น PDF และแสดงรายการลายเซ็น PDF – วิธีใช้ Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: ตรวจสอบลายเซ็น PDF และแสดงรายการลายเซ็น PDF ด้วย Aspose.PDF – คู่มือฉบับสมบูรณ์ +url: /th/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตรวจสอบลายเซ็น PDF และแสดงรายการลายเซ็น PDF ด้วย Aspose.PDF – คู่มือฉบับสมบูรณ์ + +เคยสงสัยไหมว่า จะ **validate PDF signature** ในแอป .NET อย่างไรโดยไม่ทำให้หัวเสีย? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณกำลังสร้างแพลตฟอร์ม e‑sign หรือแค่ต้องการตรวจสอบว่าข้อตกลงที่ได้รับไม่ได้ถูกดัดแปลง การสามารถ **list PDF signatures** และตรวจสอบแต่ละอันเป็นทักษะที่จำเป็น + +ในบทแนะนำนี้ เราจะพาคุณผ่านตัวอย่างที่สามารถรันได้เต็มรูปแบบซึ่งโหลด PDF ที่มีลายเซ็น, แสดงรายการลายเซ็นที่ฝังอยู่ทั้งหมด, ตรวจสอบว่ามีลายเซ็นใดถูกทำลายหรือไม่, และพิมพ์ผลลัพธ์ที่ชัดเจนไปยังคอนโซล ไม่ได้อ้างอิงแบบคลุมเครือ—เพียงโค้ดที่คุณสามารถคัดลอก‑วางได้ พร้อมเหตุผลของแต่ละขั้นตอน + +## ข้อกำหนดเบื้องต้น + +- **Aspose.PDF for .NET** เวอร์ชัน 25.3 หรือใหม่กว่า (คุณสมบัติ `IsCompromised` ปรากฏตั้งแต่เวอร์ชัน 25.3). +- สภาพแวดล้อมการพัฒนา .NET (Visual Studio 2022, Rider, หรือ `dotnet` CLI). +- ไฟล์ PDF ที่มีลายเซ็นซึ่งคุณสามารถทดสอบได้ (คุณสามารถสร้างได้ด้วย Adobe Acrobat หรือเครื่องมือ e‑signature ใด ๆ). + +หากขาดส่วนใดส่วนหนึ่ง ให้ติดตั้งแพคเกจ NuGet ก่อน: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **เคล็ดลับ:** ตั้งเป้าหมายเป็น .NET 6 หรือใหม่กว่าเพื่อประสิทธิภาพที่ดีที่สุดและการสนับสนุนระยะยาว. + +## ขั้นตอนที่ 1: โหลดเอกสาร PDF + +สิ่งแรกที่คุณต้องทำคือเปิดไฟล์ PDF. คลาส `Document` ของ Aspose.PDF จัดการทุกอย่างตั้งแต่การแยกวิเคราะห์จนถึงการแสดงผล. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*ทำไมเรื่องนี้ถึงสำคัญ:* การโหลดไฟล์จะสร้างการแสดงผลในหน่วยความจำที่ทำให้คุณสามารถสอบถามลายเซ็นได้โดยไม่ต้องเข้าถึงระบบไฟล์อีกครั้ง นอกจากนี้ยังตรวจสอบโครงสร้าง PDF ตั้งแต่ต้น ดังนั้นหากไฟล์เสียหายคุณจะได้รับข้อยกเว้นทันที. + +## ขั้นตอนที่ 2: **List PDF Signatures** – แสดงรายการลายเซ็นที่ฝังอยู่ทั้งหมด + +PDF ที่มีลายเซ็นอาจมีหลายลายเซ็น (เช่น สัญญาหลายหน้าโดยแต่ละฝ่ายลงนามในหน้าที่ต่างกัน). Aspose.PDF เปิดให้เข้าถึงผ่านคอลเลกชัน `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*สิ่งที่คุณเห็น:* ลูปนี้พิมพ์รายละเอียดของ **list PDF signatures** เช่น ชื่อผู้ลงนาม, เหตุผล, สถานที่, และเวลา นี่เป็นประโยชน์สำหรับบันทึกการตรวจสอบหรือการแสดงผลใน UI. + +## ขั้นตอนที่ 3: **Validate PDF Signature** – ตรวจสอบการถูกทำลาย + +ตอนนี้เป็นส่วนที่สำคัญด้านความปลอดภัย: ยืนยันว่าไม่มีลายเซ็นใดถูกแก้ไขหลังจากการลงนาม ตั้งแต่เวอร์ชัน 25.3, Aspose.PDF มีฟล็ก `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*ทำไมคุณควรใช้ `IsCompromised`*: การตรวจสอบแบบดั้งเดิมตรวจสอบเฉพาะห่วงโซ่การเข้ารหัส (ความถูกต้องของใบรับรอง, การเพิกถอน, ฯลฯ). `IsCompromised` เพิ่มชั้นเพิ่มเติมโดยตรวจจับการเปลี่ยนแปลงใด ๆ หลังการลงนามในเอกสาร—ตรงกับสิ่งที่คุณต้องการเมื่อ **validate PDF signature** เพื่อตรวจสอบการดัดแปลง. + +## ขั้นตอนที่ 4: การจัดการผลการตรวจสอบ + +ขึ้นอยู่กับผลลัพธ์ คุณอาจต้องทำการต่าง ๆ นี่คือตัวอย่างรูปแบบที่คุณสามารถปรับใช้ได้: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*หมายเหตุกรณีขอบ:* หาก PDF มีลายเซ็น **certified** (ลายเซ็นแรกที่ล็อกเอกสาร), การแก้ไขภายหลังอาจทำให้ไฟล์ทั้งหมดไม่ถูกต้อง แม้ว่าลายเซ็นต่อมาจะดูปกติ ก็ตาม ให้ถือว่า `true` จาก `IsCompromised` เป็นสัญญาณเตือน. + +## ตัวอย่างการทำงานเต็มรูปแบบ + +เมื่อนำทุกอย่างมารวมกัน นี่คือโปรแกรมเดียวที่มีทุกอย่างซึ่งคุณสามารถคอมไพล์และรันได้: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**ผลลัพธ์ที่คาดหวัง** (สมมติว่ามีลายเซ็นที่ดีหนึ่งอันและลายเซ็นที่ถูกดัดแปลงหนึ่งอัน): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## ข้อผิดพลาดทั่วไป & วิธีหลีกเลี่ยง + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Missing Aspose.PDF version** | `IsCompromised` ถูกแนะนำในเวอร์ชัน 25.3. แพคเกจเก่าจะคอมไพล์ได้แต่จะโยน `MissingMethodException`. | ตรวจสอบให้แน่ใจว่าอ้างอิง NuGet ของคุณเป็น `>= 25.3`. | +| **Null `SignatureInfo`** | PDF บางไฟล์มีช่องลายเซ็นว่างที่ยังปรากฏในคอลเลกชัน. | ตรวจสอบด้วย `if (signatureInfo != null)` ก่อนทำการตรวจสอบ. | +| **Performance hit on large PDFs** | การตรวจสอบทุกลายเซ็นจะอ่านไฟล์ทั้งหมดทุกครั้ง. | แคช `PdfSignatureValidator` หรือประมวลผลลายเซ็นเป็นชุดถ้าคุณต้องการสรุปเป็นค่า boolean เท่านั้น. | +| **Certificate revocation not checked** | `IsCompromised` บอกเฉพาะการเปลี่ยนแปลงของเอกสาร ไม่ได้บ่งบอกสถานะของใบรับรอง. | ใช้ `PdfSignatureValidator.Validate()` ร่วมกับ `IsCompromised` เพื่อการตรวจสอบ PKI อย่างเต็มรูปแบบ. | + +## การขยายโซลูชัน + +หากคุณต้องการ **list PDF signatures** ใน UI เพียงแค่ส่งออบเจ็กต์ `SignatureInfo` ไปยัง data grid. ต้องการเก็บผลการตรวจสอบในฐานข้อมูลหรือไม่? ทำการ serialize ค่า boolean `isCompromised` พร้อมกับชื่อผู้ลงนามและเวลา. + +หัวข้อที่เกี่ยวข้องอื่น ๆ ที่คุณอาจสนใจต่อไป: + +- **Validate PDF signature against a trusted root CA** (ใช้ `validator.Validate()`). +- **Extract embedded certificate details** (`validator.Certificate`). +- **Create digital signatures** with Aspose.PDF (`PdfSignatureBuilder`). + +## สรุป + +ตอนนี้คุณมีวิธีการเชิงปฏิบัติแบบครบวงจรเพื่อ **validate PDF signature** และ **list PDF signatures** ด้วย Aspose.PDF สำหรับ .NET โค้ดแสดงให้เห็นอย่างชัดเจนว่าต้องโหลดเอกสารอย่างไร, แสดงรายการลายเซ็นแต่ละอัน, ตรวจสอบฟล็ก `IsCompromised`, และดำเนินการตามผลลัพธ์—ทั้งหมดในรูปแบบที่อ่านง่ายบนคอนโซล. + +ลองใช้กับ PDF ที่คุณลงนามเอง, ทดลองกับหลายลายเซ็น, และรวมตรรกะนี้เข้าไปใน pipeline การประมวลผลเอกสารของคุณ PDF ที่ปลอดภัยมีความแข็งแกร่งเท่ากับการตรวจสอบที่คุณทำ ดังนั้นให้ตรวจสอบอย่างเข้มงวดและบันทึกอย่างละเอียด. + +มีคำถามหรืออยากแชร์กรณีการใช้งานที่เจ๋ง? แสดงความคิดเห็นด้านล่างหรือส่งข้อความถึงฉันบน GitHub. โค้ดดิ้งสนุก! + +![ตรวจสอบลายเซ็น PDF](/images/validate-pdf-signature.png "Screenshot of a C# console app validating a PDF signature with Aspose.PDF") + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการนำไปใช้แบบอื่นในโครงการของคุณ. + +- [วิธีตรวจสอบ PDF – Validate PDF Signature กับ Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [วิธีดึงข้อมูลลายเซ็น PDF ด้วย Aspose.PDF .NET: คู่มือทีละขั้นตอน](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [วิธีดึงรูปภาพจากฟิลด์ลายเซ็น PDF ด้วย Aspose.PDF for .NET: คู่มือทีละขั้นตอน](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/thai/net/programming-with-operators/_index.md b/pdf/thai/net/programming-with-operators/_index.md index b18b824bb2..0195f2851b 100644 --- a/pdf/thai/net/programming-with-operators/_index.md +++ b/pdf/thai/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ - [วาด XForm บนหน้า](./draw-xform-on-page/) | เรียนรู้วิธีการวาด XForms ใน PDF โดยใช้ Aspose.PDF สำหรับ .NET พร้อมคู่มือทีละขั้นตอนที่ครอบคลุมนี้ - [ตัวดำเนินการ PDF](./pdf-operators/) | คำแนะนำทีละขั้นตอนในการใช้ตัวดำเนินการ PDF กับ Aspose.PDF สำหรับ .NET เพิ่มรูปภาพลงในหน้า PDF และระบุตำแหน่งของรูปภาพ - | [ลบวัตถุกราฟิกออกจากไฟล์ PDF](./remove-graphics-objects/) เรียนรู้วิธีการลบวัตถุกราฟิกออกจากไฟล์ PDF โดยใช้ Aspose.PDF สำหรับ .NET ในคู่มือทีละขั้นตอนนี้ ทำให้ภารกิจการจัดการ PDF ของคุณง่ายขึ้น | +- [สร้างพจนานุกรม PDF ว่างใน C# – คู่มือ Aspose.Pdf ฉบับสมบูรณ์](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | เรียนรู้วิธีสร้างพจนานุกรม PDF ว่างใน C# ด้วย Aspose.PDF อย่างละเอียดในคู่มือฉบับสมบูรณ์ {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/thai/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/thai/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..8cd5e774ec --- /dev/null +++ b/pdf/thai/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: สร้างพจนานุกรม PDF ว่างด้วย Aspose.Pdf ใน C#. เรียนรู้ขั้นตอนโดยละเอียดว่าต้องเพิ่มสถานะกราฟิกไปยังพจนานุกรม + ExtGState เพื่อการจัดการ PDF อย่างไร. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: th +lastmod: 2026-07-26 +og_description: สร้างพจนานุกรม PDF ว่างโดยใช้ Aspose.Pdf สำหรับ C# ปฏิบัติตามคู่มือเชิงปฏิบัตินี้เพื่อแก้ไขสถานะกราฟิกใน + PDF ของคุณ. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: สร้างพจนานุกรม PDF ว่างใน C# – บทเรียนเต็ม Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: สร้างพจนานุกรม PDF ว่างใน C# – คู่มือ Aspose.Pdf ฉบับสมบูรณ์ +url: /th/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างพจนานุกรม PDF ว่างใน C# – คู่มือ Aspose.Pdf ฉบับสมบูรณ์ + +เคยสงสัยไหมว่าจะแทรก **create empty PDF dictionary** อย่างไรเมื่อปรับเปลี่ยนสถานะกราฟิกของ PDF? คุณไม่ได้เป็นคนเดียว—นักพัฒนาหลายคนเจออุปสรรคนี้เมื่อต้องปรับความทึบหรือโหมดการผสมแบบโปรแกรม ในบทแนะนำนี้เราจะพาคุณผ่านวิธีแก้ปัญหาโดยใช้ Aspose.Pdf สำหรับ C# โดยแสดงอย่างชัดเจนว่าจะแทรกสถานะกราฟิกใหม่เข้าไปในพจนานุกรม *ExtGState* ของ PDF ที่มีอยู่ + +เราจะครอบคลุมทุกอย่างที่คุณต้องการ: การโหลด PDF, การเข้าถึงพจนานุกรมทรัพยากร, การสร้าง **CosPdfDictionary** ใหม่, และสุดท้ายการบันทึกการเปลี่ยนแปลง เมื่อเสร็จคุณจะมีรูปแบบที่นำกลับมาใช้ใหม่ได้สำหรับการปรับ *PDF graphics state* ใด ๆ ที่คุณต้องการ + +--- + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีการ **create empty PDF dictionary** ด้วย API ระดับต่ำของ Aspose.Pdf. +- บทบาทของ **ExtGState dictionary** ในการควบคุมความทึบของเส้นและการเติมและโหมดการผสม. +- เคล็ดลับเชิงปฏิบัติสำหรับการจัดการ PDF ด้วย C# รวมถึงการจัดการกรณีขอบเมื่อพจนานุกรมหายไป. +- ตัวอย่างโค้ดที่สมบูรณ์และสามารถรันได้ที่คุณสามารถคัดลอก‑วางลงในโปรเจคของคุณ. + +### ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (โค้ดทำงานกับ .NET Framework 4.6+ ด้วย). +- สำเนา **Aspose.Pdf for .NET** ที่มีลิขสิทธิ์ (รุ่นทดลองฟรีใช้สำหรับทดสอบ). +- ความคุ้นเคยพื้นฐานกับ C# และแนวคิด PDF เช่น resources และ graphics states. + +หากสิ่งใดเหล่านี้ฟังดูไม่คุ้นเคย อย่าตื่นตระหนก—คุณสามารถติดตั้ง Aspose.Pdf ผ่าน NuGet (`Install-Package Aspose.Pdf`) และส่วนที่เหลือก็เป็นแค่ C# ธรรมดา. + +--- + +## ขั้นตอนที่ 1 – โหลดเอกสาร PDF + +สิ่งแรกที่ต้องทำคือคุณต้องมีอ็อบเจ็กต์ `Document` ที่แทนไฟล์ที่คุณต้องการแก้ไข การห่อหุ้มด้วยบล็อก `using` จะรับประกันการกำจัดที่เหมาะสม. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*ทำไมเรื่องนี้สำคัญ*: การเปิดไฟล์ทำให้คุณเข้าถึงอ็อบเจ็กต์ COS (Canonical Object Structure) ภายใน ซึ่งเป็นที่ที่ **CosPdfDictionary** อยู่ หากไม่มีอ็อบเจ็กต์เอกสารคุณจะไม่สามารถเข้าถึงพจนานุกรมทรัพยากรที่เก็บรายการ **ExtGState** ได้. + +--- + +## ขั้นตอนที่ 2 – เข้าถึงพจนานุกรมทรัพยากรของหน้าแรก + +หน้าของ PDF จะเก็บทรัพยากรของมัน (ฟอนต์, รูปภาพ, graphics states ฯลฯ) ในพจนานุกรมเฉพาะ เราจะดึงหน้าแรกเพื่อความง่าย แต่ตรรกะเดียวกันใช้ได้กับดัชนีหน้าที่ใดก็ได้. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*เคล็ดลับ*: หาก PDF ของคุณมีหลายหน้าโดยมีชุดทรัพยากรที่แตกต่างกัน ให้ทำซ้ำบล็อกนี้สำหรับแต่ละหน้าที่คุณต้องการแก้ไข คลาส `DictionaryEditor` เป็นตัวห่อที่สะดวกที่ทำให้คุณสามารถจัดการพจนานุกรม COS เหมือนกับ .NET `Dictionary`. + +--- + +## ขั้นตอนที่ 3 – ดึงหรือกำหนดค่าเริ่มต้นพจนานุกรม ExtGState + +พจนานุกรม **ExtGState** เก็บอ็อบเจ็กต์ graphics state ที่ตั้งชื่อ (`GS0`, `GS1`, …) PDF บางไฟล์มีอยู่แล้ว; บางไฟล์ไม่มี เราจะดึงอย่างปลอดภัยและสร้างพจนานุกรมว่างใหม่หากจำเป็น. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*ทำไมเราต้องทำเช่นนี้*: การพยายามเพิ่ม graphics state ลงใน **ExtGState dictionary** ที่ไม่มีอยู่จะทำให้เกิดข้อยกเว้น การตรวจสอบเชิงป้องกันนี้ทำให้โค้ดทนทานต่อ PDF ใด ๆ ที่เป็นอินพุต. + +--- + +## ขั้นตอนที่ 4 – สร้าง Graphics State ใหม่ด้วย CosPdfDictionary + +ตอนนี้เป็นส่วนสำคัญของบทแนะนำ: **creating an empty PDF dictionary** ที่กำหนด graphics state แบบกำหนดเอง เราจะตั้งค่าความทึบของเส้น (`CA`), ความทึบของการเติม (`ca`), และโหมดการผสม (`BM`). คุณสามารถเพิ่มรายการเพิ่มเติมในภายหลัง—นี่เป็นชุดเริ่มต้นเท่านั้น. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*คำอธิบาย*: +- `CA` และ `ca` เป็นคีย์มาตรฐานของ PDF ที่ควบคุมความทึบของเส้นและการเติมตามลำดับ. +- `BM` เลือกโหมดการผสม; “Normal” เป็นค่าเริ่มต้นแต่คุณสามารถใช้ “Multiply”, “Screen”, ฯลฯ ตามความต้องการของการออกแบบ. +- โดยใช้ `CosPdfDictionary.CreateEmptyDictionary` เรา **create empty PDF dictionary** อ็อบเจ็กต์ที่เราจะเติมค่าคู่คีย์/ค่าในภายหลัง. + +--- + +## ขั้นตอนที่ 5 – แทรก Graphics State ใหม่เข้าไปใน ExtGState + +เมื่อ graphics state พร้อม เราเพียงแค่เพิ่มมันเข้าไปใน **ExtGState dictionary** ภายใต้ชื่อที่ไม่ซ้ำกัน (เช่น `GS0`). หากคุณวางแผนจะเพิ่มหลายสถานะ เพียงเพิ่มตัวเลขต่อท้าย. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*เคล็ดลับ*: ก่อนเพิ่ม คุณอาจต้องตรวจสอบว่า `GS0` มีอยู่แล้วหรือไม่เพื่อหลีกเลี่ยงการเขียนทับ การตรวจสอบแบบ `if (!extGState.ContainsKey("GS0"))` อย่างรวดเร็วก็ทำได้. + +--- + +## ขั้นตอนที่ 6 – บันทึก PDF ที่แก้ไขแล้ว + +การเปลี่ยนแปลงทั้งหมดอยู่ในหน่วยความจำจนกว่าคุณจะบันทึกลงไฟล์ เลือกเส้นทางเอาต์พุตที่เหมาะกับกระบวนการทำงานของคุณ. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*ผลลัพธ์*: เปิด `output.pdf` ด้วยโปรแกรมดู PDF ใดก็ได้ แล้วตรวจสอบทรัพยากรของหน้า (เช่น ด้วยเครื่องมือตรวจสอบ PDF). คุณจะเห็นรายการใหม่ใน **ExtGState** ชื่อ `GS0` พร้อมพารามิเตอร์ที่เรากำหนด. + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ + +เมื่อรวมทุกอย่างเข้าด้วยกัน นี่คือโปรแกรมที่สมบูรณ์พร้อมคัดลอก‑วาง: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**ผลลัพธ์ที่คาดหวัง**: `output.pdf` จะแสดงผลเหมือนต้นฉบับ แต่เนื้อหาใด ๆ ที่อ้างอิงถึง `GS0` ต่อมา (เช่น ผ่านตัวดำเนินการ `gs` ในสตรีมเนื้อหา) จะใช้ความทึบและโหมดการผสมที่กำหนด หากคุณยังไม่มีการอ้างอิงดังกล่าว คุณสามารถเพิ่มด้วยตนเองหรือผ่าน API ระดับสูงของ Aspose. + +--- + +## คำถามที่พบบ่อย & กรณีขอบ + +| Question | Answer | +|----------|--------| +| *ถ้า PDF มีรายการ `ExtGState` ชื่อ `GS0` อยู่แล้วจะทำอย่างไร?* | ตรวจสอบ `extGState.ContainsKey("GS0")` ก่อนเพิ่ม หากมีอยู่แล้ว ให้เขียนทับโดยเจตนา (`extGState["GS0"] = newGraphicsState`) หรือเลือกชื่อใหม่เช่น `GS1`. | +| *ฉันสามารถเพิ่มพารามิเตอร์อื่น ๆ เช่น ความกว้างของเส้น (`LW`) หรือรูปแบบจุดประหลาด (`D`) ได้หรือไม่?* | ได้เลย เพียงขยายอาร์เรย์ `parameters` ด้วยรายการ `KeyValuePair` เพิ่มเติม. | +| *วิธีนี้เข้ากันได้กับ PDF ที่เข้ารหัสหรือไม่?* | ใช่ ตราบใดที่คุณให้รหัสผ่านที่ถูกต้องเมื่อสร้าง `Document` (`new Document(path, password)`). | +| *ฉันต้องปิดเอกสารด้วยตนเองหรือไม่?* | `using` จะจัดการการกำจัดให้โดยอัตโนมัติ ซึ่งยังทำการบันทึกการเปลี่ยนแปลงที่ค้างอยู่ด้วย. | +| *วิธีนี้แตกต่างจากการใช้คลาส `Graphics` ระดับสูงอย่างไร?* | API ระดับสูงจะซ่อนพจนานุกรมพื้นฐานซึ่งเหมาะกับงานง่าย ๆ อย่างไรก็ตาม เมื่อคุณต้องการการควบคุมละเอียดของ graphics states—เช่นโหมดการผสมแบบกำหนดเอง—คุณต้องทำงานกับ **CosPdfDictionary** ระดับต่ำ คืออ็อบเจ็กต์ **create empty PDF dictionary** โดยตรง. | + +--- + +## สรุป + +เราพึ่งแสดงวิธี **create empty PDF dictionary** ด้วย Aspose.Pdf, แทรก graphics state แบบกำหนดเองเข้าไปใน **ExtGState dictionary**, และบันทึกไฟล์ที่แก้ไข—ทั้งหมดใน C# ที่สะอาดและเป็นธรรมชาติ รูปแบบนี้เปิดการควบคุมที่แม่นยำต่อความทึบ, โหมดการผสม, และพารามิเตอร์ graphics‑state อื่น ๆ ที่กำหนดโดยสเปค PDF. + +จากนี้คุณอาจ: + +- ใช้ graphics state ใหม่กับเนื้อหาหน้าที่มีอยู่โดยใช้ตัวดำเนินการ `gs`. +- สร้างไลบรารีของ graphics state ที่นำกลับมาใช้ได้สำหรับการสร้างแบรนด์หรือการใส่ลายน้ำ. +- + +## สิ่งที่คุณควรเรียนต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานทางเลือกในโปรเจคของคุณเอง. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/turkish/net/digital-signatures/_index.md b/pdf/turkish/net/digital-signatures/_index.md index d1543118fd..885e775eea 100644 --- a/pdf/turkish/net/digital-signatures/_index.md +++ b/pdf/turkish/net/digital-signatures/_index.md @@ -64,6 +64,8 @@ C# kullanarak PDF belgesini yükleyin, PDF/X‑4 formatına dönüştürün ve i ### [Aspose ile PDF İmzasını Doğrulama – PDF'yi HTML'ye Dönüştür](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Aspose kullanarak PDF imzasını doğrularken aynı zamanda PDF'yi HTML formatına dönüştürmeyi öğrenin. +### [Aspose.PDF ile PDF İmzasını Doğrulama ve PDF İmzalarını Listeleme – Tam Kılavuz](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) + ## Ek Kaynaklar - [Net Belgeleme için Aspose.PDF](https://docs.aspose.com/pdf/net/) diff --git a/pdf/turkish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/turkish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..a882ee5156 --- /dev/null +++ b/pdf/turkish/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-26 +description: Aspose.PDF kullanarak C#'de PDF imzasını doğrulayın ve PDF imzalarını + listeleyin. Adım adım kod, dikkat edilmesi gereken noktalar ve güvenli belge işleme + için en iyi uygulamalar. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: tr +lastmod: 2026-07-26 +og_description: Aspose.PDF ile PDF imzasını doğrulayın ve PDF imzalarını listeleyin. + C#'ta PDF'leri güvence altına almak için bu pratik rehberi izleyin. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: PDF İmzasını Doğrula ve PDF İmzalarını Listele – Aspose.PDF Nasıl‑Yapılır +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Aspose.PDF ile PDF İmzasını Doğrulama ve PDF İmzalarını Listeleme – Tam Rehber +url: /tr/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF İmzasını Doğrulama ve PDF İmzalarını Listeleme Aspose.PDF – Tam Kılavuz + +Hiç .NET uygulamasında **PDF imzasını doğrulama** konusunda saçınızı yolmak zorunda kalmadan merak ettiniz mi? Tek başınıza değilsiniz. İster bir e‑imza platformu geliştiriyor olun, ister alınan bir sözleşmenin değiştirilip değiştirilmediğini kontrol etmeniz gerekiyor olsun, **PDF imzalarını listeleme** ve her birini doğrulama yeteneği olmazsa olmaz bir beceridir. + +Bu öğreticide, imzalı bir PDF dosyasını yükleyen, tüm gömülü imzaları enumerate eden, herhangi birinin bozulup bozulmadığını kontrol eden ve sonucu konsola net bir şekilde yazdıran tamamen çalıştırılabilir bir örnek üzerinden adım adım ilerleyeceğiz. Belirsiz referanslar yok—sadece kopyalayıp‑yapıştırabileceğiniz kod ve her adımın “neden”i. + +## Önkoşullar + +- **Aspose.PDF for .NET** version 25.3 veya daha yeni (`IsCompromised` özelliği 25.3'te ortaya çıktı). +- .NET geliştirme ortamı (Visual Studio 2022, Rider veya `dotnet` CLI). +- Test edebileceğiniz imzalı bir PDF dosyası (Adobe Acrobat veya herhangi bir e‑imza aracıyla oluşturabilirsiniz). + +Eğer bunlardan biri eksikse, önce NuGet paketini yükleyin: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Pro tip:** En iyi performans ve uzun vadeli destek için .NET 6 veya daha yeni bir sürümü hedefleyin. + +## Adım 1: PDF Belgesini Yükleme + +İlk yapmanız gereken PDF dosyasını açmaktır. Aspose.PDF’nin `Document` sınıfı, ayrıştırmadan renderlamaya kadar her şeyi yönetir. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Neden önemli:* Dosyayı yüklemek, dosya sistemine tekrar dokunmadan imzaları sorgulamanızı sağlayan bellek içi bir temsil oluşturur. Ayrıca PDF yapısını erken doğrular, böylece dosya bozuksa hemen bir istisna alırsınız. + +## Adım 2: **PDF İmzalarını Listeleme** – Tüm Gömülü İmzaları Enumerate Etme + +İmzalı bir PDF birden fazla imza içerebilir (her tarafın farklı bir sayfayı imzaladığı çok sayfalı bir sözleşme gibi düşünün). Aspose.PDF, bunları `Signatures` koleksiyonu aracılığıyla sunar. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Gördükleriniz:* Döngü, imzalayanın adı, nedeni, konumu ve zaman damgası gibi **PDF imzalarını listeleme** detaylarını yazdırır. Bu, denetim günlükleri veya UI gösterimleri için kullanışlıdır. + +## Adım 3: **PDF İmzasını Doğrulama** – Bozulma Kontrolü + +Şimdi güvenlik açısından kritik kısma geliyoruz: imzalar imzalandıktan sonra hiçbirinin değiştirilmediğini doğrulamak. 25.3 sürümünden itibaren, Aspose.PDF `PdfSignatureValidator.IsCompromised` bayrağını sunar. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Neden `IsCompromised` kullanmalısınız*: Geleneksel doğrulama yalnızca kriptografik zinciri (sertifika geçerliliği, iptal vb.) kontrol eder. `IsCompromised`, belgeye imzadan sonra yapılan değişiklikleri tespit ederek ekstra bir katman ekler—tam da **PDF imzasını doğrulama** sırasında manipülasyonu tespit etmek için ihtiyacınız olan şey. + +## Adım 4: Doğrulama Sonuçlarını İşleme + +Sonuca bağlı olarak farklı eylemler gerçekleştirmek isteyebilirsiniz. İşte uyarlayabileceğiniz hızlı bir desen: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Köşe durum notu:* PDF bir **sertifikalı** imza (belgeyi kilitleyen ilk imza) içeriyorsa, sonraki bir değişiklik tüm dosyayı geçersiz kılabilir, sonraki imzalar iyi görünse bile. `IsCompromised` değerinin `true` olması her zaman bir uyarı işareti olarak değerlendirilmelidir. + +## Tam Çalışan Örnek + +Her şeyi bir araya getirerek, derleyip çalıştırabileceğiniz tek bir, bağımsız program burada: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Beklenen çıktı** (bir iyi imza ve bir bozulmuş imza varsayarak): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Yaygın Tuzaklar ve Nasıl Kaçınılır + +| Tuzak | Neden Oluşur | Çözüm | +|------|--------------|------| +| **Aspose.PDF sürümü eksik** | `IsCompromised` 25.3'te tanıtıldı. Daha eski paketler derlenir ancak `MissingMethodException` fırlatır. | NuGet referansınızın `>= 25.3` olduğundan emin olun. | +| **Null `SignatureInfo`** | Bazı PDF'lerde koleksiyonda hâlâ görünen boş imza yuvaları bulunur. | Doğrulamadan önce `if (signatureInfo != null)` kontrolü ekleyin. | +| **Büyük PDF'lerde performans düşüşü** | Her imzayı doğrulamak dosyanın tamamını her seferinde okur. | Sadece boolean özetine ihtiyacınız varsa `PdfSignatureValidator`'ı önbelleğe alın veya imzaları toplu işleyin. | +| **Sertifika iptali kontrol edilmedi** | `IsCompromised` sadece belge değişikliklerini bildirir, sertifika durumunu değil. | Tam PKI kontrolleri için `IsCompromised` ile birlikte `PdfSignatureValidator.Validate()` kullanın. | + +## Çözümü Genişletme + +Eğer bir UI'da **PDF imzalarını listeleme** ihtiyacınız varsa, `SignatureInfo` nesnelerini doğrudan bir veri ızgarasına besleyin. Doğrulama sonuçlarını bir veritabanında saklamak ister misiniz? Boolean `isCompromised` değerini imzalayanın adı ve zaman damgası ile birlikte serileştirin. + +İleride keşfedebileceğiniz diğer ilgili konular: + +- **Güvenilir bir kök CA'ya karşı PDF imzasını doğrulama** (`validator.Validate()` kullanın). +- **Gömülü sertifika detaylarını çıkarma** (`validator.Certificate`). +- **Aspose.PDF ile dijital imzalar oluşturma** (`PdfSignatureBuilder`). + +## Sonuç + +Artık Aspose.PDF for .NET kullanarak **PDF imzasını doğrulama** ve **PDF imzalarını listeleme** için uygulamalı, uçtan uca bir yönteme sahipsiniz. Kod, bir belgeyi nasıl yükleyeceğinizi, her imzayı nasıl enumerate edeceğinizi, `IsCompromised` bayrağını nasıl kontrol edeceğinizi ve sonucu nasıl işleyeceğinizi net, konsol‑dostu bir formatta gösteriyor. + +Kendi imzalı PDF'lerinizle deneyin, birden fazla imza ile oynayın ve mantığı daha büyük belge‑işleme hattınıza entegre edin. Güvenli PDF'ler, yaptığınız doğrulama kadar güçlüdür; bu yüzden kontrolleri sıkı tutun ve günlükleri ayrıntılı tutun. + +Sorularınız mı var ya da ilginç bir kullanım senaryosu paylaşmak mı istiyorsunuz? Aşağıya bir yorum bırakın ya da GitHub'ta bana mesaj atın. İyi kodlamalar! + +![PDF İmzasını Doğrulama](/images/validate-pdf-signature.png "Aspose.PDF ile bir C# konsol uygulamasının PDF imzasını doğrulamasının ekran görüntüsü") + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [PDF'yi Doğrulama – Aspose ile PDF İmzasını Doğrulama](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Aspose.PDF .NET Kullanarak PDF İmza Bilgilerini Çıkarma – Adım Adım Kılavuz](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Aspose.PDF for .NET ile PDF İmza Alanlarından Görüntü Çıkarma – Adım Adım Kılavuz](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/turkish/net/programming-with-operators/_index.md b/pdf/turkish/net/programming-with-operators/_index.md index 20dfde302d..9d4064c22d 100644 --- a/pdf/turkish/net/programming-with-operators/_index.md +++ b/pdf/turkish/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ Aspose.PDF for .NET'in "Operatörlerle Programlama" eğitimleri, PDF programlama | --- | --- | | [Sayfada XForm Çiz](./draw-xform-on-page/) | Bu kapsamlı adım adım kılavuzla .NET için Aspose.PDF kullanarak PDF'de XForms'un nasıl çizileceğini öğrenin. | | [PDF Operatörleri](./pdf-operators/) | Aspose.PDF for .NET ile PDF operatörlerini kullanma konusunda adım adım kılavuz. Bir PDF sayfasına resim ekleyin ve konumunu belirtin. | -| [PDF Dosyasındaki Grafik Nesnelerini Kaldır](./remove-graphics-objects/) Bu adım adım kılavuzda Aspose.PDF for .NET kullanarak bir PDF dosyasından grafik nesnelerinin nasıl kaldırılacağını öğrenin. PDF düzenleme görevlerinizi basitleştirin. | +| [PDF Dosyasındaki Grafik Nesnelerini Kaldır](./remove-graphics-objects/) | Bu adım adım kılavuzda Aspose.PDF for .NET kullanarak bir PDF dosyasından grafik nesnelerinin nasıl kaldırılacağını öğrenin. PDF düzenleme görevlerinizi basitleştirin. | +| [C#'ta Boş PDF Sözlüğü Oluşturma – Tam Aspose.Pdf Rehberi](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Aspose.PDF for .NET kullanarak C# ile boş bir PDF sözlüğü oluşturmayı adım adım öğrenin. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/turkish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/turkish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..bd1bf96635 --- /dev/null +++ b/pdf/turkish/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: Aspose.Pdf ile C#'ta boş PDF sözlüğü oluşturun. PDF manipülasyonu için + ExtGState sözlüğüne bir grafik durumu eklemeyi adım adım öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: tr +lastmod: 2026-07-26 +og_description: Aspose.Pdf for C# kullanarak boş PDF sözlüğü oluşturun. PDF'lerinizde + grafik durumlarını değiştirmek için bu uygulamalı kılavuzu izleyin. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: C#'ta Boş PDF Sözlüğü Oluşturma – Tam Aspose.Pdf Öğreticisi +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: C#'ta Boş PDF Sözlüğü Oluşturma – Tam Aspose.Pdf Rehberi +url: /tr/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta Boş PDF Sözlüğü Oluşturma – Tam Aspose.Pdf Rehberi + +Bir PDF'in grafik durumunu ayarlarken **boş PDF sözlüğü** girdileri oluşturmanız gerektiğini hiç merak ettiniz mi? Tek değilsiniz—birçok geliştirici, opaklık ya da karışım modlarını programatik olarak ayarlamaya çalışırken bu soruna takılıyor. Bu öğreticide, mevcut bir PDF'in *ExtGState* sözlüğüne yeni bir grafik durumu enjekte etmenin tam çözümünü Aspose.Pdf for C# kullanarak adım adım göstereceğiz. + +PDF'i yükleme, kaynak sözlüğüne erişme, yeni bir **CosPdfDictionary** oluşturma ve sonunda değişiklikleri kaydetme konularını ele alacağız. Sonunda, ihtiyacınız olabilecek herhangi bir *PDF grafik durumu* ayarı için yeniden kullanılabilir bir deseniniz olacak. + +--- + +## Öğrenecekleriniz + +- Aspose.Pdf’in düşük seviyeli API’si ile **boş PDF sözlüğü** nesneleri nasıl oluşturulur. +- **ExtGState sözlüğünün** çizgi/alan opaklığı ve karışım modlarını kontrol etmedeki rolü. +- C# PDF manipülasyonu için pratik ipuçları, sözlüğün eksik olduğu durumların ele alınması dahil. +- Projenize kopyalayıp yapıştırabileceğiniz tam, çalıştırılabilir bir kod örneği. + +### Önkoşullar + +- .NET 6.0 veya üzeri (kod .NET Framework 4.6+ ile de çalışır). +- **Aspose.Pdf for .NET** lisanslı bir kopya (ücretsiz deneme sürümü test için yeterli). +- C# ve PDF kavramları (kaynaklar ve grafik durumları gibi) hakkında temel bilgi. + +Eğer bunlar size yabancı geliyorsa panik yapmayın—Aspose.Pdf’i NuGet üzerinden (`Install-Package Aspose.Pdf`) kurabilir ve geri kalan kısmı sadece saf C# ile halledebilirsiniz. + +--- + +## 1. Adım – PDF Belgesini Yükleyin + +İlk iş, düzenlemek istediğiniz dosyayı temsil eden bir `Document` nesnesine sahip olmak. Bunu bir `using` bloğu içinde sarmalamak, doğru şekilde imha edilmesini garantiler. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Neden önemli*: Dosyayı açmak, **CosPdfDictionary**'nin bulunduğu iç COS (Canonical Object Structure) nesnelerine erişmenizi sağlar. Document nesnesi olmadan, **ExtGState** girdilerini tutan kaynak sözlüklerine ulaşamazsınız. + +--- + +## 2. Adım – İlk Sayfanın Kaynak Sözlüğüne Erişin + +PDF sayfaları, kaynaklarını (fontlar, görseller, grafik durumları vb.) ayrı bir sözlükte saklar. Basitlik açısından ilk sayfayı çekeceğiz, ancak aynı mantık herhangi bir sayfa indeksi için geçerlidir. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*İpucu*: PDF'inizde farklı kaynak setlerine sahip birden fazla sayfa varsa, değiştirmek istediğiniz her sayfa için bu bloğu tekrarlayın. `DictionaryEditor` sınıfı, COS sözlüğünü .NET `Dictionary` gibi kullanmanızı sağlayan kullanışlı bir sarmalayıcıdır. + +--- + +## 3. Adım – ExtGState Sözlüğünü Alın ya da Başlatın + +**ExtGState sözlüğü**, adlandırılmış grafik durumu nesnelerini (`GS0`, `GS1`, …) tutar. Bazı PDF'lerde zaten bulunur; bazılarında yoktur. Güvenli bir şekilde alacağız ve gerekirse yeni boş bir sözlük oluşturacağız. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Neden bu şekilde*: Mevcut olmayan bir **ExtGState sözlüğüne** grafik durumu eklemeye çalışmak bir istisna fırlatır. Bu savunma kontrolü, kodun her türlü giriş PDF'i için dayanıklı olmasını sağlar. + +--- + +## 4. Adım – CosPdfDictionary ile Yeni Bir Grafik Durumu Oluşturun + +Şimdi öğretinin kalbi: **boş PDF sözlüğü** oluşturarak özel bir grafik durumu tanımlamak. Çizgi opaklığını (`CA`), dolgu opaklığını (`ca`) ve karışım modunu (`BM`) ayarlayacağız. Daha sonra daha fazla giriş ekleyebilirsiniz—bu sadece başlangıç seti. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Açıklama*: +- `CA` ve `ca`, sırasıyla çizgi ve dolgu opaklığını kontrol eden standart PDF anahtarlarıdır. +- `BM` karışım modunu seçer; “Normal” varsayılan değerdir ancak tasarım ihtiyaçlarınıza göre “Multiply”, “Screen” gibi diğer modları da kullanabilirsiniz. +- `CosPdfDictionary.CreateEmptyDictionary` kullanarak **boş PDF sözlüğü** nesneleri oluşturur, ardından bu nesneleri anahtar/değer çiftleriyle doldururuz. + +--- + +## 5. Adım – Yeni Grafik Durumunu ExtGState’e Ekleyin + +Grafik durumu hazır olduğunda, onu **ExtGState sözlüğüne** benzersiz bir ad (ör. `GS0`) altında ekliyoruz. Birden fazla durum eklemeyi planlıyorsanız, sadece sonek sayısını artırın. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*İpucu*: Eklemeye başlamadan önce `GS0` zaten var mı kontrol etmek, üzerine yazmayı önler. `if (!extGState.ContainsKey("GS0"))` guard'ı bu işi halleder. + +--- + +## 6. Adım – Değiştirilen PDF’i Kaydedin + +Tüm değişiklikler bellekte kalır; kalıcı hale getirmek için kaydetmeniz gerekir. İş akışınıza uygun bir çıktı yolu seçin. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Sonuç*: `output.pdf` dosyasını herhangi bir PDF görüntüleyicide açın ve sayfa kaynaklarını (ör. bir PDF denetleyici aracıyla) inceleyin. **ExtGState** altında `GS0` adlı yeni bir giriş ve tanımladığımız parametreleri göreceksiniz. + +--- + +## Tam Çalışan Örnek + +Her şeyi bir araya getirdiğimizde, işte kopyala‑yapıştır‑hazır tam program: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Beklenen çıktı**: `output.pdf` orijinaliyle aynı şekilde renderlanacak, ancak daha sonra `GS0`'a (ör. içerik akışında `gs` operatörüyle) referans veren herhangi bir içerik, tanımladığınız opaklık ve karışım modunu kullanacaktır. Böyle bir referansınız yoksa, bunu manuel olarak ya da Aspose’un yüksek seviyeli API’leriyle ekleyebilirsiniz. + +--- + +## Sık Sorulan Sorular & Kenar Durumları + +| Soru | Cevap | +|------|-------| +| *PDF zaten `GS0` adlı bir `ExtGState` girdisine sahipse ne olur?* | Eklemeye çalışmadan önce `extGState.ContainsKey("GS0")` kontrol edin. Eğer mevcutsa, isteyerek üzerine yazın (`extGState["GS0"] = newGraphicsState`) ya da `GS1` gibi yeni bir ad seçin. | +| *Çizgi kalınlığı (`LW`) ya da kesik çizgi deseni (`D`) gibi daha fazla parametre ekleyebilir miyim?* | Kesinlikle. `parameters` dizisine ek `KeyValuePair` öğeleri ekleyerek genişletebilirsiniz. | +| *Bu yöntem şifreli PDF'lerle uyumlu mu?* | Evet, `Document` oluştururken doğru şifreyi (`new Document(path, password)`) sağladığınız sürece çalışır. | +| *Belgeyi manuel olarak kapatmam gerekir mi?* | `using` ifadesi imha işlemini halleder; bu da bekleyen değişikliklerin flush edilmesini sağlar. | +| *Yüksek seviyeli `Graphics` sınıfı ile bu nasıl farklılaşıyor?* | Yüksek seviyeli API, sözlükleri soyutlayarak basit görevler için iyidir. Ancak özel karışım modları gibi ince ayar gerektiren durumlarda, düşük seviyeli **CosPdfDictionary** ile çalışmanız gerekir; yani **boş PDF sözlüğü** nesnelerini doğrudan **create empty PDF dictionary** yapmanız gerekir. | + +--- + +## Sonuç + +Aspose.Pdf kullanarak **boş PDF sözlüğü** nesneleri oluşturmayı, özel bir grafik durumunu **ExtGState sözlüğüne** enjekte etmeyi ve değiştirilen dosyayı kaydetmeyi temiz, idiomatik C# kodu ile gösterdik. Bu desen, opaklık, karışım modları ve PDF spesifikasyonu tarafından tanımlanan diğer grafik‑durum parametreleri üzerinde hassas kontrol sağlar. + +Bundan sonra şunları yapabilirsiniz: + +- Yeni grafik durumunu mevcut sayfa içeriğine `gs` operatörüyle uygulamak. +- Markalaşma ya da filigranlama için yeniden kullanılabilir grafik durumları kütüphanesi oluşturmak. +- + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayalı olarak yakın konuları ele alır. Her kaynak, tam çalışan kod örnekleri ve adım adım açıklamalar içerir; böylece ek API özelliklerini öğrenebilir ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/vietnamese/net/digital-signatures/_index.md b/pdf/vietnamese/net/digital-signatures/_index.md index 4eda08eebc..2899d20b68 100644 --- a/pdf/vietnamese/net/digital-signatures/_index.md +++ b/pdf/vietnamese/net/digital-signatures/_index.md @@ -58,12 +58,16 @@ Tìm hiểu cách xác minh chữ ký số trong tệp PDF bằng Aspose.PDF cho ### [Xác minh chữ ký PDF trong C# – Hướng dẫn toàn diện để xác thực chữ ký số PDF](./verify-pdf-signature-in-c-complete-guide-to-validate-digital/) Hướng dẫn chi tiết cách xác thực chữ ký số PDF bằng C# với Aspose.PDF, bao gồm các bước triển khai và kiểm tra tính toàn vẹn. + ### [Tải tài liệu PDF C# – Chuyển đổi sang PDF/X‑4 và Liệt kê chữ ký](./load-pdf-document-c-convert-to-pdf-x-4-list-signatures/) Hướng dẫn cách tải tài liệu PDF, chuyển đổi sang định dạng PDF/X‑4 và liệt kê các chữ ký trong tài liệu bằng C#. ### [Xác thực chữ ký PDF với Aspose – Chuyển PDF sang HTML](./validate-pdf-signature-with-aspose-convert-pdf-to-html/) Hướng dẫn cách xác thực chữ ký PDF và chuyển đổi tài liệu PDF sang HTML bằng Aspose. +### [Xác thực chữ ký PDF và liệt kê các chữ ký PDF với Aspose.PDF – Hướng dẫn đầy đủ](./validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/) +Hướng dẫn chi tiết cách xác thực chữ ký PDF và liệt kê tất cả chữ ký trong tài liệu bằng Aspose.PDF. + ## Tài nguyên bổ sung - [Aspose.PDF cho Tài liệu Net](https://docs.aspose.com/pdf/net/) diff --git a/pdf/vietnamese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md b/pdf/vietnamese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md new file mode 100644 index 0000000000..ead3051579 --- /dev/null +++ b/pdf/vietnamese/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-07-26 +description: Xác thực chữ ký PDF và liệt kê các chữ ký PDF bằng Aspose.PDF trong C#. + Mã từng bước, các rủi ro tiềm ẩn và các thực tiễn tốt nhất để xử lý tài liệu an + toàn. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- validate pdf signature +- list pdf signatures +language: vi +lastmod: 2026-07-26 +og_description: Xác thực chữ ký PDF và liệt kê các chữ ký PDF bằng Aspose.PDF. Theo + dõi hướng dẫn thực tế này để bảo mật PDF trong C#. +og_image_alt: Screenshot of a C# console app validating a PDF signature with Aspose.PDF +og_title: Xác thực chữ ký PDF & Liệt kê các chữ ký PDF – Hướng dẫn Aspose.PDF +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Validate PDF signature and list PDF signatures using Aspose.PDF in + C#. Step‑by‑step code, pitfalls, and best practices for secure document handling. + headline: Validate PDF Signature and List PDF Signatures with Aspose.PDF – Complete + Guide + type: TechArticle +tags: +- Aspose.PDF +- PDF signature +- C# +- document security +title: Xác thực chữ ký PDF và liệt kê các chữ ký PDF với Aspose.PDF – Hướng dẫn đầy + đủ +url: /vi/net/digital-signatures/validate-pdf-signature-and-list-pdf-signatures-with-aspose-p/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Xác Thực Chữ Ký PDF và Liệt Kê Các Chữ Ký PDF với Aspose.PDF – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi làm sao **validate PDF signature** trong một ứng dụng .NET mà không phải đau đầu không? Bạn không phải là người duy nhất. Dù bạn đang xây dựng một nền tảng ký điện tử hay chỉ cần chắc chắn một hợp đồng đã nhận không bị thay đổi, khả năng **list PDF signatures** và xác thực từng chữ ký là một kỹ năng không thể thiếu. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ có thể chạy ngay, tải một PDF đã ký, liệt kê mọi chữ ký nhúng, kiểm tra xem có chữ ký nào bị xâm phạm không, và in kết quả rõ ràng ra console. Không có những tham chiếu mơ hồ—chỉ có mã bạn có thể copy‑paste, cùng với “tại sao” cho mỗi bước. + +## Prerequisites + +Trước khi bắt đầu, hãy chắc chắn bạn đã có: + +- **Aspose.PDF for .NET** phiên bản 25.3 trở lên (thuộc tính `IsCompromised` xuất hiện từ 25.3). +- Môi trường phát triển .NET (Visual Studio 2022, Rider, hoặc `dotnet` CLI). +- Một file PDF đã ký để thử nghiệm (bạn có thể tạo bằng Adobe Acrobat hoặc bất kỳ công cụ e‑signature nào). + +Nếu còn thiếu bất kỳ mục nào, hãy cài đặt gói NuGet trước: + +```bash +dotnet add package Aspose.PDF --version 25.3 +``` + +> **Mẹo chuyên nghiệp:** Nhắm mục tiêu .NET 6 hoặc mới hơn để đạt hiệu năng tốt nhất và hỗ trợ lâu dài. + +## Step 1: Load the PDF Document + +Điều đầu tiên bạn cần làm là mở file PDF. Lớp `Document` của Aspose.PDF xử lý mọi thứ từ phân tích tới render. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +// Replace with the actual path to your signed PDF +string pdfPath = @"C:\Docs\signed.pdf"; + +// Load the document into memory +Document pdfDocument = new Document(pdfPath); +``` + +*Lý do quan trọng:* Việc tải file tạo ra một biểu diễn trong bộ nhớ, cho phép bạn truy vấn các chữ ký mà không cần truy cập lại hệ thống file. Nó cũng kiểm tra cấu trúc PDF sớm, vì vậy nếu file bị hỏng bạn sẽ nhận được ngoại lệ ngay lập tức. + +## Step 2: **List PDF Signatures** – Enumerate All Embedded Signatures + +Một PDF đã ký có thể chứa nhiều chữ ký (nghĩ đến một hợp đồng nhiều trang, mỗi bên ký ở một trang khác nhau). Aspose.PDF cung cấp chúng qua collection `Signatures`. + +```csharp +Console.WriteLine("=== Embedded Signatures ==="); + +// Iterate over each signature object +foreach (var signatureInfo in pdfDocument.Signatures) +{ + Console.WriteLine($"- Name: {signatureInfo.Name}"); + Console.WriteLine($" Reason: {signatureInfo.Reason}"); + Console.WriteLine($" Location: {signatureInfo.Location}"); + Console.WriteLine($" Signing Time: {signatureInfo.SignDate}"); +} +``` + +*Bạn đang thấy gì:* Vòng lặp in ra chi tiết **list PDF signatures** như tên người ký, lý do, vị trí và thời gian ký. Điều này rất hữu ích cho log kiểm toán hoặc hiển thị UI. + +## Step 3: **Validate PDF Signature** – Check for Compromise + +Bây giờ là phần quan trọng về bảo mật: xác nhận rằng không có chữ ký nào bị thay đổi sau khi ký. Bắt đầu từ phiên bản 25.3, Aspose.PDF cung cấp cờ `PdfSignatureValidator.IsCompromised`. + +```csharp +Console.WriteLine("\n=== Validation Results ==="); + +// Validate each signature individually +foreach (var signatureInfo in pdfDocument.Signatures) +{ + // Create a validator for the current signature + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + + // The IsCompromised property tells us if the signature's integrity is broken + bool isCompromised = validator.IsCompromised; + + // Output the result in a friendly format + Console.WriteLine($"Signature \"{signatureInfo.Name}\": compromised = {isCompromised}"); +} +``` + +*Tại sao nên dùng `IsCompromised`*: Kiểm tra truyền thống chỉ xem chuỗi mật mã (tính hợp lệ của chứng chỉ, thu hồi, v.v.). `IsCompromised` bổ sung một lớp nữa bằng cách phát hiện bất kỳ thay đổi nào sau khi ký tài liệu—đúng những gì bạn cần khi **validate PDF signature** để phát hiện giả mạo. + +## Step 4: Handling Validation Outcomes + +Tùy theo kết quả, bạn có thể muốn thực hiện các hành động khác nhau. Dưới đây là một mẫu nhanh bạn có thể tùy biến: + +```csharp +foreach (var signatureInfo in pdfDocument.Signatures) +{ + PdfSignatureValidator validator = new PdfSignatureValidator(signatureInfo); + bool compromised = validator.IsCompromised; + + if (compromised) + { + // Alert the user, reject the document, or log for investigation + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{signatureInfo.Name}\" is compromised! Do not trust this PDF."); + } + else + { + // Proceed with business logic – e.g., store the document, mark as approved + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{signatureInfo.Name}\" is intact."); + } + + // Reset console color for next line + Console.ResetColor(); +} +``` + +*Lưu ý trường hợp đặc biệt:* Nếu một PDF chứa chữ ký **certified** (chữ ký đầu tiên khóa tài liệu), bất kỳ sửa đổi nào sau đó có thể làm toàn bộ file không hợp lệ, ngay cả khi các chữ ký tiếp theo trông ổn. Luôn coi bất kỳ giá trị `true` từ `IsCompromised` là dấu hiệu nguy hiểm. + +## Full Working Example + +Kết hợp mọi thứ lại, đây là một chương trình tự chứa, có thể biên dịch và chạy: + +```csharp +using System; +using Aspose.Pdf; +using Aspose.Pdf.Signature; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // 1️⃣ Load the PDF document + // ------------------------------------------------- + string pdfPath = @"C:\Docs\signed.pdf"; + Document pdfDocument = new Document(pdfPath); + + // ------------------------------------------------- + // 2️⃣ List all embedded signatures + // ------------------------------------------------- + Console.WriteLine("=== Embedded Signatures ==="); + foreach (var sig in pdfDocument.Signatures) + { + Console.WriteLine($"- Name: {sig.Name}"); + Console.WriteLine($" Reason: {sig.Reason}"); + Console.WriteLine($" Location: {sig.Location}"); + Console.WriteLine($" Signing Time: {sig.SignDate}"); + } + + // ------------------------------------------------- + // 3️⃣ Validate each signature (check for compromise) + // ------------------------------------------------- + Console.WriteLine("\n=== Validation Results ==="); + foreach (var sig in pdfDocument.Signatures) + { + PdfSignatureValidator validator = new PdfSignatureValidator(sig); + bool compromised = validator.IsCompromised; + + // ------------------------------------------------- + // 4️⃣ React to the validation outcome + // ------------------------------------------------- + if (compromised) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"⚠️ Signature \"{sig.Name}\" is compromised! Do not trust this PDF."); + } + else + { + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"✅ Signature \"{sig.Name}\" is intact."); + } + Console.ResetColor(); + } + } +} +``` + +**Kết quả mong đợi** (giả sử có một chữ ký hợp lệ và một chữ ký bị giả mạo): + +``` +=== Embedded Signatures === +- Name: John Doe + Reason: Approved + Location: New York, USA + Signing Time: 2024-03-15 14:32:00 + +=== Validation Results === +✅ Signature "John Doe" is intact. +⚠️ Signature "Jane Smith" is compromised! Do not trust this PDF. +``` + +## Common Pitfalls & How to Avoid Them + +| Pitfall | Why it Happens | Fix | +|---------|----------------|-----| +| **Missing Aspose.PDF version** | `IsCompromised` được giới thiệu trong 25.3. Các phiên bản cũ biên dịch được nhưng ném `MissingMethodException`. | Đảm bảo tham chiếu NuGet của bạn là `>= 25.3`. | +| **Null `SignatureInfo`** | Một số PDF có các slot chữ ký trống vẫn xuất hiện trong collection. | Kiểm tra `if (signatureInfo != null)` trước khi thực hiện xác thực. | +| **Performance hit on large PDFs** | Xác thực mỗi chữ ký đọc toàn bộ file mỗi lần. | Cache `PdfSignatureValidator` hoặc xử lý hàng loạt nếu bạn chỉ cần một tổng quan boolean. | +| **Certificate revocation not checked** | `IsCompromised` chỉ cho biết thay đổi tài liệu, không kiểm tra trạng thái chứng chỉ. | Sử dụng `PdfSignatureValidator.Validate()` cùng với `IsCompromised` để có kiểm tra PKI đầy đủ. | + +## Extending the Solution + +Nếu bạn cần **list PDF signatures** trong UI, chỉ cần đưa các đối tượng `SignatureInfo` vào một data grid. Muốn lưu kết quả xác thực vào cơ sở dữ liệu? Serialize giá trị boolean `isCompromised` cùng với tên người ký và thời gian ký. + +Các chủ đề liên quan bạn có thể khám phá tiếp: + +- **Validate PDF signature against a trusted root CA** (sử dụng `validator.Validate()`). +- **Extract embedded certificate details** (`validator.Certificate`). +- **Create digital signatures** với Aspose.PDF (`PdfSignatureBuilder`). + +## Conclusion + +Bạn đã có một phương pháp thực tế, đầu‑cuối‑đầu để **validate PDF signature** và **list PDF signatures** bằng Aspose.PDF cho .NET. Mã nguồn cho thấy cách tải tài liệu, liệt kê từng chữ ký, kiểm tra cờ `IsCompromised`, và hành động dựa trên kết quả—tất cả trong một định dạng console rõ ràng. + +Hãy thử với các PDF đã ký của bạn, thực nghiệm với nhiều chữ ký, và tích hợp logic này vào pipeline xử lý tài liệu lớn hơn. PDF an toàn chỉ mạnh bằng mức độ xác thực bạn thực hiện, vì vậy hãy giữ các kiểm tra chặt chẽ và log chi tiết. + +Có câu hỏi hoặc muốn chia sẻ trường hợp sử dụng thú vị? Để lại bình luận bên dưới hoặc nhắn tin cho tôi trên GitHub. Chúc lập trình vui! + +![Validate PDF Signature](/images/validate-pdf-signature.png "Screenshot of a C# console app validating a PDF signature with Aspose.PDF") + + +## What Should You Learn Next? + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm mã mẫu đầy đủ cùng giải thích chi tiết từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách Xác Thực PDF – Xác Thực Chữ Ký PDF với Aspose](/pdf/english/net/digital-signatures/how-to-verify-pdf-validate-pdf-signature-with-aspose/) +- [Cách Trích Xuất Thông Tin Chữ Ký PDF Sử Dụng Aspose.PDF .NET: Hướng Dẫn Từng Bước](/pdf/english/net/digital-signatures/extract-pdf-signature-info-aspose-pdf-net/) +- [Cách Trích Xuất Hình Ảnh Từ Trường Chữ Ký PDF Sử Dụng Aspose.PDF cho .NET: Hướng Dẫn Từng Bước](/pdf/english/net/forms-annotations/extract-images-from-pdf-signature-fields-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/pdf/vietnamese/net/programming-with-operators/_index.md b/pdf/vietnamese/net/programming-with-operators/_index.md index bae1c8435c..8be82fe719 100644 --- a/pdf/vietnamese/net/programming-with-operators/_index.md +++ b/pdf/vietnamese/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Hướng dẫn "Lập trình với Toán tử" của Aspose.PDF cho .NET hướn | [Vẽ XForm Trên Trang](./draw-xform-on-page/) | hướng dẫn cách vẽ XForms trong PDF bằng Aspose.PDF cho .NET với hướng dẫn từng bước toàn diện này. | | [Toán tử PDF](./pdf-operators/) | Hướng dẫn từng bước sử dụng toán tử PDF với Aspose.PDF cho .NET. Thêm hình ảnh vào trang PDF và chỉ định vị trí của hình ảnh đó. | | [Xóa Đối Tượng Đồ Họa Trong Tệp PDF](./remove-graphics-objects/) Tìm hiểu cách xóa các đối tượng đồ họa khỏi tệp PDF bằng Aspose.PDF cho .NET trong hướng dẫn từng bước này. Đơn giản hóa các tác vụ thao tác PDF của bạn. | +| [Tạo Từ Điển PDF Trống trong C# – Hướng Dẫn Toàn Diện Aspose.Pdf](./create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/) | Hướng dẫn chi tiết cách tạo một từ điển PDF trống trong C# bằng Aspose.PDF cho .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/vietnamese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md b/pdf/vietnamese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md new file mode 100644 index 0000000000..3d4d11d9aa --- /dev/null +++ b/pdf/vietnamese/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-26 +description: Tạo từ điển PDF trống bằng Aspose.Pdf trong C#. Học từng bước cách thêm + trạng thái đồ họa vào từ điển ExtGState để thao tác PDF. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty pdf dictionary +- Aspose.Pdf +- ExtGState dictionary +- CosPdfDictionary +- PDF graphics state +- C# PDF manipulation +language: vi +lastmod: 2026-07-26 +og_description: Tạo từ điển PDF trống bằng Aspose.Pdf cho C#. Tham khảo hướng dẫn + thực hành này để chỉnh sửa trạng thái đồ họa trong các tệp PDF của bạn. +og_image_alt: Diagram showing how to create empty PDF dictionary with Aspose.Pdf in + C# +og_title: Tạo Từ Điển PDF Trống trong C# – Hướng Dẫn Đầy Đủ Aspose.Pdf +schemas: +- author: Aspose + dateModified: '2026-07-26' + description: Create empty PDF dictionary with Aspose.Pdf in C#. Learn step‑by‑step + how to add a graphics state to ExtGState dictionary for PDF manipulation. + headline: Create Empty PDF Dictionary in C# – Complete Aspose.Pdf Guide + type: TechArticle +tags: +- Aspose +- PDF +- C# +- GraphicsState +title: Tạo Từ điển PDF Trống trong C# – Hướng dẫn đầy đủ Aspose.Pdf +url: /vi/net/programming-with-operators/create-empty-pdf-dictionary-in-c-complete-aspose-pdf-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo Dictionary PDF Trống trong C# – Hướng Dẫn Toàn Diện Aspose.Pdf + +Bạn đã bao giờ tự hỏi làm thế nào để **tạo các mục dictionary PDF trống** khi điều chỉnh trạng thái đồ họa của PDF? Bạn không phải là người duy nhất—nhiều nhà phát triển gặp khó khăn này khi cố gắng thay đổi độ trong suốt hoặc chế độ hòa trộn một cách lập trình. Trong hướng dẫn này, chúng ta sẽ đi qua một giải pháp cụ thể bằng cách sử dụng Aspose.Pdf cho C#, cho thấy cách chèn một trạng thái đồ họa mới vào dictionary *ExtGState* của một PDF hiện có. + +Chúng ta sẽ bao phủ mọi thứ bạn cần: tải PDF, truy cập dictionary tài nguyên, xây dựng một **CosPdfDictionary** mới, và cuối cùng lưu các thay đổi. Khi hoàn thành, bạn sẽ có một mẫu có thể tái sử dụng cho bất kỳ điều chỉnh *trạng thái đồ họa PDF* nào bạn cần. + +--- + +## Những Điều Bạn Sẽ Học + +- Cách **tạo dictionary PDF trống** bằng API cấp thấp của Aspose.Pdf. +- Vai trò của **dictionary ExtGState** trong việc kiểm soát độ trong suốt nét vẽ/lấp đầy và chế độ hòa trộn. +- Các mẹo thực tiễn cho việc thao tác PDF bằng C#, bao gồm xử lý các trường hợp biên khi dictionary thiếu. +- Một mẫu mã hoàn chỉnh, có thể chạy được mà bạn có thể sao chép‑dán vào dự án của mình. + +### Điều Kiện Tiên Quyết + +- .NET 6.0 trở lên (mã cũng hoạt động với .NET Framework 4.6+). +- Bản sao có giấy phép của **Aspose.Pdf for .NET** (bản dùng thử miễn phí đủ cho việc thử nghiệm). +- Kiến thức cơ bản về C# và các khái niệm PDF như tài nguyên và trạng thái đồ họa. + +Nếu bất kỳ mục nào trên còn lạ, đừng lo—bạn có thể cài đặt Aspose.Pdf qua NuGet (`Install-Package Aspose.Pdf`) và phần còn lại chỉ là C# thuần. + +--- + +## Bước 1 – Tải Tài Liệu PDF + +Đầu tiên, bạn cần một đối tượng `Document` đại diện cho tệp bạn muốn chỉnh sửa. Đặt nó trong khối `using` để đảm bảo giải phóng tài nguyên đúng cách. + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; // for low‑level PDF objects +using Aspose.Pdf.Text; // if you need to add text later + +// Step 1: Load the PDF document +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // The rest of the workflow lives inside this block. +} +``` + +*Lý do quan trọng*: Mở tệp cho phép bạn truy cập các đối tượng COS (Canonical Object Structure) nội bộ, nơi **CosPdfDictionary** tồn tại. Nếu không có đối tượng tài liệu, bạn không thể tới các dictionary tài nguyên chứa các mục **ExtGState**. + +--- + +## Bước 2 – Truy Cập Dictionary Tài Nguyên của Trang Đầu Tiên + +Các trang PDF lưu trữ tài nguyên (phông chữ, hình ảnh, trạng thái đồ họa, v.v.) trong một dictionary riêng. Chúng ta sẽ lấy trang đầu tiên để đơn giản, nhưng logic này áp dụng cho bất kỳ chỉ số trang nào. + +```csharp +// Step 2: Access the first page and its resource dictionary +Page firstPage = pdfDocument.Pages[1]; +DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); +``` + +*Mẹo chuyên nghiệp*: Nếu PDF của bạn có nhiều trang với các bộ tài nguyên khác nhau, hãy lặp lại khối này cho mỗi trang bạn cần chỉnh sửa. Lớp `DictionaryEditor` là một wrapper tiện lợi cho phép bạn xử lý dictionary COS như một `Dictionary` của .NET. + +--- + +## Bước 3 – Lấy Hoặc Khởi Tạo Dictionary ExtGState + +**Dictionary ExtGState** chứa các đối tượng trạng thái đồ họa có tên (`GS0`, `GS1`, …). Một số PDF đã có sẵn; một số khác thì không. Chúng ta sẽ lấy một cách an toàn, tạo một dictionary trống mới nếu cần. + +```csharp +// Step 3: Get the existing ExtGState dictionary (or create it if missing) +CosPdfDictionary extGState; +if (resourceEditor.ContainsKey("ExtGState")) +{ + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); +} +else +{ + // Create a fresh ExtGState dictionary and attach it to the resources + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); +} +``` + +*Tại sao chúng ta làm như vậy*: Cố gắng thêm một trạng thái đồ họa vào **dictionary ExtGState** không tồn tại sẽ gây ra ngoại lệ. Kiểm tra phòng thủ này làm cho mã ổn định với bất kỳ PDF đầu vào nào. + +--- + +## Bước 4 – Xây Dựng Trạng Thái Đồ Họa Mới với CosPdfDictionary + +Bây giờ là phần cốt lõi của hướng dẫn: **tạo một dictionary PDF trống** định nghĩa một trạng thái đồ họa tùy chỉnh. Chúng ta sẽ thiết lập độ trong suốt nét vẽ (`CA`), độ trong suốt lấp đầy (`ca`), và chế độ hòa trộn (`BM`). Bạn có thể thêm các mục khác sau này—đây chỉ là bộ khởi đầu. + +```csharp +// Step 4: Create a new graphics state dictionary with desired parameters +CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + +// Define the parameters we want +KeyValuePair[] parameters = new[] +{ + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity (fully opaque) + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity (semi‑transparent) + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode +}; + +// Populate the dictionary +foreach (var p in parameters) +{ + newGraphicsState.Add(p); +} +``` + +*Giải thích*: +- `CA` và `ca` là các khóa PDF chuẩn điều khiển độ trong suốt nét vẽ và lấp đầy, tương ứng. +- `BM` chọn chế độ hòa trộn; “Normal” là mặc định nhưng bạn có thể dùng “Multiply”, “Screen”, v.v., tùy nhu cầu thiết kế. +- Bằng cách sử dụng `CosPdfDictionary.CreateEmptyDictionary`, chúng ta **tạo các dictionary PDF trống** mà sau này sẽ được điền các cặp khóa/giá trị. + +--- + +## Bước 5 – Chèn Trạng Thái Đồ Họa Mới vào ExtGState + +Khi trạng thái đồ họa đã sẵn sàng, chúng ta chỉ cần thêm nó vào **dictionary ExtGState** dưới một tên duy nhất (ví dụ `GS0`). Nếu bạn dự định thêm nhiều trạng thái, chỉ cần tăng số hậu tố. + +```csharp +// Step 5: Add the new graphics state to the ExtGState dictionary +extGState.Add("GS0", newGraphicsState); +``` + +*Mẹo*: Trước khi thêm, bạn có thể kiểm tra xem `GS0` đã tồn tại chưa để tránh ghi đè. Một câu lệnh `if (!extGState.ContainsKey("GS0"))` nhanh gọn sẽ giải quyết. + +--- + +## Bước 6 – Lưu PDF Đã Sửa Đổi + +Tất cả các thay đổi vẫn ở bộ nhớ cho đến khi bạn ghi chúng ra đĩa. Chọn một đường dẫn đầu ra phù hợp với quy trình làm việc của bạn. + +```csharp +// Step 6: Save the modified PDF +pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +``` + +*Kết quả*: Mở `output.pdf` bằng bất kỳ trình xem PDF nào, sau đó kiểm tra tài nguyên trang (ví dụ bằng công cụ kiểm tra PDF). Bạn sẽ thấy một mục mới trong **ExtGState** có tên `GS0` với các tham số chúng ta đã định nghĩa. + +--- + +## Ví Dụ Hoàn Chỉnh + +Kết hợp mọi thứ lại, đây là chương trình hoàn chỉnh, sẵn sàng sao chép‑dán: + +```csharp +using Aspose.Pdf; +using Aspose.Pdf.Operators; +using Aspose.Pdf.Text; + +using (var pdfDocument = new Document("YOUR_DIRECTORY/input.pdf")) +{ + // Access first page resources + Page firstPage = pdfDocument.Pages[1]; + DictionaryEditor resourceEditor = new DictionaryEditor(firstPage.Resources); + + // Ensure ExtGState dictionary exists + CosPdfDictionary extGState; + if (resourceEditor.ContainsKey("ExtGState")) + extGState = resourceEditor["ExtGState"].ToCosPdfDictionary(); + else + { + extGState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + resourceEditor.Add("ExtGState", extGState); + } + + // Build new graphics state + CosPdfDictionary newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), + new KeyValuePair("ca", new CosPdfNumber(0.5)), + new KeyValuePair("BM", new CosPdfName("Normal")) + }; + foreach (var p in parameters) newGraphicsState.Add(p); + + // Insert into ExtGState + if (!extGState.ContainsKey("GS0")) + extGState.Add("GS0", newGraphicsState); + + // Save result + pdfDocument.Save("YOUR_DIRECTORY/output.pdf"); +} +``` + +**Kết quả mong đợi**: `output.pdf` sẽ hiển thị giống hệt bản gốc, nhưng bất kỳ nội dung nào sau này tham chiếu tới `GS0` (ví dụ qua toán tử `gs` trong luồng nội dung) sẽ áp dụng độ trong suốt và chế độ hòa trộn đã định nghĩa. Nếu bạn chưa có tham chiếu như vậy, có thể thêm thủ công hoặc thông qua các API cấp cao của Aspose. + +--- + +## Câu Hỏi Thường Gặp & Các Trường Hợp Cạnh + +| Câu Hỏi | Trả Lời | +|----------|--------| +| *PDF đã có mục `ExtGState` tên `GS0` thì sao?* | Kiểm tra `extGState.ContainsKey("GS0")` trước khi thêm. Nếu đã tồn tại, bạn có thể ghi đè có chủ ý (`extGState["GS0"] = newGraphicsState`) hoặc chọn tên mới như `GS1`. | +| *Có thể thêm các tham số khác, như độ rộng nét (`LW`) hoặc mẫu gạch (`D`) không?* | Chắc chắn rồi. Chỉ cần mở rộng mảng `parameters` với các mục `KeyValuePair` bổ sung. | +| *Phương pháp này có tương thích với PDF được mã hoá không?* | Có, miễn là bạn cung cấp mật khẩu đúng khi khởi tạo `Document` (`new Document(path, password)`). | +| *Có cần đóng tài liệu thủ công không?* | Câu lệnh `using` sẽ tự động giải phóng, đồng thời flush mọi thay đổi còn lại. | +| *Điểm khác biệt so với việc dùng lớp `Graphics` cấp cao?* | API cấp cao ẩn đi các dictionary bên dưới, rất tiện cho các tác vụ đơn giản. Tuy nhiên, khi bạn cần kiểm soát chi tiết trạng thái đồ họa—như chế độ hòa trộn tùy chỉnh—bạn phải làm việc với **CosPdfDictionary** cấp thấp, tức là **tạo các dictionary PDF trống** trực tiếp. | + +--- + +## Kết Luận + +Chúng ta vừa chứng minh cách **tạo các dictionary PDF trống** bằng Aspose.Pdf, chèn một trạng thái đồ họa tùy chỉnh vào **dictionary ExtGState**, và lưu tệp đã sửa—all trong C# sạch sẽ và idiomatic. Mẫu này mở ra khả năng kiểm soát chính xác độ trong suốt, chế độ hòa trộn và bất kỳ tham số trạng thái đồ họa nào khác được định nghĩa trong chuẩn PDF. + +Từ đây, bạn có thể: + +- Áp dụng trạng thái đồ họa mới cho nội dung trang hiện có bằng toán tử `gs`. +- Xây dựng thư viện các trạng thái đồ họa tái sử dụng cho thương hiệu hoặc watermark. +- + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, dựa trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên đều bao gồm mã mẫu đầy đủ và giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [How to Create Dashed Lines in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Create & Fill Rectangles in PDFs Using Aspose.PDF for .NET: A Step-by-Step Guide](/pdf/english/net/images-graphics/create-fill-rectangle-aspose-pdf-net/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file