diff --git a/pdf/arabic/net/programming-with-operators/_index.md b/pdf/arabic/net/programming-with-operators/_index.md index 43ac049085..e65862c04c 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#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | تعلم كيفية إنشاء حالة رسومية فارغة في PDF باستخدام Aspose.PDF لـ .NET مع C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/arabic/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/arabic/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..1dfa040954 --- /dev/null +++ b/pdf/arabic/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-08-17 +description: إنشاء حالة رسومية فارغة في ملف PDF باستخدام C# و Aspose.Pdf. اتبع هذا + الدليل خطوة بخطوة لتعديل موارد ExtGState بأمان. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: ar +lastmod: 2026-08-17 +og_description: إنشاء حالة رسومية فارغة في ملف PDF باستخدام C#. يوضح هذا الدرس كيفية + تعديل موارد ExtGState باستخدام Aspose.Pdf لتعديلات PDF موثوقة. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: إنشاء حالة رسومية فارغة في PDF باستخدام C# – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: كيفية إنشاء حالة رسومية فارغة في ملف PDF باستخدام C# +url: /ar/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية إنشاء حالة رسومية فارغة في ملف PDF باستخدام C# + +إذا كنت بحاجة إلى **إنشاء حالة رسومية فارغة** في ملف PDF، يوضح لك هذا الدليل بالضبط كيفية القيام بذلك باستخدام C# و Aspose.Pdf. ستشاهد مثالًا كاملاً قابلاً للتنفيذ يضيف إدخالًا جديدًا إلى القاموس ExtGState للصفحة دون التأثير على المحتوى الموجود. + +يُعد العمل مع حالات الرسومات في PDF مطلبًا شائعًا عندما تريد التحكم في الشفافية، أو أوضاع الدمج، أو غيرها من معلمات العرض على أساس كل كائن. يوضح الكود أدناه النهج الموصى به، ويشرح لماذا كل خطوة مهمة، ويغطي الاختلافات النموذجية التي قد تواجهها. + +## المتطلبات المسبقة + +قبل أن تبدأ، تأكد من وجود ما يلي: + +* .NET 6.0 أو أحدث (العينة تُجمع أيضًا مع .NET Core). +* ترخيص Aspose.Pdf for .NET (أو مفتاح تقييم مؤقت). +* مجلد يحتوي على ملف `input.pdf` الذي تريد تعديله. +* إلمام أساسي بصياغة C# ومفاهيم PDF مثل قواميس الموارد. + +## الخطوة 1: إعداد المشروع واستيراد المساحات الاسمية + +أنشئ تطبيقًا كونسول جديدًا أو دمج الكود في مشروع موجود. أضف حزمة NuGet الخاصة بـ Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +ثم استورد المساحات الاسمية المطلوبة: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +تمنحك هذه الاستيرادات الوصول إلى الفئات `Document` و `DictionaryEditor` وفئات PDF الأولية اللازمة **لإنشاء حالة رسومية فارغة**. + +## الخطوة 2: تعريف المجلد الذي يحتوي ملفات PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +استبدل المسار بموقع ملفات PDF الخاصة بك. يجعل تخزين الدليل في متغير الكود قابلًا لإعادة الاستخدام وأسهل للاختبار. + +## الخطوة 3: تحميل مستند PDF المصدر + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +فتح المستند داخل عبارة `using` يضمن تحرير مقبض الملف تلقائيًا بعد حفظ التغييرات. + +## الخطوة 4: الوصول إلى الصفحة الأولى وقاموس Resources الخاص بها + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` يسترجع الصفحة الأولى (أرقام صفحات PDF تبدأ من 1). +* `DictionaryEditor` يوفر طريقة مريحة لقراءة وتعديل قواميس PDF. +* إدخال `ExtGState` يحتوي على جميع كائنات حالة الرسومات للصفحة. إذا لم يكن المفتاح موجودًا، يقوم Aspose.Pdf بإنشاء قاموس فارغ تلقائيًا. + +## الخطوة 5: بناء قاموس حالة رسومية فارغ جديد + +يمكن أن تكون حالة الرسومات التي تضيفها فارغة أو مُعبأة مسبقًا بمعلمات مثل الشفافية (`CA`, `ca`) أو وضع الدمج (`BM`). في هذا الدرس ننشئ **حالة رسومية فارغة** ثم نضبط بعض القيم النموذجية لتوضيح كيفية عمل القاموس. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` ينشئ حاوية نظيفة يمكنك ملؤها بأي مفاتيح حالة رسومية. +* إضافة `CA` و `ca` و `BM` اختياري؛ يمكنك حذفها إذا كنت بحاجة فعلًا إلى حالة فارغة. يوضح الكود كيفية إضافة الإدخالات عندما تقرر لاحقًا التحكم في العرض. + +## الخطوة 6: إدراج حالة الرسومات الجديدة في قاموس ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +تسمية الإدخال `"GS0"` تتبع الاتفاقية الشائعة لبدء أسماء حالات الرسومات بـ “GS”. يمكنك اختيار أي اسم PDF صالح لا يتعارض مع المفاتيح الموجودة. + +## الخطوة 7: حفظ مستند PDF المعدل + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +نداء `Save` يكتب الملف المحدث إلى `output.pdf`. فتح هذا الملف في عارض PDF يؤكد وجود حالة الرسومات الجديدة؛ يمكنك الإشارة إليها لاحقًا باستخدام المشغل `gs` في تدفقات المحتوى. + +### قائمة المصدر الكاملة + +بجمع كل ما سبق، يبدو البرنامج الكامل كالتالي: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +تشغيل البرنامج يطبع سطر تأكيد وينتج `output.pdf` مع حالة الرسومات التي أضيفت حديثًا. + +## لماذا يعمل هذا النهج بأفضل شكل + +* **تحرير القاموس مباشرة** – استخدام `DictionaryEditor` يتجنب الحاجة إلى تحليل تدفق المحتوى بالكامل. أنت تعدل فقط الموارد التي تهمك. +* **أنواع PDF الأولية** – `CosPdfNumber` و `CosPdfName` و `CosPdfDictionary` تضمن أن PDF المُولد يتوافق مع مواصفة PDF 1.7. +* **الأمان** – كتلة `using` تُفرغ كائن `Document`، مما يمنع أقفال الملفات التي قد تُفسد عمليات البناء اللاحقة. +* **القابلية للتوسيع** – بمجرد وجود حالة الرسومات الفارغة، يمكنك الإشارة إليها من أي مشغل محتوى (`gs`) لتغيير الشفافية أو وضع الدمج أو معلمات أخرى لأوامر الرسم المختارة. + +## الاختلافات الشائعة والحالات الحدية + +| الحالة | التعديل الموصى به | +|-----------|-------------------| +| **صفحات متعددة** | كرر الحلقة على `pdfDocument.Pages` وكرر إدراج القاموس لكل صفحة تحتاج إلى تعديلها. | +| **عدم وجود إدخال ExtGState موجود** | `resourcesEditor["ExtGState"]` ينشئ قاموسًا فارغًا تلقائيًا إذا لم يكن موجودًا. لا يلزم أي كود إضافي. | +| **اسم حالة رسومية مختلف** | استبدل `"GS0"` باسم يتوافق مع نمط التسمية الخاص بك، مثل `"MyTransparentState"`. | +| **إضافة حالة فارغة فقط** | احذف مصفوفة `parameters` وحلقة `foreach`؛ سيبقى القاموس فارغًا. | +| **العمل مع ملفات PDF مشفرة** | قدم كلمة المرور عند إنشاء `new Document(path, password)` قبل تعديل الموارد. | + +## التحقق من النتيجة + +يمكنك التحقق من إضافة حالة الرسومات بفحص PDF باستخدام عارض منخفض المستوى مثل **PDF‑Tron** أو **iText Sharp**. ابحث عن إدخال مشابه لـ: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +إذا ظهر الإدخال، فإن عملية **إنشاء حالة رسومية فارغة** نجحت. + +## الخلاصة + +أنت الآن تعرف كيف **تنشئ حالة رسومية فارغة** في ملف PDF باستخدام C# و Aspose.Pdf. غطى الدرس كل خطوة — من تحميل المستند إلى تعديل قاموس `ExtGState` وحفظ النتيجة — مع شرح السبب وراء كل إجراء. + +من هنا يمكنك: + +* استخدام حالة الرسومات الجديدة في تدفقات المحتوى (`gs /GS0`). +* تجربة مفاتيح إضافية مثل `/SM` (تعديل الخط) أو `/OPM` (وضع الطباعة فوق). +* تطبيق نفس التقنية على أنواع موارد أخرى مثل `/XObject` أو `/ColorSpace`. + +نتمنى لك تجربة ممتعة مع PDF، ولا تتردد في استكشاف سيناريوهات **حالة رسومات Aspose PDF** أخرى مثل تغييرات الشفافية الديناميكية أو أوضاع الدمج المخصصة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شفرة كاملة مع شرح خطوة بخطوة لمساعدتك على إتقان ميزات 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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/chinese/net/programming-with-operators/_index.md b/pdf/chinese/net/programming-with-operators/_index.md index 30ebbdeb45..09a8c39ca3 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 操作任务。| +| [如何在 PDF 中使用 C# 创建空图形状态](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | 使用 Aspose.PDF for .NET 的 C# 示例,学习在 PDF 中创建空的图形状态。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/chinese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/chinese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..0219a240c1 --- /dev/null +++ b/pdf/chinese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-08-17 +description: 使用 C# 和 Aspose.Pdf 在 PDF 中创建空的图形状态。请按照本分步指南安全地编辑 ExtGState 资源。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: zh +lastmod: 2026-08-17 +og_description: 使用 C# 在 PDF 中创建空的图形状态。本教程展示了如何使用 Aspose.Pdf 编辑 ExtGState 资源,以实现可靠的 + PDF 修改。 +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: 使用 C# 在 PDF 中创建空图形状态 – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: 如何在 PDF 中使用 C# 创建空图形状态 +url: /zh/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 PDF 中使用 C# 创建空的图形状态 + +如果您需要在 PDF 中**创建空的图形状态**,本指南将向您展示如何使用 C# 和 Aspose.Pdf 完成此操作。您将看到一个完整、可运行的示例,它向页面的 ExtGState 字典添加一个新条目,而不会影响现有内容。 + +在 PDF 图形状态上工作是一个常见需求,当您想要在每个对象层面控制透明度、混合模式或其他渲染参数时。下面的代码演示了推荐的做法,解释了每一步的原因,并涵盖了您可能遇到的典型变体。 + +## 前置条件 + +在开始之前,请确保您拥有: + +* .NET 6.0 或更高版本(示例同样可以在 .NET Core 下编译)。 +* Aspose.Pdf for .NET 许可证(或临时评估密钥)。 +* 包含您想要修改的 `input.pdf` 文件的文件夹。 +* 对 C# 语法以及 PDF 资源字典等概念有基本了解。 + +## 第 1 步:设置项目并导入命名空间 + +创建一个新的控制台应用程序,或将代码集成到现有项目中。添加 Aspose.Pdf NuGet 包: + +```bash +dotnet add package Aspose.Pdf +``` + +然后导入所需的命名空间: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +这些导入让您能够访问 `Document`、`DictionaryEditor` 以及用于**创建空的图形状态**条目的 PDF 原始类。 + +## 第 2 步:定义保存 PDF 文件的文件夹 + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +将路径替换为您自己的 PDF 文件所在位置。将目录保存到变量中可以使代码更易复用和测试。 + +## 第 3 步:加载源 PDF 文档 + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +在 `using` 语句中打开文档可确保在保存更改后自动释放文件句柄。 + +## 第 4 步:访问第一页及其 Resources 字典 + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` 获取第一页(PDF 页码从 1 开始)。 +* `DictionaryEditor` 提供了一种便捷方式来读取和修改 PDF 字典。 +* `ExtGState` 条目保存了页面的所有图形状态对象。如果该键不存在,Aspose.Pdf 会自动创建一个空字典。 + +## 第 5 步:构建一个新的空图形状态字典 + +您添加的图形状态可以是空的,也可以预先填充诸如不透明度(`CA`、`ca`)或混合模式(`BM`)等参数。在本教程中,我们创建一个**空的图形状态**,随后设置几个典型值以演示字典的工作方式。 + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` 创建一个干净的容器,您可以向其中填入任意图形状态键。 +* 添加 `CA`、`ca` 和 `BM` 是可选的;如果您真的需要一个空状态,可以省略它们。代码展示了在以后需要控制渲染时如何添加条目。 + +## 第 6 步:将新图形状态插入 ExtGState 字典 + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +将条目命名为 `"GS0"` 符合常见的以 “GS” 为前缀的图形状态命名约定。您可以选择任何不与现有键冲突的有效 PDF 名称。 + +## 第 7 步:保存修改后的 PDF 文档 + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +`Save` 调用会将更新后的文件写入 `output.pdf`。在 PDF 查看器中打开此文件即可确认新图形状态已存在;随后您可以在内容流中使用 `gs` 操作符引用它。 + +### 完整源码列表 + +将所有内容组合在一起,完整程序如下: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +运行程序会打印确认信息,并生成包含新添加图形状态的 `output.pdf`。 + +## 为什么这种做法是最佳选择 + +* **直接字典编辑** – 使用 `DictionaryEditor` 可避免解析整个内容流,只修改您关心的资源。 +* **强类型 PDF 原始对象** – `CosPdfNumber`、`CosPdfName` 和 `CosPdfDictionary` 确保生成的 PDF 符合 PDF 1.7 规范。 +* **安全性** – `using` 块会释放 `Document` 对象,防止文件锁定导致后续构建损坏。 +* **可扩展性** – 一旦空的图形状态存在,您可以在任何内容操作符(`gs`)中引用它,以改变选定绘图命令的透明度、混合模式或其他参数。 + +## 常见变体和边缘情况 + +| 情形 | 推荐的调整 | +|-----------|-------------------| +| **多页文档** | 遍历 `pdfDocument.Pages`,对每个需要修改的页面重复字典插入操作。 | +| **不存在 ExtGState 条目** | `resourcesEditor["ExtGState"]` 会在键不存在时自动创建空字典,无需额外代码。 | +| **不同的图形状态名称** | 将 `"GS0"` 替换为符合您命名约定的名称,例如 `"MyTransparentState"`。 | +| **仅添加空状态** | 省略 `parameters` 数组和 `foreach` 循环;字典将保持为空。 | +| **处理加密 PDF** | 在构造 `new Document(path, password)` 时提供密码,然后再编辑资源。 | + +## 验证结果 + +您可以使用诸如 **PDF‑Tron** 或 **iText Sharp** 等低层查看器检查 PDF,以确认图形状态已被添加。查找类似以下的条目: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +如果出现该条目,**创建空的图形状态**操作即告成功。 + +## 结论 + +现在,您已经掌握了如何使用 C# 和 Aspose.Pdf 在 PDF 中**创建空的图形状态**。本教程涵盖了从加载文档、编辑 `ExtGState` 字典到保存结果的每一步,并解释了每个操作背后的原理。 + +接下来您可以: + +* 在内容流中使用新图形状态(`gs /GS0`)。 +* 试验其他键,例如 `/SM`(描边调整)或 `/OPM`(过印模式)。 +* 将相同技术应用于其他资源类型,如 `/XObject` 或 `/ColorSpace`。 + +祝您 PDF 开发愉快,欢迎探索其他 **Aspose PDF 图形状态** 场景,如动态透明度变化或自定义混合模式! + +## 接下来您应该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助您在项目中进一步使用 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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/czech/net/programming-with-operators/_index.md b/pdf/czech/net/programming-with-operators/_index.md index 8d98f67cb7..5e00a6467b 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. | +| [Jak vytvořit prázdný grafický stav v PDF pomocí C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Naučte se, jak pomocí Aspose.PDF pro .NET vytvořit prázdný grafický stav v PDF pomocí C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/czech/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/czech/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..f5e8d65d52 --- /dev/null +++ b/pdf/czech/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-08-17 +description: Vytvořte prázdný grafický stav v PDF pomocí C# a Aspose.Pdf. Postupujte + podle tohoto krok‑za‑krokem návodu pro bezpečnou úpravu zdrojů ExtGState. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: cs +lastmod: 2026-08-17 +og_description: Vytvořte prázdný grafický stav v PDF pomocí C#. Tento tutoriál ukazuje, + jak upravit zdroje ExtGState pomocí Aspose.Pdf pro spolehlivé úpravy PDF. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Vytvořte prázdný grafický stav v PDF pomocí C# – krok za krokem průvodce +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Jak vytvořit prázdný grafický stav v PDF pomocí C# +url: /cs/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak vytvořit prázdný grafický stav v PDF pomocí C# + +Pokud potřebujete **vytvořit prázdný grafický stav** v PDF, tento návod vám přesně ukáže, jak to provést pomocí C# a Aspose.Pdf. Uvidíte kompletní, spustitelný příklad, který přidá nový záznam do slovníku ExtGState stránky, aniž by ovlivnil existující obsah. + +Práce s grafickými stavy PDF je běžná požadavek, když chcete řídit průhlednost, režimy míchání nebo jiné parametry vykreslování na úrovni jednotlivých objektů. Níže uvedený kód demonstruje doporučený přístup, vysvětluje, proč je každý krok důležitý, a popisuje typické varianty, na které můžete narazit. + +## Požadavky + +* .NET 6.0 nebo novější (ukázka se také kompiluje s .NET Core). +* Licence Aspose.Pdf pro .NET (nebo dočasný evaluační klíč). +* Složka, která obsahuje soubor `input.pdf`, který chcete upravit. +* Základní znalost syntaxe C# a konceptů PDF, jako jsou slovníky zdrojů. + +## Krok 1: Nastavení projektu a import jmenných prostorů + +Vytvořte novou konzolovou aplikaci nebo integrujte kód do existujícího projektu. Přidejte NuGet balíček Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Poté importujte požadované jmenné prostory: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Tyto importy vám poskytují přístup ke třídám `Document`, `DictionaryEditor` a PDF primitivům potřebným k **vytvoření prázdného grafického stavu**. + +## Krok 2: Definování složky, která obsahuje PDF soubory + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Nahraďte cestu umístěním vašich vlastních PDF souborů. Uchování adresáře v proměnné činí kód znovupoužitelným a snadněji testovatelným. + +## Krok 3: Načtení zdrojového PDF dokumentu + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Otevření dokumentu uvnitř `using` bloku zajišťuje, že souborový handle je automaticky uvolněn po uložení změn. + +## Krok 4: Přístup k první stránce a jejímu slovníku Resources + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` získá první stránku (čísla stránek PDF začínají na 1). +* `DictionaryEditor` poskytuje pohodlný způsob, jak číst a upravovat PDF slovníky. +* Záznam `ExtGState` obsahuje všechny objekty grafického stavu pro stránku. Pokud klíč neexistuje, Aspose.Pdf automaticky vytvoří prázdný slovník. + +## Krok 5: Vytvoření nového prázdného slovníku grafického stavu + +Grafický stav, který přidáte, může být prázdný nebo předem naplněný parametry, jako je průhlednost (`CA`, `ca`) nebo režim míchání (`BM`). V tomto tutoriálu vytvoříme **prázdný grafický stav** a poté nastavíme několik typických hodnot, abychom ilustrovali, jak slovník funguje. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` vytvoří čistý kontejner, který můžete naplnit libovolnými klíči grafického stavu. +* Přidání `CA`, `ca` a `BM` je volitelné; můžete je vynechat, pokud opravdu potřebujete prázdný stav. Kód ukazuje, jak přidat záznamy, když se později rozhodnete řídit vykreslování. + +## Krok 6: Vložení nového grafického stavu do slovníku ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Pojmenování záznamu `"GS0"` následuje běžnou konvenci, kdy se názvy grafických stavů předponují „GS“. Můžete zvolit libovolný platný PDF název, který nekoliduje s existujícími klíči. + +## Krok 7: Uložení upraveného PDF dokumentu + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +Volání `Save` zapíše aktualizovaný soubor do `output.pdf`. Otevření tohoto souboru v PDF prohlížeči potvrdí, že nový grafický stav existuje; můžete na něj později odkazovat pomocí operátoru `gs` v obsahových streamech. + +### Kompletní výpis zdrojového kódu + +Spojením všeho dohromady vypadá kompletní program takto: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Spuštěním programu se vypíše potvrzovací řádek a vytvoří se `output.pdf` s nově přidaným grafickým stavem. + +## Proč tento přístup funguje nejlépe + +* **Přímá úprava slovníku** – Použití `DictionaryEditor` eliminuje potřebu parsovat celý obsahový stream. Měníte jen zdroje, které vás zajímají. +* **Typované PDF primitivy** – `CosPdfNumber`, `CosPdfName` a `CosPdfDictionary` zaručují, že generované PDF splňuje specifikaci PDF 1.7. +* **Bezpečnost** – `using` blok uvolní objekt `Document`, což zabraňuje zamykání souborů, které by mohly poškodit následné sestavení. +* **Rozšiřitelnost** – Jakmile existuje prázdný grafický stav, můžete na něj odkazovat z libovolného obsahového operátoru (`gs`) a měnit průhlednost, režim míchání nebo jiné parametry pro vybrané kreslicí příkazy. + +## Běžné varianty a okrajové případy + +| Situace | Doporučená úprava | +|-----------|-------------------| +| **Více stránek** | Procházet `pdfDocument.Pages` a opakovat vložení slovníku pro každou stránku, kterou potřebujete upravit. | +| **Žádný existující záznam ExtGState** | `resourcesEditor["ExtGState"]` automaticky vytvoří prázdný slovník, pokud neexistuje. Není potřeba žádný další kód. | +| **Jiný název grafického stavu** | Nahraďte `"GS0"` názvem, který odpovídá vaší konvenci, např. `"MyTransparentState"`. | +| **Přidání pouze prázdného stavu** | Vynechte pole `parameters` a smyčku `foreach`; slovník zůstane prázdný. | +| **Práce s šifrovanými PDF** | Zadejte heslo při vytváření `new Document(path, password)` před úpravou zdrojů. | + +## Ověření výsledku + +Můžete ověřit, že byl grafický stav přidán, inspekcí PDF pomocí nízkoúrovňového prohlížeče, jako je **PDF‑Tron** nebo **iText Sharp**. Hledejte záznam podobný: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Pokud se záznam objeví, operace **vytvořit prázdný grafický stav** byla úspěšná. + +## Závěr + +Nyní víte, jak **vytvořit prázdný grafický stav** v PDF pomocí C# a Aspose.Pdf. Tutoriál pokryl každý krok – od načtení dokumentu po úpravu slovníku `ExtGState` a uložení výsledku – a vysvětlil důvody za každou akcí. + +Odtud můžete: + +* Použít nový grafický stav v obsahových streamech (`gs /GS0`). +* Experimentovat s dalšími klíči, jako je `/SM` (úprava tahu) nebo `/OPM` (režim přetisku). +* Použít stejnou techniku na jiné typy zdrojů, jako `/XObject` nebo `/ColorSpace`. + +Šťastné hackování PDF a neváhejte prozkoumat další scénáře **Aspose PDF graphics state**, jako jsou dynamické změny průhlednosti nebo vlastní režimy míchání! + +## 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 návodu. 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 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/) +- [Jak odstranit grafiku z PDF pomocí Aspose.PDF .NET: kompletní průvodce](/pdf/english/net/images-graphics/remove-graphics-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/programming-with-operators/_index.md b/pdf/dutch/net/programming-with-operators/_index.md index a58af1c622..9972c40aa5 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. | +| [Lege grafische status maken in een PDF met C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Leer hoe u een lege grafische status maakt in een PDF met C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/dutch/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/dutch/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..78a1ee9588 --- /dev/null +++ b/pdf/dutch/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-08-17 +description: Maak een lege grafische toestand aan in een PDF met C# en Aspose.Pdf. + Volg deze stapsgewijze handleiding om ExtGState‑resources veilig te bewerken. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: nl +lastmod: 2026-08-17 +og_description: Maak een lege grafische toestand aan in een PDF met C#. Deze tutorial + laat zien hoe je ExtGState‑resources bewerkt met Aspose.Pdf voor betrouwbare PDF‑wijzigingen. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Maak een lege grafische toestand in PDF met C# – stapsgewijze handleiding +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Hoe een lege grafische toestand in een PDF te maken met C# +url: /nl/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe een lege graphics state te maken in een PDF met C# + +Als je een **lege graphics state** in een PDF moet **maken**, laat deze gids je precies zien hoe je dit doet met C# en Aspose.Pdf. Je ziet een volledig, uitvoerbaar voorbeeld dat een nieuw item toevoegt aan het ExtGState‑woordenboek van de pagina zonder bestaande inhoud te beïnvloeden. + +Werken met PDF‑graphics‑states is een veelvoorkomende behoefte wanneer je transparantie, mengmodi of andere render‑parameters per object wilt regelen. De onderstaande code demonstreert de aanbevolen aanpak, legt uit waarom elke stap belangrijk is, en behandelt typische variaties die je kunt tegenkomen. + +## Voorvereisten + +Voordat je begint, zorg dat je het volgende hebt: + +* .NET 6.0 of later (het voorbeeld compileert ook met .NET Core). +* Een Aspose.Pdf for .NET‑licentie (of een tijdelijke evaluatiesleutel). +* Een map die een `input.pdf`‑bestand bevat dat je wilt aanpassen. +* Basiskennis van C#‑syntaxis en PDF‑concepten zoals resource‑woordenboeken. + +## Stap 1: Het project opzetten en namespaces importeren + +Maak een nieuwe console‑applicatie of integreer de code in een bestaand project. Voeg het Aspose.Pdf‑NuGet‑pakket toe: + +```bash +dotnet add package Aspose.Pdf +``` + +Importeer vervolgens de benodigde namespaces: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Deze imports geven je toegang tot de `Document`, `DictionaryEditor` en PDF‑primitieve klassen die nodig zijn om **lege graphics state**‑items te **maken**. + +## Stap 2: De map definiëren die de PDF‑bestanden bevat + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Vervang het pad door de locatie van jouw eigen PDF‑bestanden. Het opslaan van de directory in een variabele maakt de code herbruikbaar en makkelijker te testen. + +## Stap 3: Het bron‑PDF‑document laden + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Het openen van het document binnen een `using`‑statement zorgt ervoor dat de bestands‑handle automatisch wordt vrijgegeven nadat je de wijzigingen hebt opgeslagen. + +## Stap 4: Toegang krijgen tot de eerste pagina en het Resources‑woordenboek + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` haalt de eerste pagina op (PDF‑paginanummers beginnen bij 1). +* `DictionaryEditor` biedt een handige manier om PDF‑woordenboeken te lezen en te wijzigen. +* Het `ExtGState`‑item bevat alle graphics‑state‑objecten voor de pagina. Als de sleutel niet bestaat, maakt Aspose.Pdf automatisch een leeg woordenboek aan. + +## Stap 5: Een nieuw leeg graphics‑state‑woordenboek bouwen + +De graphics‑state die je toevoegt kan leeg zijn of vooraf gevuld met parameters zoals opacity (`CA`, `ca`) of blend‑mode (`BM`). In deze tutorial maken we een **lege graphics state** en stellen vervolgens een paar typische waarden in om te illustreren hoe het woordenboek werkt. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` maakt een schone container die je kunt vullen met willekeurige graphics‑state‑sleutels. +* Het toevoegen van `CA`, `ca` en `BM` is optioneel; je kunt ze weglaten als je echt een lege state nodig hebt. De code laat zien hoe je items toevoegt wanneer je later de rendering wilt regelen. + +## Stap 6: De nieuwe graphics state invoegen in het ExtGState‑woordenboek + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Het benoemen van het item `"GS0"` volgt de gangbare conventie om graphics‑state‑namen te prefixen met “GS”. Je kunt elke geldige PDF‑naam kiezen die niet conflicteert met bestaande sleutels. + +## Stap 7: Het gewijzigde PDF‑document opslaan + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +De `Save`‑aanroep schrijft het bijgewerkte bestand naar `output.pdf`. Het openen van dit bestand in een PDF‑viewer bevestigt dat de nieuwe graphics state bestaat; je kunt er later naar verwijzen met de `gs`‑operator in content‑streams. + +### Volledige broncode + +Alles samengevoegd ziet het complete programma er als volgt uit: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Het uitvoeren van het programma geeft een bevestigingsregel weer en produceert `output.pdf` met de nieuw toegevoegde graphics state. + +## Waarom deze aanpak het beste werkt + +* **Direct woordenboek bewerken** – Met `DictionaryEditor` hoef je de volledige content‑stream niet te parseren. Je wijzigt alleen de resources die je interesseren. +* **Getypeerde PDF‑primitieven** – `CosPdfNumber`, `CosPdfName` en `CosPdfDictionary` garanderen dat de gegenereerde PDF voldoet aan de PDF 1.7‑specificatie. +* **Veiligheid** – Het `using`‑blok maakt het `Document`‑object schoon, waardoor bestands‑locks die latere builds kunnen corrupt maken, worden voorkomen. +* **Uitbreidbaarheid** – Zodra de lege graphics state bestaat, kun je er vanuit elke content‑operator (`gs`) naar verwijzen om opacity, blend‑mode of andere parameters voor geselecteerde teken‑commando’s te wijzigen. + +## Veelvoorkomende variaties en randgevallen + +| Situatie | Aanbevolen aanpassing | +|-----------|-------------------| +| **Meerdere pagina's** | Loop over `pdfDocument.Pages` en herhaal de woordenboek‑invoeging voor elke pagina die je wilt aanpassen. | +| **Geen bestaand ExtGState‑item** | `resourcesEditor["ExtGState"]` maakt automatisch een leeg woordenboek aan als het niet bestaat. Er is geen extra code nodig. | +| **Andere graphics‑state‑naam** | Vervang `"GS0"` door een naam die past bij jouw naamgevingsconventie, bv. `"MyTransparentState"`. | +| **Alleen een lege state toevoegen** | Laat de `parameters`‑array en de `foreach`‑lus weg; het woordenboek blijft leeg. | +| **Werken met versleutelde PDF's** | Geef het wachtwoord op bij het aanmaken van `new Document(path, password)` voordat je resources bewerkt. | + +## Het resultaat verifiëren + +Je kunt controleren of de graphics state is toegevoegd door de PDF te inspecteren met een low‑level viewer zoals **PDF‑Tron** of **iText Sharp**. Zoek naar een item dat er ongeveer zo uitziet: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Als het item verschijnt, is de **create empty graphics state**‑operatie geslaagd. + +## Conclusie + +Je weet nu hoe je een **lege graphics state** in een PDF kunt **maken** met C# en Aspose.Pdf. De tutorial heeft elke stap behandeld – van het laden van het document tot het bewerken van het `ExtGState`‑woordenboek en het opslaan van het resultaat – en de reden achter elke handeling uitgelegd. + +Vanaf hier kun je: + +* De nieuwe graphics state gebruiken in content‑streams (`gs /GS0`). +* Experimenteren met extra sleutels zoals `/SM` (stroke adjustment) of `/OPM` (overprint mode). +* Dezelfde techniek toepassen op andere resource‑typen zoals `/XObject` of `/ColorSpace`. + +Veel plezier met PDF‑hacking, en voel je vrij om andere **Aspose PDF graphics state**‑scenario’s te verkennen, zoals dynamische opacity‑wijzigingen of aangepaste blend‑modi! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige 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. + +- [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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/_index.md b/pdf/english/net/programming-with-operators/_index.md index 96ad036346..35c56d11d3 100644 --- a/pdf/english/net/programming-with-operators/_index.md +++ b/pdf/english/net/programming-with-operators/_index.md @@ -21,6 +21,7 @@ Aspose.PDF for .NET's "Programming with Operators" tutorials guide you through t | Title | Description | | --- | --- | | [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. | +| [How to create empty graphics state in a PDF with C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Learn how to create an empty graphics state in a PDF using Aspose.PDF for .NET with C# in this 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. | @@ -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/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/english/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..69cbd19f01 --- /dev/null +++ b/pdf/english/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2026-08-17 +description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: en +lastmod: 2026-08-17 +og_description: Create empty graphics state in a PDF using C#. This tutorial shows + how to edit ExtGState resources with Aspose.Pdf for reliable PDF modifications. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Create empty graphics state in PDF with C# – step‑by‑step guide +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: How to create empty graphics state in a PDF with C# +url: /net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to create empty graphics state in a PDF with C# + +If you need to **create empty graphics state** in a PDF, this guide shows you exactly how to do it with C# and Aspose.Pdf. You’ll see a complete, runnable example that adds a new entry to the page’s ExtGState dictionary without affecting existing content. + +Working with PDF graphics states is a common requirement when you want to control transparency, blend modes, or other rendering parameters on a per‑object basis. The code below demonstrates the recommended approach, explains why each step matters, and covers typical variations you might encounter. + +## Prerequisites + +Before you start, make sure you have: + +* .NET 6.0 or later (the sample compiles with .NET Core as well). +* An Aspose.Pdf for .NET license (or a temporary evaluation key). +* A folder that contains an `input.pdf` file you want to modify. +* Basic familiarity with C# syntax and PDF concepts such as resources dictionaries. + +## Step 1: Set up the project and import namespaces + +Create a new console application or integrate the code into an existing project. Add the Aspose.Pdf NuGet package: + +```bash +dotnet add package Aspose.Pdf +``` + +Then import the required namespaces: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +These imports give you access to the `Document`, `DictionaryEditor`, and PDF primitive classes needed to **create empty graphics state** entries. + +## Step 2: Define the folder that holds the PDF files + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Replace the path with the location of your own PDF files. Keeping the directory in a variable makes the code reusable and easier to test. + +## Step 3: Load the source PDF document + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Opening the document inside a `using` statement ensures that the file handle is released automatically after you save the changes. + +## Step 4: Access the first page and its Resources dictionary + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` retrieves the first page (PDF page numbers start at 1). +* `DictionaryEditor` provides a convenient way to read and modify PDF dictionaries. +* The `ExtGState` entry holds all graphics‑state objects for the page. If the key does not exist, Aspose.Pdf creates an empty dictionary automatically. + +## Step 5: Build a new empty graphics‑state dictionary + +The graphics state you add can be empty or pre‑populated with parameters such as opacity (`CA`, `ca`) or blend mode (`BM`). In this tutorial we create an **empty graphics state** and then set a few typical values to illustrate how the dictionary works. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` creates a clean container that you can fill with any graphics‑state keys. +* Adding `CA`, `ca`, and `BM` is optional; you may omit them if you truly need an empty state. The code shows how to add entries when you later decide to control rendering. + +## Step 6: Insert the new graphics state into the ExtGState dictionary + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Naming the entry `"GS0"` follows the common convention of prefixing graphics‑state names with “GS”. You can choose any valid PDF name that does not clash with existing keys. + +## Step 7: Save the modified PDF document + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +The `Save` call writes the updated file to `output.pdf`. Opening this file in a PDF viewer confirms that the new graphics state exists; you can reference it later with the `gs` operator in content streams. + +### Full source listing + +Putting everything together, the complete program looks like this: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Running the program prints a confirmation line and produces `output.pdf` with the newly added graphics state. + +## Why this approach works best + +* **Direct dictionary editing** – Using `DictionaryEditor` avoids the need to parse the entire content stream. You modify only the resources you care about. +* **Typed PDF primitives** – `CosPdfNumber`, `CosPdfName`, and `CosPdfDictionary` guarantee that the generated PDF complies with the PDF 1.7 specification. +* **Safety** – The `using` block disposes of the `Document` object, preventing file locks that could corrupt subsequent builds. +* **Extensibility** – Once the empty graphics state exists, you can reference it from any content operator (`gs`) to change opacity, blend mode, or other parameters for selected drawing commands. + +## Common variations and edge cases + +| Situation | Recommended tweak | +|-----------|-------------------| +| **Multiple pages** | Loop over `pdfDocument.Pages` and repeat the dictionary insertion for each page you need to modify. | +| **No existing ExtGState entry** | `resourcesEditor["ExtGState"]` automatically creates an empty dictionary if it does not exist. No extra code is required. | +| **Different graphics‑state name** | Replace `"GS0"` with a name that matches your naming convention, e.g., `"MyTransparentState"`. | +| **Adding only an empty state** | Omit the `parameters` array and the `foreach` loop; the dictionary will remain empty. | +| **Working with encrypted PDFs** | Supply the password when constructing `new Document(path, password)` before editing resources. | + +## Verifying the result + +You can verify that the graphics state was added by inspecting the PDF with a low‑level viewer such as **PDF‑Tron** or **iText Sharp**. Look for an entry similar to: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +If the entry appears, the **create empty graphics state** operation succeeded. + +## Conclusion + +You now know how to **create empty graphics state** in a PDF using C# and Aspose.Pdf. The tutorial covered every step—from loading the document to editing the `ExtGState` dictionary and saving the result—while explaining the rationale behind each action. + +From here you can: + +* Use the new graphics state in content streams (`gs /GS0`). +* Experiment with additional keys such as `/SM` (stroke adjustment) or `/OPM` (overprint mode). +* Apply the same technique to other resource types like `/XObject` or `/ColorSpace`. + +Happy PDF hacking, and feel free to explore other **Aspose PDF graphics state** scenarios such as dynamic opacity changes or custom blend modes! + + +## 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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/how-to-create-empty-graphics-state-in-a-pdf-with-c/og-image.png b/pdf/english/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/og-image.png new file mode 100644 index 0000000000..926615caa8 Binary files /dev/null and b/pdf/english/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/og-image.png differ diff --git a/pdf/french/net/programming-with-operators/_index.md b/pdf/french/net/programming-with-operators/_index.md index 3b71167812..c51b689889 100644 --- a/pdf/french/net/programming-with-operators/_index.md +++ b/pdf/french/net/programming-with-operators/_index.md @@ -20,6 +20,7 @@ Les tutoriels « Programmation avec opérateurs » d'Aspose.PDF pour .NET vous ## Tutoriels | Titre | Description | | --- | --- | +| [Comment créer un état graphique vide dans un PDF avec C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Apprenez à créer un état graphique vide dans un PDF avec Aspose.PDF pour .NET en C#. | | [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. | diff --git a/pdf/french/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/french/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..63dc783c70 --- /dev/null +++ b/pdf/french/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2026-08-17 +description: Créez un état graphique vide dans un PDF en utilisant C# et Aspose.Pdf. + Suivez ce guide étape par étape pour modifier les ressources ExtGState en toute + sécurité. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: fr +lastmod: 2026-08-17 +og_description: Créer un état graphique vide dans un PDF en C#. Ce tutoriel montre + comment modifier les ressources ExtGState avec Aspose.Pdf pour des modifications + fiables de PDF. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Créer un état graphique vide dans un PDF avec C# – guide étape par étape +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Comment créer un état graphique vide dans un PDF avec C# +url: /fr/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment créer un état graphique vide dans un PDF avec C# + +Si vous devez **créer un état graphique vide** dans un PDF, ce guide vous montre exactement comment le faire avec C# et Aspose.Pdf. Vous verrez un exemple complet et exécutable qui ajoute une nouvelle entrée au dictionnaire ExtGState de la page sans affecter le contenu existant. + +Travailler avec les états graphiques PDF est une exigence courante lorsque vous voulez contrôler la transparence, les modes de fusion ou d’autres paramètres de rendu objet par objet. Le code ci‑dessous démontre l’approche recommandée, explique pourquoi chaque étape est importante et couvre les variations typiques que vous pourriez rencontrer. + +## Prérequis + +Avant de commencer, assurez‑vous d’avoir : + +* .NET 6.0 ou ultérieur (l’exemple se compile également avec .NET Core). +* Une licence Aspose.Pdf for .NET (ou une clé d’évaluation temporaire). +* Un dossier contenant un fichier `input.pdf` que vous souhaitez modifier. +* Une connaissance de base de la syntaxe C# et des concepts PDF tels que les dictionnaires de ressources. + +## Étape 1 : Configurer le projet et importer les espaces de noms + +Créez une nouvelle application console ou intégrez le code dans un projet existant. Ajoutez le package NuGet Aspose.Pdf : + +```bash +dotnet add package Aspose.Pdf +``` + +Puis importez les espaces de noms requis : + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Ces imports vous donnent accès aux classes `Document`, `DictionaryEditor` et aux primitives PDF nécessaires pour **créer des entrées d’état graphique vides**. + +## Étape 2 : Définir le dossier contenant les fichiers PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Remplacez le chemin par l’emplacement de vos propres fichiers PDF. Conserver le répertoire dans une variable rend le code réutilisable et plus facile à tester. + +## Étape 3 : Charger le document PDF source + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Ouvrir le document à l’intérieur d’une instruction `using` garantit que le handle du fichier est libéré automatiquement après l’enregistrement des modifications. + +## Étape 4 : Accéder à la première page et à son dictionnaire Resources + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` récupère la première page (les numéros de page PDF commencent à 1). +* `DictionaryEditor` offre un moyen pratique de lire et de modifier les dictionnaires PDF. +* L’entrée `ExtGState` contient tous les objets d’état graphique de la page. Si la clé n’existe pas, Aspose.Pdf crée automatiquement un dictionnaire vide. + +## Étape 5 : Construire un nouveau dictionnaire d’état graphique vide + +L’état graphique que vous ajoutez peut être vide ou pré‑rempli avec des paramètres tels que l’opacité (`CA`, `ca`) ou le mode de fusion (`BM`). Dans ce tutoriel nous créons un **état graphique vide** puis définissons quelques valeurs typiques pour illustrer le fonctionnement du dictionnaire. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` crée un conteneur vierge que vous pouvez remplir avec n’importe quelles clés d’état graphique. +* Ajouter `CA`, `ca` et `BM` est optionnel ; vous pouvez les omettre si vous avez réellement besoin d’un état vide. Le code montre comment ajouter des entrées lorsque vous décidez plus tard de contrôler le rendu. + +## Étape 6 : Insérer le nouvel état graphique dans le dictionnaire ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Nommer l’entrée `"GS0"` suit la convention courante de préfixer les noms d’états graphiques par « GS ». Vous pouvez choisir n’importe quel nom PDF valide qui ne rentre pas en conflit avec des clés existantes. + +## Étape 7 : Enregistrer le document PDF modifié + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +L’appel `Save` écrit le fichier mis à jour sous `output.pdf`. Ouvrir ce fichier dans un visualiseur PDF confirme que le nouvel état graphique existe ; vous pourrez le référencer plus tard avec l’opérateur `gs` dans les flux de contenu. + +### Listing complet du code source + +En rassemblant le tout, le programme complet ressemble à ceci : + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +L’exécution du programme affiche une ligne de confirmation et produit `output.pdf` contenant le nouvel état graphique ajouté. + +## Pourquoi cette approche est la meilleure + +* **Édition directe du dictionnaire** – L’utilisation de `DictionaryEditor` évite d’analyser tout le flux de contenu. Vous ne modifiez que les ressources qui vous intéressent. +* **Primitives PDF typées** – `CosPdfNumber`, `CosPdfName` et `CosPdfDictionary` garantissent que le PDF généré respecte la spécification PDF 1.7. +* **Sécurité** – Le bloc `using` libère l’objet `Document`, prévenant les verrous de fichier qui pourraient corrompre des builds ultérieurs. +* **Extensibilité** – Une fois l’état graphique vide créé, vous pouvez le référencer depuis n’importe quel opérateur de contenu (`gs`) pour modifier l’opacité, le mode de fusion ou d’autres paramètres pour des commandes de dessin sélectionnées. + +## Variations courantes et cas limites + +| Situation | Ajustement recommandé | +|-----------|-----------------------| +| **Pages multiples** | Parcourez `pdfDocument.Pages` et répétez l’insertion du dictionnaire pour chaque page que vous devez modifier. | +| **Pas d’entrée ExtGState existante** | `resourcesEditor["ExtGState"]` crée automatiquement un dictionnaire vide s’il n’existe pas. Aucun code supplémentaire n’est nécessaire. | +| **Nom d’état graphique différent** | Remplacez `"GS0"` par un nom qui correspond à votre convention, par ex. `"MyTransparentState"`. | +| **Ajout d’un seul état vide** | Omettez le tableau `parameters` et la boucle `foreach` ; le dictionnaire restera vide. | +| **Travail avec des PDF chiffrés** | Fournissez le mot de passe lors de la construction `new Document(path, password)` avant de modifier les ressources. | + +## Vérification du résultat + +Vous pouvez vérifier que l’état graphique a été ajouté en inspectant le PDF avec un visualiseur bas‑niveau tel que **PDF‑Tron** ou **iText Sharp**. Recherchez une entrée similaire à : + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Si l’entrée apparaît, l’opération **create empty graphics state** a réussi. + +## Conclusion + +Vous savez maintenant comment **créer un état graphique vide** dans un PDF en utilisant C# et Aspose.Pdf. Le tutoriel a couvert chaque étape — du chargement du document à la modification du dictionnaire `ExtGState` et à l’enregistrement du résultat — tout en expliquant la logique derrière chaque action. + +À partir d’ici, vous pouvez : + +* Utiliser le nouvel état graphique dans les flux de contenu (`gs /GS0`). +* Expérimenter avec des clés supplémentaires comme `/SM` (ajustement du trait) ou `/OPM` (mode surimpression). +* Appliquer la même technique à d’autres types de ressources comme `/XObject` ou `/ColorSpace`. + +Bonne manipulation de PDF, et n’hésitez pas à explorer d’autres scénarios **Aspose PDF graphics state** tels que les changements d’opacité dynamiques ou les modes de fusion personnalisés ! + +## Que devez‑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 inclut des exemples de code complets et fonctionnels avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et à explorer des approches d’implémentation 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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/programming-with-operators/_index.md b/pdf/german/net/programming-with-operators/_index.md index 4969bb117c..761027436e 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. | +| [Wie man einen leeren Grafikzustand in einem PDF mit C# erstellt](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Erfahren Sie, wie Sie mit Aspose.PDF für .NET einen leeren Grafikzustand in einem PDF mit C# erzeugen. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/german/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/german/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..d1fb19c1e7 --- /dev/null +++ b/pdf/german/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-08-17 +description: Erstellen Sie einen leeren Grafikzustand in einem PDF mit C# und Aspose.Pdf. + Befolgen Sie diese Schritt‑für‑Schritt‑Anleitung, um ExtGState‑Ressourcen sicher + zu bearbeiten. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: de +lastmod: 2026-08-17 +og_description: Erstellen Sie einen leeren Grafikzustand in einem PDF mit C#. Dieses + Tutorial zeigt, wie man ExtGState‑Ressourcen mit Aspose.Pdf bearbeitet, um zuverlässige + PDF‑Modifikationen vorzunehmen. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Leeren Grafikzustand in PDF mit C# erstellen – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Wie man einen leeren Grafikzustand in einem PDF mit C# erstellt +url: /de/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man einen leeren Grafikzustand in einem PDF mit C# erstellt + +Wenn Sie einen **leeren Grafikzustand** in einem PDF **erstellen** müssen, zeigt Ihnen dieser Leitfaden genau, wie Sie dies mit C# und Aspose.Pdf tun. Sie sehen ein vollständiges, ausführbares Beispiel, das einen neuen Eintrag zum ExtGState‑Wörterbuch der Seite hinzufügt, ohne vorhandenen Inhalt zu beeinflussen. + +Die Arbeit mit PDF‑Grafikzuständen ist eine häufige Anforderung, wenn Sie Transparenz, Mischmodi oder andere Render‑Parameter auf Objektbasis steuern möchten. Der untenstehende Code demonstriert den empfohlenen Ansatz, erklärt, warum jeder Schritt wichtig ist, und behandelt typische Variationen, denen Sie begegnen könnten. + +## Voraussetzungen + +* .NET 6.0 oder höher (das Beispiel lässt sich auch mit .NET Core kompilieren). +* Eine Aspose.Pdf for .NET Lizenz (oder ein temporärer Evaluierungsschlüssel). +* Ein Ordner, der eine `input.pdf`‑Datei enthält, die Sie ändern möchten. +* Grundlegende Kenntnisse der C#‑Syntax und von PDF‑Konzepten wie Ressourcen‑Wörterbüchern. + +## Schritt 1: Projekt einrichten und Namespaces importieren + +Erstellen Sie eine neue Konsolenanwendung oder integrieren Sie den Code in ein bestehendes Projekt. Fügen Sie das Aspose.Pdf‑NuGet‑Paket hinzu: + +```bash +dotnet add package Aspose.Pdf +``` + +Anschließend importieren Sie die erforderlichen Namespaces: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Diese Importe geben Ihnen Zugriff auf die Klassen `Document`, `DictionaryEditor` und PDF‑Primitive, die zum **Erstellen leerer Grafikzustände** erforderlich sind. + +## Schritt 2: Ordner festlegen, der die PDF‑Dateien enthält + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Ersetzen Sie den Pfad durch den Speicherort Ihrer eigenen PDF‑Dateien. Das Halten des Verzeichnisses in einer Variablen macht den Code wiederverwendbar und einfacher zu testen. + +## Schritt 3: Quell‑PDF‑Dokument laden + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Das Öffnen des Dokuments innerhalb einer `using`‑Anweisung stellt sicher, dass der Dateihandle nach dem Speichern der Änderungen automatisch freigegeben wird. + +## Schritt 4: Erste Seite und ihr Ressourcen‑Wörterbuch zugreifen + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` ruft die erste Seite ab (PDF‑Seitenzahlen beginnen bei 1). +* `DictionaryEditor` bietet eine bequeme Möglichkeit, PDF‑Wörterbücher zu lesen und zu ändern. +* Der Eintrag `ExtGState` enthält alle Grafik‑Zustandsobjekte für die Seite. Wenn der Schlüssel nicht existiert, erstellt Aspose.Pdf automatisch ein leeres Wörterbuch. + +## Schritt 5: Neues leeres Grafik‑Zustands‑Wörterbuch erstellen + +Der Grafikzustand, den Sie hinzufügen, kann leer sein oder bereits mit Parametern wie Opazität (`CA`, `ca`) oder Mischmodus (`BM`) vorbefüllt sein. In diesem Tutorial erstellen wir einen **leeren Grafikzustand** und setzen anschließend einige typische Werte, um zu zeigen, wie das Wörterbuch funktioniert. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` erstellt einen leeren Container, den Sie mit beliebigen Grafik‑Zustands‑Schlüsseln füllen können. +* Das Hinzufügen von `CA`, `ca` und `BM` ist optional; Sie können sie weglassen, wenn Sie wirklich einen leeren Zustand benötigen. Der Code zeigt, wie Einträge hinzugefügt werden, wenn Sie später das Rendering steuern möchten. + +## Schritt 6: Neuen Grafikzustand in das ExtGState‑Wörterbuch einfügen + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Die Benennung des Eintrags `"GS0"` folgt der üblichen Konvention, Grafik‑Zustands‑Namen mit „GS“ zu prefixed. Sie können jeden gültigen PDF‑Namen wählen, der nicht mit bestehenden Schlüsseln kollidiert. + +## Schritt 7: Modifiziertes PDF‑Dokument speichern + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +Der Aufruf `Save` schreibt die aktualisierte Datei nach `output.pdf`. Das Öffnen dieser Datei in einem PDF‑Betrachter bestätigt, dass der neue Grafikzustand existiert; Sie können später mit dem `gs`‑Operator in Inhaltsstreams darauf verweisen. + +### Vollständige Quellcode‑Auflistung + +Wenn das Programm ausgeführt wird, gibt es eine Bestätigungszeile aus und erzeugt `output.pdf` mit dem neu hinzugefügten Grafikzustand. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +## Warum dieser Ansatz am besten funktioniert + +* **Direktes Wörterbuch‑Editing** – Die Verwendung von `DictionaryEditor` vermeidet das Parsen des gesamten Inhaltsstreams. Sie ändern nur die Ressourcen, die Sie interessieren. +* **Typisierte PDF‑Primitive** – `CosPdfNumber`, `CosPdfName` und `CosPdfDictionary` garantieren, dass das erzeugte PDF der PDF 1.7‑Spezifikation entspricht. +* **Sicherheit** – Der `using`‑Block gibt das `Document`‑Objekt frei und verhindert Dateisperren, die nachfolgende Builds beschädigen könnten. +* **Erweiterbarkeit** – Sobald der leere Grafikzustand existiert, können Sie ihn von jedem Inhaltsoperator (`gs`) aus referenzieren, um Opazität, Mischmodus oder andere Parameter für ausgewählte Zeichenbefehle zu ändern. + +## Häufige Variationen und Sonderfälle + +| Situation | Empfohlene Anpassung | +|-----------|----------------------| +| **Mehrere Seiten** | Durchlaufen Sie `pdfDocument.Pages` und wiederholen Sie das Einfügen des Wörterbuchs für jede Seite, die Sie ändern müssen. | +| **Kein vorhandener ExtGState‑Eintrag** | `resourcesEditor["ExtGState"]` erstellt automatisch ein leeres Wörterbuch, wenn es nicht existiert. Kein zusätzlicher Code ist erforderlich. | +| **Anderer Grafik‑Zustands‑Name** | Ersetzen Sie `"GS0"` durch einen Namen, der Ihrer Namenskonvention entspricht, z. B. `"MyTransparentState"`. | +| **Nur einen leeren Zustand hinzufügen** | Lassen Sie das `parameters`‑Array und die `foreach`‑Schleife weg; das Wörterbuch bleibt leer. | +| **Arbeiten mit verschlüsselten PDFs** | Geben Sie das Passwort beim Erzeugen von `new Document(path, password)` an, bevor Sie Ressourcen bearbeiten. | + +## Ergebnis verifizieren + +Sie können überprüfen, dass der Grafikzustand hinzugefügt wurde, indem Sie das PDF mit einem Low‑Level‑Viewer wie **PDF‑Tron** oder **iText Sharp** inspizieren. Suchen Sie nach einem Eintrag ähnlich wie: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Wenn der Eintrag erscheint, war die **Erstellung eines leeren Grafikzustands** erfolgreich. + +## Fazit + +Sie wissen jetzt, wie Sie mit C# und Aspose.Pdf einen **leeren Grafikzustand** in einem PDF **erstellen**. Das Tutorial behandelte jeden Schritt – vom Laden des Dokuments über das Bearbeiten des `ExtGState`‑Wörterbuchs bis zum Speichern des Ergebnisses – und erklärte die Begründung hinter jeder Aktion. + +Ab hier können Sie: + +* Den neuen Grafikzustand in Inhaltsstreams verwenden (`gs /GS0`). +* Mit zusätzlichen Schlüsseln wie `/SM` (Strichanpassung) oder `/OPM` (Überdruckmodus) experimentieren. +* Die gleiche Technik auf andere Ressourcentypen wie `/XObject` oder `/ColorSpace` anwenden. + +Viel Spaß beim PDF‑Hacken und fühlen Sie sich frei, weitere **Aspose PDF Grafikzustands**‑Szenarien zu erkunden, wie dynamische Opazitätsänderungen oder benutzerdefinierte Mischmodi! + +## Was sollten Sie als Nächstes lernen? + +- [Wie man gestrichelte Linien in PDFs mit Aspose.PDF für .NET erstellt: Eine Schritt‑für‑Schritt‑Anleitung](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Wie man Grafiken aus PDFs mit Aspose.PDF .NET entfernt: Ein vollständiger Leitfaden](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [Rechtecke in PDFs erstellen & füllen mit Aspose.PDF für .NET: Eine Schritt‑für‑Schritt‑Anleitung](/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/programming-with-operators/_index.md b/pdf/greek/net/programming-with-operators/_index.md index d85e0461f7..e9dcfc2e30 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#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Μάθετε πώς να δημιουργήσετε μια κενή κατάσταση γραφικών σε PDF χρησιμοποιώντας C# και Aspose.PDF. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/greek/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/greek/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..5884208d63 --- /dev/null +++ b/pdf/greek/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-08-17 +description: Δημιουργήστε κενή κατάσταση γραφικών σε ένα PDF χρησιμοποιώντας C# και + Aspose.Pdf. Ακολουθήστε αυτόν τον οδηγό βήμα-βήμα για να επεξεργαστείτε με ασφάλεια + τους πόρους ExtGState. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: el +lastmod: 2026-08-17 +og_description: Δημιουργήστε κενή κατάσταση γραφικών σε PDF χρησιμοποιώντας C#. Αυτό + το σεμινάριο δείχνει πώς να επεξεργαστείτε τους πόρους ExtGState με το Aspose.Pdf + για αξιόπιστες τροποποιήσεις PDF. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Δημιουργία κενής κατάστασης γραφικών σε PDF με C# – οδηγός βήμα‑προς‑βήμα +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Πώς να δημιουργήσετε κενή κατάσταση γραφικών σε PDF με C# +url: /el/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να δημιουργήσετε κενή κατάσταση γραφικών σε PDF με C# + +Αν χρειάζεστε **να δημιουργήσετε κενή κατάσταση γραφικών** σε ένα PDF, αυτός ο οδηγός σας δείχνει ακριβώς πώς να το κάνετε με C# και Aspose.Pdf. Θα δείτε ένα πλήρες, εκτελέσιμο παράδειγμα που προσθέτει μια νέα καταχώρηση στο λεξικό ExtGState της σελίδας χωρίς να επηρεάζει το υπάρχον περιεχόμενο. + +Η εργασία με καταστάσεις γραφικών PDF είναι μια κοινή απαίτηση όταν θέλετε να ελέγξετε τη διαφάνεια, τις λειτουργίες ανάμειξης ή άλλες παραμέτρους απόδοσης ανά αντικείμενο. Ο παρακάτω κώδικας δείχνει την προτεινόμενη προσέγγιση, εξηγεί γιατί κάθε βήμα είναι σημαντικό και καλύπτει τυπικές παραλλαγές που μπορεί να συναντήσετε. + +## Προαπαιτούμενα + +* .NET 6.0 ή νεότερο (το παράδειγμα μεταγλωττίζεται επίσης με .NET Core). +* Άδεια Aspose.Pdf for .NET (ή προσωρινό κλειδί αξιολόγησης). +* Ένας φάκελος που περιέχει το αρχείο `input.pdf` που θέλετε να τροποποιήσετε. +* Βασική εξοικείωση με τη σύνταξη C# και έννοιες PDF όπως τα λεξικά πόρων. + +## Βήμα 1: Ρύθμιση του έργου και εισαγωγή namespaces + +Δημιουργήστε μια νέα εφαρμογή κονσόλας ή ενσωματώστε τον κώδικα σε ένα υπάρχον έργο. Προσθέστε το πακέτο NuGet Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Στη συνέχεια, εισάγετε τα απαιτούμενα namespaces: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Αυτές οι εισαγωγές σας δίνουν πρόσβαση στις κλάσεις `Document`, `DictionaryEditor` και τις πρωτότυπες κλάσεις PDF που χρειάζονται για τη **δημιουργία κενής κατάστασης γραφικών**. + +## Βήμα 2: Ορισμός του φακέλου που περιέχει τα αρχεία PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Αντικαταστήστε τη διαδρομή με τη θέση των δικών σας αρχείων PDF. Η διατήρηση του καταλόγου σε μια μεταβλητή κάνει τον κώδικα επαναχρησιμοποιήσιμο και πιο εύκολο στη δοκιμή. + +## Βήμα 3: Φόρτωση του πηγαίου εγγράφου PDF + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Το άνοιγμα του εγγράφου μέσα σε δήλωση `using` εξασφαλίζει ότι το χειριστήριο του αρχείου απελευθερώνεται αυτόματα μετά την αποθήκευση των αλλαγών. + +## Βήμα 4: Πρόσβαση στην πρώτη σελίδα και στο λεξικό Resources της + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` ανακτά την πρώτη σελίδα (οι αριθμοί σελίδων PDF ξεκινούν από 1). +* `DictionaryEditor` παρέχει έναν βολικό τρόπο για ανάγνωση και τροποποίηση λεξικών PDF. +* Η καταχώρηση `ExtGState` περιέχει όλα τα αντικείμενα κατάστασης γραφικών για τη σελίδα. Εάν το κλειδί δεν υπάρχει, το Aspose.Pdf δημιουργεί αυτόματα ένα κενό λεξικό. + +## Βήμα 5: Δημιουργία νέου λεξικού κενής κατάστασης γραφικών + +Η κατάσταση γραφικών που προσθέτετε μπορεί να είναι κενή ή προ‑συμπληρωμένη με παραμέτρους όπως η διαφάνεια (`CA`, `ca`) ή η λειτουργία ανάμειξης (`BM`). Σε αυτό το tutorial δημιουργούμε μια **κενή κατάσταση γραφικών** και στη συνέχεια ορίζουμε μερικές τυπικές τιμές για να δείξουμε πώς λειτουργεί το λεξικό. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` δημιουργεί ένα καθαρό κοντέινερ που μπορείτε να γεμίσετε με οποιαδήποτε κλειδιά κατάστασης γραφικών. +* Η προσθήκη των `CA`, `ca` και `BM` είναι προαιρετική· μπορείτε να τα παραλείψετε εάν χρειάζεστε πραγματικά μια κενή κατάσταση. Ο κώδικας δείχνει πώς να προσθέσετε καταχωρήσεις όταν αποφασίσετε αργότερα να ελέγξετε την απόδοση. + +## Βήμα 6: Εισαγωγή της νέας κατάστασης γραφικών στο λεξικό ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Η ονομασία της καταχώρησης `"GS0"` ακολουθεί τη συνήθη σύμβαση προθέματος των ονομάτων κατάστασης γραφικών με “GS”. Μπορείτε να επιλέξετε οποιοδήποτε έγκυρο όνομα PDF που δεν συγκρούεται με υπάρχοντα κλειδιά. + +## Βήμα 7: Αποθήκευση του τροποποιημένου εγγράφου PDF + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +Η κλήση `Save` γράφει το ενημερωμένο αρχείο στο `output.pdf`. Το άνοιγμα αυτού του αρχείου σε προβολέα PDF επιβεβαιώνει ότι η νέα κατάσταση γραφικών υπάρχει· μπορείτε να την αναφερθείτε αργότερα με τον τελεστή `gs` στα ρεύματα περιεχομένου. + +### Πλήρης λίστα πηγαίου κώδικα + +Εκτελώντας το πρόγραμμα εκτυπώνει μια γραμμή επιβεβαίωσης και παράγει το `output.pdf` με τη νέα προστιθέμενη κατάσταση γραφικών. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +## Γιατί αυτή η προσέγγιση λειτουργεί καλύτερα + +* **Άμεση επεξεργασία λεξικού** – Η χρήση του `DictionaryEditor` αποφεύγει την ανάγκη ανάλυσης ολόκληρου του ρεύματος περιεχομένου. Τροποποιείτε μόνο τους πόρους που σας ενδιαφέρουν. +* **Τυποποιημένα PDF primitives** – Τα `CosPdfNumber`, `CosPdfName` και `CosPdfDictionary` εγγυώνται ότι το παραγόμενο PDF συμμορφώνεται με την προδιαγραφή PDF 1.7. +* **Ασφάλεια** – Το μπλοκ `using` απελευθερώνει το αντικείμενο `Document`, αποτρέποντας κλειδώματα αρχείων που θα μπορούσαν να καταστρέψουν επόμενες κατασκευές. +* **Επεκτασιμότητα** – Μόλις υπάρχει η κενή κατάσταση γραφικών, μπορείτε να την αναφέρετε από οποιονδήποτε τελεστή περιεχομένου (`gs`) για να αλλάξετε τη διαφάνεια, τη λειτουργία ανάμειξης ή άλλες παραμέτρους για επιλεγμένες εντολές σχεδίασης. + +## Συνηθισμένες παραλλαγές και ειδικές περιπτώσεις + +| Κατάσταση | Συνιστώμενη τροποποίηση | +|-----------|-------------------| +| **Πολλές σελίδες** | Επανάληψη πάνω από `pdfDocument.Pages` και επανάληψη της εισαγωγής λεξικού για κάθε σελίδα που χρειάζεται να τροποποιήσετε. | +| **Καμία υπάρχουσα καταχώρηση ExtGState** | `resourcesEditor["ExtGState"]` δημιουργεί αυτόματα ένα κενό λεξικό εάν δεν υπάρχει. Δεν απαιτείται επιπλέον κώδικας. | +| **Διαφορετικό όνομα κατάστασης γραφικών** | Αντικαταστήστε το `"GS0"` με ένα όνομα που ταιριάζει με τη δική σας σύμβαση ονοματοδοσίας, π.χ., `"MyTransparentState"`. | +| **Προσθήκη μόνο κενής κατάστασης** | Παραλείψτε τον πίνακα `parameters` και τον βρόχο `foreach`; το λεξικό θα παραμείνει κενό. | +| **Εργασία με κρυπτογραφημένα PDF** | Παρέχετε τον κωδικό πρόσβασης κατά τη δημιουργία του `new Document(path, password)` πριν την επεξεργασία των πόρων. | + +## Επαλήθευση του αποτελέσματος + +Μπορείτε να επαληθεύσετε ότι η κατάσταση γραφικών προστέθηκε εξετάζοντας το PDF με έναν χαμηλού επιπέδου προβολέα όπως το **PDF‑Tron** ή το **iText Sharp**. Αναζητήστε μια καταχώρηση παρόμοια με: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Εάν η καταχώρηση εμφανιστεί, η λειτουργία **δημιουργίας κενής κατάστασης γραφικών** πέτυχε. + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **δημιουργήσετε κενή κατάσταση γραφικών** σε PDF χρησιμοποιώντας C# και Aspose.Pdf. Το tutorial κάλυψε κάθε βήμα—από τη φόρτωση του εγγράφου μέχρι την επεξεργασία του λεξικού `ExtGState` και την αποθήκευση του αποτελέσματος—εξηγώντας τη λογική πίσω από κάθε ενέργεια. + +Από εδώ μπορείτε: + +* Να χρησιμοποιήσετε τη νέα κατάσταση γραφικών σε ρεύματα περιεχομένου (`gs /GS0`). +* Να πειραματιστείτε με πρόσθετα κλειδιά όπως `/SM` (ρύθμιση χτυπήματος) ή `/OPM` (λειτουργία overprint). +* Να εφαρμόσετε την ίδια τεχνική σε άλλους τύπους πόρων όπως `/XObject` ή `/ColorSpace`. + +Καλή διασκέδαση με το PDF hacking, και μη διστάσετε να εξερευνήσετε άλλες περιπτώσεις **Aspose PDF graphics state** όπως δυναμικές αλλαγές διαφάνειας ή προσαρμοσμένες λειτουργίες ανάμειξης! + +## Τι Θα Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες 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/remove-graphics-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/hindi/net/programming-with-operators/_index.md b/pdf/hindi/net/programming-with-operators/_index.md index c421e807e7..5b2eb360e1 100644 --- a/pdf/hindi/net/programming-with-operators/_index.md +++ b/pdf/hindi/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ 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 हेरफेर कार्यों को सरल बनाएँ। | +| [पीडीएफ फाइल में ग्राफिक ऑब्जेक्ट्स हटाएँ](./remove-graphics-objects/) | इस चरण-दर-श... | +| [C# के साथ PDF में खाली ग्राफ़िक्स स्टेट बनाना](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | C# का उपयोग करके PDF में खाली ग्राफ़िक्स स्टेट बनाने की चरण-दर-चरण मार्गदर्शिका। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/hindi/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/hindi/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..ed42da4e61 --- /dev/null +++ b/pdf/hindi/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-08-17 +description: C# और Aspose.Pdf का उपयोग करके PDF में खाली ग्राफ़िक्स स्टेट बनाएं। ExtGState + संसाधनों को सुरक्षित रूप से संपादित करने के लिए इस चरण‑दर‑चरण मार्गदर्शिका का पालन + करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: hi +lastmod: 2026-08-17 +og_description: C# का उपयोग करके PDF में खाली ग्राफ़िक्स स्टेट बनाएं। यह ट्यूटोरियल + दिखाता है कि Aspose.Pdf के साथ ExtGState संसाधनों को कैसे संपादित किया जाए, ताकि + विश्वसनीय PDF संशोधन किया जा सके। +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: C# के साथ PDF में खाली ग्राफ़िक्स स्टेट बनाएं – चरण‑दर‑चरण मार्गदर्शिका +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: C# के साथ PDF में खाली ग्राफ़िक्स स्टेट कैसे बनाएं +url: /hi/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# के साथ PDF में खाली ग्राफ़िक्स स्टेट कैसे बनाएं + +यदि आपको PDF में **खाली ग्राफ़िक्स स्टेट बनाएं** है, तो यह गाइड आपको C# और Aspose.Pdf के साथ इसे कैसे करें दिखाता है। आप एक पूर्ण, चलाने योग्य उदाहरण देखेंगे जो पृष्ठ के ExtGState डिक्शनरी में एक नया एंट्री जोड़ता है बिना मौजूदा सामग्री को प्रभावित किए। + +PDF ग्राफ़िक्स स्टेट्स के साथ काम करना एक सामान्य आवश्यकता है जब आप ट्रांसपेरेंसी, ब्लेंड मोड्स, या अन्य रेंडरिंग पैरामीटर्स को प्रति‑ऑब्जेक्ट आधार पर नियंत्रित करना चाहते हैं। नीचे दिया गया कोड अनुशंसित दृष्टिकोण को दर्शाता है, प्रत्येक चरण के महत्व को समझाता है, और आप जिन सामान्य विविधताओं का सामना कर सकते हैं उन्हें कवर करता है। + +## आवश्यकताएँ + +* .NET 6.0 या बाद का संस्करण (सैंपल .NET Core के साथ भी संकलित होता है)। +* Aspose.Pdf for .NET लाइसेंस (या एक अस्थायी मूल्यांकन कुंजी)। +* एक फ़ोल्डर जिसमें वह `input.pdf` फ़ाइल हो जिसे आप संशोधित करना चाहते हैं। +* C# सिंटैक्स और PDF अवधारणाओं जैसे resources dictionaries की बुनियादी जानकारी। + +## चरण 1: प्रोजेक्ट सेट अप करें और नेमस्पेस इम्पोर्ट करें + +एक नया कंसोल एप्लिकेशन बनाएं या कोड को मौजूदा प्रोजेक्ट में इंटीग्रेट करें। Aspose.Pdf NuGet पैकेज जोड़ें: + +```bash +dotnet add package Aspose.Pdf +``` + +फिर आवश्यक नेमस्पेस इम्पोर्ट करें: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +ये इम्पोर्ट आपको `Document`, `DictionaryEditor`, और PDF प्रिमिटिव क्लासेज़ तक पहुँच देते हैं जो **खाली ग्राफ़िक्स स्टेट बनाएं** एंट्रीज़ के लिए आवश्यक हैं। + +## चरण 2: PDF फ़ाइलों को रखने वाले फ़ोल्डर को परिभाषित करें + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +पथ को अपने PDF फ़ाइलों के स्थान से बदलें। डायरेक्टरी को एक वेरिएबल में रखना कोड को पुन: उपयोग योग्य और परीक्षण में आसान बनाता है। + +## चरण 3: स्रोत PDF दस्तावेज़ लोड करें + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +`using` स्टेटमेंट के भीतर दस्तावेज़ खोलने से फ़ाइल हैंडल स्वचालित रूप से रिलीज़ हो जाता है जब आप परिवर्तन सहेजते हैं। + +## चरण 4: पहले पृष्ठ और उसके Resources डिक्शनरी तक पहुँचें + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` पहला पृष्ठ प्राप्त करता है (PDF पेज नंबर 1 से शुरू होते हैं)। +* `DictionaryEditor` PDF डिक्शनरी को पढ़ने और संशोधित करने का सुविधाजनक तरीका प्रदान करता है। +* `ExtGState` एंट्री पृष्ठ के सभी graphics‑state ऑब्जेक्ट्स रखती है। यदि कुंजी मौजूद नहीं है, तो Aspose.Pdf स्वचालित रूप से एक खाली डिक्शनरी बनाता है। + +## चरण 5: नया खाली graphics‑state डिक्शनरी बनाएं + +आप जो graphics state जोड़ते हैं वह खाली या opacity (`CA`, `ca`) या blend mode (`BM`) जैसे पैरामीटर्स के साथ पूर्व‑भरा हो सकता है। इस ट्यूटोरियल में हम **खाली ग्राफ़िक्स स्टेट** बनाते हैं और फिर कुछ सामान्य मान सेट करके दिखाते हैं कि डिक्शनरी कैसे काम करती है। + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` एक साफ कंटेनर बनाता है जिसे आप किसी भी graphics‑state कुंजियों से भर सकते हैं। +* `CA`, `ca`, और `BM` जोड़ना वैकल्पिक है; यदि आपको वास्तव में एक खाली स्टेट चाहिए तो आप इन्हें छोड़ सकते हैं। कोड दिखाता है कि बाद में रेंडरिंग को नियंत्रित करने के लिए एंट्री कैसे जोड़ें। + +## चरण 6: नया graphics state ExtGState डिक्शनरी में डालें + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +एंट्री का नाम `"GS0"` रखने से ग्राफ़िक्स‑state नामों को “GS” से प्रीफ़िक्स करने की सामान्य प्रथा का पालन होता है। आप कोई भी वैध PDF नाम चुन सकते हैं जो मौजूदा कुंजियों से टकराता न हो। + +## चरण 7: संशोधित PDF दस्तावेज़ सहेजें + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +`Save` कॉल अपडेटेड फ़ाइल को `output.pdf` में लिखता है। इस फ़ाइल को PDF व्यूअर में खोलने से पुष्टि होती है कि नया graphics state मौजूद है; आप बाद में इसे कंटेंट स्ट्रीम में `gs` ऑपरेटर के साथ रेफ़र कर सकते हैं। + +### पूर्ण स्रोत सूची + +सब कुछ मिलाकर, पूरा प्रोग्राम इस प्रकार दिखता है: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +प्रोग्राम चलाने से एक पुष्टि पंक्ति प्रिंट होती है और `output.pdf` बनता है जिसमें नया graphics state जोड़ा गया है। + +## क्यों यह दृष्टिकोण सबसे अच्छा काम करता है + +* **Direct dictionary editing** – `DictionaryEditor` का उपयोग करने से पूरे कंटेंट स्ट्रीम को पार्स करने की आवश्यकता नहीं रहती। आप केवल उन रिसोर्सेज़ को संशोधित करते हैं जिनकी आपको ज़रूरत है। +* **Typed PDF primitives** – `CosPdfNumber`, `CosPdfName`, और `CosPdfDictionary` यह सुनिश्चित करते हैं कि उत्पन्न PDF PDF 1.7 स्पेसिफिकेशन के अनुरूप हो। +* **Safety** – `using` ब्लॉक `Document` ऑब्जेक्ट को डिस्पोज़ कर देता है, जिससे फ़ाइल लॉक नहीं होते जो बाद के बिल्ड को भ्रष्ट कर सकते हैं। +* **Extensibility** – एक बार खाली graphics state बन जाने पर, आप इसे किसी भी कंटेंट ऑपरेटर (`gs`) से रेफ़र कर सकते हैं ताकि चयनित ड्रॉइंग कमांड्स के लिए opacity, blend mode, या अन्य पैरामीटर बदल सकें। + +## सामान्य विविधताएँ और किनारे के मामले + +| स्थिति | अनुशंसित संशोधन | +|-----------|-------------------| +| **Multiple pages** | `pdfDocument.Pages` पर लूप करें और प्रत्येक पृष्ठ के लिए डिक्शनरी इन्सर्शन दोहराएँ जिसे आप संशोधित करना चाहते हैं। | +| **No existing ExtGState entry** | `resourcesEditor["ExtGState"]` स्वचालित रूप से एक खाली डिक्शनरी बनाता है यदि वह मौजूद नहीं है। अतिरिक्त कोड की आवश्यकता नहीं है। | +| **Different graphics‑state name** | `"GS0"` को ऐसे नाम से बदलें जो आपके नामकरण मानक से मेल खाता हो, उदाहरण के लिए `"MyTransparentState"`। | +| **Adding only an empty state** | `parameters` एरे और `foreach` लूप को छोड़ दें; डिक्शनरी खाली ही रहेगी। | +| **Working with encrypted PDFs** | रिसोर्सेज़ को एडिट करने से पहले `new Document(path, password)` बनाते समय पासवर्ड प्रदान करें। | + +## परिणाम की पुष्टि करना + +आप PDF को एक लो‑लेवल व्यूअर जैसे **PDF‑Tron** या **iText Sharp** से निरीक्षण करके पुष्टि कर सकते हैं कि graphics state जोड़ा गया है। इस तरह की एंट्री देखें: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +यदि एंट्री दिखाई देती है, तो **खाली ग्राफ़िक्स स्टेट बनाएं** ऑपरेशन सफल रहा। + +## निष्कर्ष + +अब आप जानते हैं कि C# और Aspose.Pdf का उपयोग करके PDF में **खाली ग्राफ़िक्स स्टेट बनाएं**। ट्यूटोरियल ने हर चरण को कवर किया—दस्तावेज़ लोड करने से लेकर `ExtGState` डिक्शनरी को एडिट करने और परिणाम सहेजने तक—और प्रत्येक कार्रवाई के पीछे का तर्क समझाया। + +* नए graphics state को कंटेंट स्ट्रीम्स (`gs /GS0`) में उपयोग करें। +* अतिरिक्त कुंजियों जैसे `/SM` (stroke adjustment) या `/OPM` (overprint mode) के साथ प्रयोग करें। +* इसी तकनीक को अन्य रिसोर्स टाइप्स जैसे `/XObject` या `/ColorSpace` पर लागू करें। + +हैप्पी PDF हैकिंग, और स्वतंत्र रूप से अन्य **Aspose PDF graphics state** परिदृश्यों जैसे डायनामिक opacity परिवर्तन या कस्टम ब्लेंड मोड्स का अन्वेषण करें! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं ताकि आप अतिरिक्त API फीचर्स में निपुण हो सकें और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों का अन्वेषण कर सकें। + +- [Aspose.PDF for .NET के साथ PDFs में डैश्ड लाइन्स कैसे बनाएं: एक चरण‑दर‑चरण गाइड](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Aspose.PDF .NET के साथ PDFs से ग्राफ़िक्स कैसे हटाएं: एक पूर्ण गाइड](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [Aspose.PDF for .NET के साथ PDFs में रेक्टैंगल्स कैसे बनाएं और भरें: एक चरण‑दर‑चरण गाइड](/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/programming-with-operators/_index.md b/pdf/hongkong/net/programming-with-operators/_index.md index 855a4ca86a..841370d556 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 中建立空的圖形狀態](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) |本指南說明如何使用 Aspose.PDF for .NET 及 C# 在 PDF 中建立空的圖形狀態,以便進一步自訂繪圖操作。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/hongkong/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/hongkong/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..7463afe9be --- /dev/null +++ b/pdf/hongkong/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-08-17 +description: 使用 C# 與 Aspose.Pdf 在 PDF 中建立空的圖形狀態。請遵循此逐步指南安全地編輯 ExtGState 資源。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: zh-hant +lastmod: 2026-08-17 +og_description: 使用 C# 在 PDF 中建立空的圖形狀態。本教學示範如何使用 Aspose.Pdf 編輯 ExtGState 資源,以實現可靠的 + PDF 修改。 +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: 使用 C# 在 PDF 中建立空的圖形狀態 – 逐步指南 +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: 如何使用 C# 在 PDF 中建立空的圖形狀態 +url: /zh-hant/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 PDF 中使用 C# 建立空白圖形狀態 + +如果您需要在 PDF 中 **建立空的圖形狀態**,本指南會向您展示如何使用 C# 和 Aspose.Pdf 完成此操作。您將看到一個完整、可執行的範例,該範例會在頁面的 ExtGState 字典中新增一個條目,而不會影響現有內容。 + +在 PDF 中使用圖形狀態是常見需求,特別是當您想要在每個物件層面控制透明度、混合模式或其他渲染參數時。以下程式碼示範了建議的做法,說明每一步的重要性,並涵蓋您可能遇到的典型變化。 + +## 前置條件 + +* .NET 6.0 或更新版本(此範例亦可在 .NET Core 上編譯)。 +* Aspose.Pdf for .NET 授權(或暫時的評估金鑰)。 +* 包含您想要修改的 `input.pdf` 檔案的資料夾。 +* 具備基本的 C# 語法與 PDF 概念(如資源字典)的熟悉度。 + +## 第一步:設定專案並匯入命名空間 + +建立一個新的主控台應用程式,或將程式碼整合至現有專案中。加入 Aspose.Pdf NuGet 套件: + +```bash +dotnet add package Aspose.Pdf +``` + +接著匯入所需的命名空間: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +這些匯入讓您可以存取 `Document`、`DictionaryEditor` 以及建立 **空的圖形狀態** 條目所需的 PDF 原始類別。 + +## 第二步:定義存放 PDF 檔案的資料夾 + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +將路徑替換為您自己的 PDF 檔案所在位置。將目錄存於變數中可提升程式碼的可重用性與測試便利性。 + +## 第三步:載入來源 PDF 文件 + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +在 `using` 陳述式內開啟文件,可確保在儲存變更後自動釋放檔案句柄。 + +## 第四步:存取第一頁及其 Resources 字典 + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` 取得第一頁(PDF 頁碼從 1 開始)。 +* `DictionaryEditor` 提供便利的方式來讀取與修改 PDF 字典。 +* `ExtGState` 條目保存該頁面的所有圖形狀態物件。若鍵不存在,Aspose.Pdf 會自動建立空字典。 + +## 第五步:建立新的空白圖形狀態字典 + +您新增的圖形狀態可以是空的,或預先填入如不透明度 (`CA`, `ca`) 或混合模式 (`BM`) 等參數。在本教學中,我們建立一個 **空的圖形狀態**,然後設定少數典型值,以說明字典的運作方式。 + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` 建立一個乾淨的容器,您可以在其中填入任何圖形狀態鍵。 +* 加入 `CA`、`ca` 與 `BM` 為可選項目;若真的需要空狀態,可省略它們。程式碼示範了在之後決定控制渲染時如何加入條目。 + +## 第六步:將新圖形狀態插入 ExtGState 字典 + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +將條目命名為 `"GS0"` 符合以 “GS” 為前綴的常見圖形狀態命名慣例。您可以選擇任何不與現有鍵衝突的有效 PDF 名稱。 + +## 第七步:儲存已修改的 PDF 文件 + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +`Save` 呼叫會將更新後的檔案寫入 `output.pdf`。在 PDF 檢視器中開啟此檔案即可確認新圖形狀態已存在;之後您可以在內容串流中使用 `gs` 運算子來參考它。 + +### 完整程式碼清單 + +將所有步驟整合起來,完整程式如下: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +執行程式會印出確認訊息,並產生包含新加入圖形狀態的 `output.pdf`。 + +## 為何此方法最佳 + +* **直接編輯字典** – 使用 `DictionaryEditor` 可避免必須解析整個內容串流。您只會修改關心的資源。 +* **具型別的 PDF 原始類別** – `CosPdfNumber`、`CosPdfName` 與 `CosPdfDictionary` 確保產生的 PDF 符合 PDF 1.7 規範。 +* **安全性** – `using` 區塊會釋放 `Document` 物件,防止檔案鎖定導致後續建置受損。 +* **可擴充性** – 一旦空的圖形狀態存在,您即可從任何內容運算子(`gs`)引用它,以變更選取繪圖指令的透明度、混合模式或其他參數。 + +## 常見變化與邊緣案例 + +| 情況 | 建議調整 | +|-----------|-------------------| +| **多頁面** | 對 `pdfDocument.Pages` 進行迴圈,並在每個需要修改的頁面重複插入字典的動作。 | +| **不存在 ExtGState 條目** | `resourcesEditor["ExtGState"]` 若不存在會自動建立空字典。無需額外程式碼。 | +| **不同的圖形狀態名稱** | 將 `"GS0"` 替換為符合您命名慣例的名稱,例如 `"MyTransparentState"`。 | +| **僅加入空狀態** | 省略 `parameters` 陣列與 `foreach` 迴圈;字典將保持空白。 | +| **處理加密 PDF** | 在建立 `new Document(path, password)` 時提供密碼,然後再編輯資源。 | + +## 驗證結果 + +您可以使用低階檢視器(如 **PDF‑Tron** 或 **iText Sharp**)檢查 PDF,以驗證圖形狀態是否已加入。尋找類似以下的條目: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +若出現該條目,表示 **建立空的圖形狀態** 操作成功。 + +## 結論 + +現在您已了解如何使用 C# 與 Aspose.Pdf 在 PDF 中 **建立空的圖形狀態**。本教學涵蓋了每一步——從載入文件、編輯 `ExtGState` 字典到儲存結果——同時說明了每個動作背後的原理。 + +從此您可以: + +* 在內容串流中使用新的圖形狀態(`gs /GS0`)。 +* 嘗試額外的鍵值,如 `/SM`(筆畫調整)或 `/OPM`(覆蓋模式)。 +* 將相同技巧套用於其他資源類型,如 `/XObject` 或 `/ColorSpace`。 + +祝您 PDF 開發順利,並隨時探索其他 **Aspose PDF 圖形狀態** 的情境,例如動態不透明度變化或自訂混合模式! + +## 接下來該學什麼? + +以下教學涵蓋與本指南密切相關的主題,建立在所示技巧之上。每個資源皆包含完整可執行的程式碼範例與逐步說明,協助您精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何使用 Aspose.PDF for .NET 在 PDF 中建立虛線: 步驟指南](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [如何使用 Aspose.PDF .NET 移除 PDF 中的圖形: 完整指南](/pdf/english/net/images-graphics/remove-graphics-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/hungarian/net/programming-with-operators/_index.md b/pdf/hungarian/net/programming-with-operators/_index.md index 27868b3575..03846813b9 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 grafikus állapot létrehozása PDF-ben C#-val](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Ismerd meg, hogyan hozhatsz létre üres grafikus állapotot PDF-ben C# használatával az Aspose.PDF for .NET segítségével. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/hungarian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/hungarian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..408bea62e2 --- /dev/null +++ b/pdf/hungarian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-08-17 +description: Üres grafikus állapot létrehozása PDF-ben C# és Aspose.Pdf használatával. + Kövesse ezt a lépésről‑lépésre útmutatót az ExtGState erőforrások biztonságos szerkesztéséhez. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: hu +lastmod: 2026-08-17 +og_description: Üres grafikai állapot létrehozása PDF-ben C# használatával. Ez az + útmutató bemutatja, hogyan szerkeszthetőek az ExtGState erőforrások az Aspose.Pdf + segítségével a megbízható PDF módosításokhoz. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Üres grafikai állapot létrehozása PDF-ben C#‑val – lépésről lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Üres grafikai állapot létrehozása PDF-ben C#‑val +url: /hu/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan hozhatunk létre üres grafikai állapotot PDF-ben C#‑vel + +Ha **üres grafikai állapotot** kell létrehoznod egy PDF‑ben, ez az útmutató pontosan megmutatja, hogyan teheted ezt meg C#‑vel és az Aspose.Pdf‑vel. Egy teljes, futtatható példát láthatsz, amely egy új bejegyzést ad a lap ExtGState szótárához anélkül, hogy a meglévő tartalmat befolyásolná. + +A PDF grafikai állapotok kezelése gyakori igény, ha átlátszóságot, keverési módokat vagy egyéb renderelési paramétereket szeretnél vezérelni objektumonként. Az alábbi kód bemutatja az ajánlott megközelítést, elmagyarázza, miért fontos minden lépés, és kitér a tipikus variációkra, amelyekkel találkozhatsz. + +## Előfeltételek + +Mielőtt elkezdenéd, győződj meg róla, hogy a következők rendelkezésre állnak: + +* .NET 6.0 vagy újabb (a minta .NET Core‑ral is lefordítható). +* Aspose.Pdf for .NET licenc (vagy ideiglenes értékelő kulcs). +* Egy mappa, amely tartalmaz egy módosítani kívánt `input.pdf` fájlt. +* Alapvető ismeretek a C# szintaxisról és a PDF‑koncepciókról, például a resources szótárakról. + +## 1. lépés: A projekt beállítása és a névterek importálása + +Hozz létre egy új konzolos alkalmazást, vagy integráld a kódot egy meglévő projektbe. Add hozzá az Aspose.Pdf NuGet csomagot: + +```bash +dotnet add package Aspose.Pdf +``` + +Ezután importáld a szükséges névtereket: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Ezek az importok hozzáférést biztosítanak a `Document`, `DictionaryEditor` és a PDF primitív osztályokhoz, amelyekre a **üres grafikai állapot** bejegyzések létrehozásához szükség van. + +## 2. lépés: A PDF fájlokat tartalmazó mappa meghatározása + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Cseréld le az útvonalat a saját PDF fájljaid helyére. A könyvtár változóban való tárolása újrahasználhatóvá és könnyebben tesztelhetővé teszi a kódot. + +## 3. lépés: A forrás PDF dokumentum betöltése + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +A dokumentum `using` blokkban történő megnyitása biztosítja, hogy a fájlkezelő automatikusan felszabaduljon a mentés után. + +## 4. lépés: Az első oldal és a Resources szótár elérése + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` visszaadja az első oldalt (a PDF oldalszámozás 1‑től indul). +* A `DictionaryEditor` kényelmes módot kínál a PDF szótárak olvasására és módosítására. +* Az `ExtGState` bejegyzés tartalmazza az oldal összes grafikai‑állapot objektumát. Ha a kulcs nem létezik, az Aspose.Pdf automatikusan létrehoz egy üres szótárat. + +## 5. lépés: Új üres grafikai‑állapot szótár felépítése + +A hozzáadott grafikai állapot lehet üres vagy előre kitöltött olyan paraméterekkel, mint az átlátszóság (`CA`, `ca`) vagy a keverési mód (`BM`). Ebben az útmutatóban **üres grafikai állapotot** hozunk létre, majd néhány tipikus értéket állítunk be, hogy bemutassuk a szótár működését. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* A `CosPdfDictionary.CreateEmptyDictionary` egy tiszta tárolót hoz létre, amelyet bármilyen grafikai‑állapot kulccsal feltölthetsz. +* A `CA`, `ca` és `BM` hozzáadása opcionális; elhagyhatod őket, ha valóban üres állapotra van szükséged. A kód megmutatja, hogyan lehet bejegyzéseket hozzáadni, ha később a renderelést szeretnéd szabályozni. + +## 6. lépés: Az új grafikai állapot beszúrása az ExtGState szótárba + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Az `"GS0"` név használata a grafikai‑állapot nevek “GS” előtaggal való ellátásának általános konvencióját követi. Bármilyen érvényes PDF nevet választhatsz, amely nem ütközik a meglévő kulcsokkal. + +## 7. lépés: A módosított PDF dokumentum mentése + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +A `Save` hívás az `output.pdf` fájlba írja az frissített tartalmat. A fájl PDF‑nézőben történő megnyitása megerősíti, hogy az új grafikai állapot létezik; később a `gs` operátorral hivatkozhatsz rá a tartalmi áramokban. + +### Teljes forráskód + +Mindent összevonva a teljes program így néz ki: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +A program futtatása egy megerősítő üzenetet ír ki, és létrehozza az `output.pdf` fájlt az újonnan hozzáadott grafikai állapottal. + +## Miért ez a legjobb megközelítés + +* **Közvetlen szótárszerkesztés** – A `DictionaryEditor` használata elkerüli a teljes tartalmi áram elemzését. Csak a számodra fontos erőforrásokat módosítod. +* **Tipizált PDF primitívek** – A `CosPdfNumber`, `CosPdfName` és `CosPdfDictionary` garantálja, hogy a generált PDF megfeleljen a PDF 1.7 specifikációnak. +* **Biztonság** – A `using` blokk elpusztítja a `Document` objektumot, megakadályozva a fájlzárolásokat, amelyek a későbbi buildeket korruptálhatnák. +* **Bővíthetőség** – Miután az üres grafikai állapot létezik, bármely tartalmi operátor (`gs`) segítségével hivatkozhatsz rá, hogy átlátszóságot, keverési módot vagy egyéb paramétereket állíts be a kiválasztott rajzolási parancsokhoz. + +## Gyakori variációk és szélsőséges esetek + +| Helyzet | Ajánlott módosítás | +|-----------|-------------------| +| **Több oldal** | Iterálj a `pdfDocument.Pages` elemein, és ismételd meg a szótárbeszúrást minden módosítani kívánt oldalon. | +| **Nincs meglévő ExtGState bejegyzés** | A `resourcesEditor["ExtGState"]` automatikusan létrehoz egy üres szótárat, ha az nem létezik. Nem szükséges extra kód. | +| **Eltérő grafikai‑állapot név** | Cseréld le a `"GS0"`-t egy saját konvenciódnak megfelelő névre, például `"MyTransparentState"`‑re. | +| **Csak egy üres állapot hozzáadása** | Hagyd ki a `parameters` tömböt és a `foreach` ciklust; a szótár üres marad. | +| **Titkosított PDF‑ek kezelése** | Add meg a jelszót a `new Document(path, password)` konstruktorban, mielőtt a resources‑t szerkesztenéd. | + +## Az eredmény ellenőrzése + +Ellenőrizheted, hogy a grafikai állapot hozzá lett-e adva, ha alacsony szintű nézővel, például **PDF‑Tron** vagy **iText Sharp** segítségével nézed meg a PDF‑et. Keresd a következőhöz hasonló bejegyzést: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Ha a bejegyzés megjelenik, a **üres grafikai állapot létrehozása** sikeres volt. + +## Összegzés + +Most már tudod, hogyan **hozz létre üres grafikai állapotot** egy PDF‑ben C#‑vel és az Aspose.Pdf‑vel. Az útmutató minden lépést lefedett – a dokumentum betöltésétől az `ExtGState` szótár szerkesztéséig és a mentésig – miközben megmagyarázta az egyes műveletek indokait. + +Innen tovább: + +* Használd az új grafikai állapotot a tartalmi áramokban (`gs /GS0`). +* Kísérletezz további kulcsokkal, például `/SM` (stroke adjustment) vagy `/OPM` (overprint mode). +* Alkalmazd ugyanazt a technikát más erőforrás típusokra, mint a `/XObject` vagy a `/ColorSpace`. + +Boldog PDF‑hackelést, és bátran fedezd fel a további **Aspose PDF grafikai állapot** szcenáriókat, például dinamikus átlátszóság‑változtatásokat vagy egyedi keverési módokat! + +## Mit tanulj meg legközelebb? + +A következő oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan hozzunk létre szaggatott vonalakat PDF‑ekben az Aspose.PDF for .NET‑vel: Lépésről‑lépésre útmutató](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Hogyan távolítsunk el grafikákat PDF‑ekből az Aspose.PDF .NET‑vel: Teljes útmutató](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [Hogyan hozzunk létre és töltsünk ki téglalapokat PDF‑ekben az Aspose.PDF for .NET‑vel: Lépésről‑lépésre útmutató](/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/programming-with-operators/_index.md b/pdf/indonesian/net/programming-with-operators/_index.md index 0539c962ff..17ceffd6a3 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. | +| [Cara membuat keadaan grafik kosong dalam PDF dengan C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Panduan langkah demi langkah untuk membuat state grafik kosong dalam PDF menggunakan Aspose.PDF untuk .NET dengan C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/indonesian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/indonesian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..981951c831 --- /dev/null +++ b/pdf/indonesian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-08-17 +description: Buat keadaan grafik kosong dalam PDF menggunakan C# dan Aspose.Pdf. Ikuti + panduan langkah demi langkah ini untuk mengedit sumber daya ExtGState dengan aman. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: id +lastmod: 2026-08-17 +og_description: Buat keadaan grafik kosong dalam PDF menggunakan C#. Tutorial ini + menunjukkan cara mengedit sumber daya ExtGState dengan Aspose.Pdf untuk modifikasi + PDF yang dapat diandalkan. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Buat keadaan grafik kosong di PDF dengan C# – panduan langkah demi langkah +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Cara membuat status grafis kosong dalam PDF dengan C# +url: /id/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara membuat graphics state kosong dalam PDF dengan C# + +Jika Anda perlu **membuat graphics state kosong** dalam PDF, panduan ini menunjukkan secara tepat cara melakukannya dengan C# dan Aspose.Pdf. Anda akan melihat contoh lengkap yang dapat dijalankan yang menambahkan entri baru ke kamus ExtGState halaman tanpa memengaruhi konten yang ada. + +Bekerja dengan graphics state PDF adalah kebutuhan umum ketika Anda ingin mengontrol transparansi, mode pencampuran, atau parameter rendering lainnya secara per‑objek. Kode di bawah ini mendemonstrasikan pendekatan yang direkomendasikan, menjelaskan mengapa setiap langkah penting, dan mencakup variasi tipikal yang mungkin Anda temui. + +## Prasyarat + +Sebelum memulai, pastikan Anda memiliki: + +* .NET 6.0 atau yang lebih baru (contoh dapat dikompilasi dengan .NET Core juga). +* Lisensi Aspose.Pdf untuk .NET (atau kunci evaluasi sementara). +* Folder yang berisi file `input.pdf` yang ingin Anda modifikasi. +* Pengetahuan dasar tentang sintaks C# dan konsep PDF seperti kamus sumber daya. + +## Langkah 1: Siapkan proyek dan impor namespace + +Buat aplikasi konsol baru atau integrasikan kode ke dalam proyek yang sudah ada. Tambahkan paket NuGet Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Kemudian impor namespace yang diperlukan: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Impor ini memberi Anda akses ke kelas `Document`, `DictionaryEditor`, dan primitif PDF yang dibutuhkan untuk **membuat graphics state kosong**. + +## Langkah 2: Tentukan folder yang berisi file PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Ganti path dengan lokasi file PDF Anda sendiri. Menyimpan direktori dalam variabel membuat kode dapat digunakan kembali dan lebih mudah diuji. + +## Langkah 3: Muat dokumen PDF sumber + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Membuka dokumen di dalam pernyataan `using` memastikan handle file dilepaskan secara otomatis setelah Anda menyimpan perubahan. + +## Langkah 4: Akses halaman pertama dan kamus Resources‑nya + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` mengambil halaman pertama (nomor halaman PDF dimulai dari 1). +* `DictionaryEditor` menyediakan cara yang nyaman untuk membaca dan memodifikasi kamus PDF. +* Entri `ExtGState` menyimpan semua objek graphics‑state untuk halaman tersebut. Jika kunci tidak ada, Aspose.Pdf secara otomatis membuat kamus kosong. + +## Langkah 5: Bangun kamus graphics‑state kosong baru + +Graphics state yang Anda tambahkan dapat kosong atau sudah berisi parameter seperti opacity (`CA`, `ca`) atau blend mode (`BM`). Dalam tutorial ini kami membuat **graphics state kosong** dan kemudian menetapkan beberapa nilai tipikal untuk mengilustrasikan cara kerja kamus. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` membuat wadah bersih yang dapat Anda isi dengan kunci graphics‑state apa pun. +* Menambahkan `CA`, `ca`, dan `BM` bersifat opsional; Anda dapat menghilangkannya jika benar‑benar membutuhkan state kosong. Kode ini menunjukkan cara menambahkan entri ketika Anda kemudian memutuskan untuk mengontrol rendering. + +## Langkah 6: Sisipkan graphics state baru ke dalam kamus ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Menamai entri `"GS0"` mengikuti konvensi umum memberi awalan “GS” pada nama graphics‑state. Anda dapat memilih nama PDF yang valid asalkan tidak bentrok dengan kunci yang sudah ada. + +## Langkah 7: Simpan dokumen PDF yang telah dimodifikasi + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +Pemanggilan `Save` menulis file yang telah diperbarui ke `output.pdf`. Membuka file ini di penampil PDF mengonfirmasi bahwa graphics state baru ada; Anda dapat merujuknya nanti dengan operator `gs` dalam aliran konten. + +### Daftar sumber lengkap + +Menggabungkan semua bagian, program lengkapnya terlihat seperti ini: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Menjalankan program mencetak baris konfirmasi dan menghasilkan `output.pdf` dengan graphics state yang baru ditambahkan. + +## Mengapa pendekatan ini paling efektif + +* **Pengeditan kamus langsung** – Menggunakan `DictionaryEditor` menghindari kebutuhan untuk mengurai seluruh aliran konten. Anda hanya memodifikasi sumber daya yang Anda perlukan. +* **Primtif PDF bertipe** – `CosPdfNumber`, `CosPdfName`, dan `CosPdfDictionary` menjamin PDF yang dihasilkan mematuhi spesifikasi PDF 1.7. +* **Keamanan** – Blok `using` membuang objek `Document`, mencegah penguncian file yang dapat merusak build selanjutnya. +* **Ekstensibilitas** – Setelah graphics state kosong ada, Anda dapat merujuknya dari operator konten mana pun (`gs`) untuk mengubah opacity, blend mode, atau parameter lain pada perintah gambar yang dipilih. + +## Variasi umum dan kasus tepi + +| Situasi | Penyesuaian yang disarankan | +|-----------|-------------------| +| **Beberapa halaman** | Lakukan loop pada `pdfDocument.Pages` dan ulangi penyisipan kamus untuk setiap halaman yang perlu Anda modifikasi. | +| **Tidak ada entri ExtGState yang ada** | `resourcesEditor["ExtGState"]` secara otomatis membuat kamus kosong jika belum ada. Tidak diperlukan kode tambahan. | +| **Nama graphics‑state yang berbeda** | Ganti `"GS0"` dengan nama yang sesuai konvensi penamaan Anda, misalnya `"MyTransparentState"`. | +| **Menambahkan hanya state kosong** | Hapus array `parameters` dan loop `foreach`; kamus akan tetap kosong. | +| **Bekerja dengan PDF terenkripsi** | Berikan password saat membuat `new Document(path, password)` sebelum mengedit sumber daya. | + +## Memverifikasi hasil + +Anda dapat memverifikasi bahwa graphics state telah ditambahkan dengan memeriksa PDF menggunakan penampil tingkat‑rendah seperti **PDF‑Tron** atau **iText Sharp**. Cari entri serupa dengan: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Jika entri muncul, operasi **create empty graphics state** berhasil. + +## Kesimpulan + +Anda kini tahu cara **membuat graphics state kosong** dalam PDF menggunakan C# dan Aspose.Pdf. Tutorial ini mencakup setiap langkah—dari memuat dokumen hingga mengedit kamus `ExtGState` dan menyimpan hasilnya—serta menjelaskan alasan di balik setiap tindakan. + +Dari sini Anda dapat: + +* Menggunakan graphics state baru dalam aliran konten (`gs /GS0`). +* Bereksperimen dengan kunci tambahan seperti `/SM` (penyesuaian goresan) atau `/OPM` (mode overprint). +* Menerapkan teknik yang sama pada tipe sumber daya lain seperti `/XObject` atau `/ColorSpace`. + +Selamat bereksperimen dengan PDF, dan jangan ragu menjelajahi skenario **Aspose PDF graphics state** lainnya seperti perubahan opacity dinamis atau blend mode khusus! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya 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 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/) +- [Cara Menghapus Grafik dari PDF Menggunakan Aspose.PDF .NET: Panduan Lengkap](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [Membuat & Mengisi 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/programming-with-operators/_index.md b/pdf/italian/net/programming-with-operators/_index.md index 0bc8780b31..cd43d20274 100644 --- a/pdf/italian/net/programming-with-operators/_index.md +++ b/pdf/italian/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ 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. | +| [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. | +| [Come creare uno stato grafico vuoto in un PDF con C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Scopri come creare uno stato grafico vuoto in un PDF usando Aspose.PDF per .NET con C# in questa guida passo passo. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/italian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/italian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..2de217cb08 --- /dev/null +++ b/pdf/italian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-08-17 +description: Crea uno stato grafico vuoto in un PDF usando C# e Aspose.Pdf. Segui + questa guida passo‑passo per modificare in modo sicuro le risorse ExtGState. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: it +lastmod: 2026-08-17 +og_description: Crea uno stato grafico vuoto in un PDF usando C#. Questo tutorial + mostra come modificare le risorse ExtGState con Aspose.Pdf per modifiche PDF affidabili. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Crea uno stato grafico vuoto in PDF con C# – guida passo‑a‑passo +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Come creare uno stato grafico vuoto in un PDF con C# +url: /it/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come creare uno stato grafico vuoto in un PDF con C# + +Se devi **creare uno stato grafico vuoto** in un PDF, questa guida ti mostra esattamente come farlo con C# e Aspose.Pdf. Vedrai un esempio completo, eseguibile, che aggiunge una nuova voce al dizionario ExtGState della pagina senza influire sul contenuto esistente. + +Lavorare con gli stati grafici PDF è una necessità comune quando vuoi controllare trasparenza, modalità di fusione o altri parametri di rendering su base per‑oggetto. Il codice qui sotto dimostra l'approccio consigliato, spiega perché ogni passaggio è importante e copre le variazioni tipiche che potresti incontrare. + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +* .NET 6.0 o successivo (il campione compila anche con .NET Core). +* Una licenza Aspose.Pdf per .NET (o una chiave di valutazione temporanea). +* Una cartella che contiene un file `input.pdf` che desideri modificare. +* Familiarità di base con la sintassi C# e i concetti PDF come i dizionari delle risorse. + +## Passo 1: Configura il progetto e importa i namespace + +Crea una nuova applicazione console o integra il codice in un progetto esistente. Aggiungi il pacchetto NuGet Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Quindi importa i namespace richiesti: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Queste importazioni ti danno accesso alle classi `Document`, `DictionaryEditor` e alle primitive PDF necessarie per **creare uno stato grafico vuoto**. + +## Passo 2: Definisci la cartella che contiene i file PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Sostituisci il percorso con la posizione dei tuoi file PDF. Tenere la directory in una variabile rende il codice riutilizzabile e più facile da testare. + +## Passo 3: Carica il documento PDF di origine + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Aprire il documento all'interno di un'istruzione `using` garantisce che il handle del file venga rilasciato automaticamente dopo aver salvato le modifiche. + +## Passo 4: Accedi alla prima pagina e al suo dizionario Resources + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` recupera la prima pagina (i numeri di pagina PDF partono da 1). +* `DictionaryEditor` fornisce un modo comodo per leggere e modificare i dizionari PDF. +* La voce `ExtGState` contiene tutti gli oggetti di stato grafico per la pagina. Se la chiave non esiste, Aspose.Pdf crea automaticamente un dizionario vuoto. + +## Passo 5: Costruisci un nuovo dizionario di stato grafico vuoto + +Lo stato grafico che aggiungi può essere vuoto o pre‑popolato con parametri come opacità (`CA`, `ca`) o modalità di fusione (`BM`). In questo tutorial creiamo uno **stato grafico vuoto** e poi impostiamo alcuni valori tipici per illustrare come funziona il dizionario. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` crea un contenitore pulito che puoi riempire con qualsiasi chiave di stato grafico. +* L'aggiunta di `CA`, `ca` e `BM` è opzionale; puoi ometterli se ti serve davvero uno stato vuoto. Il codice mostra come aggiungere voci quando decidi in seguito di controllare il rendering. + +## Passo 6: Inserisci il nuovo stato grafico nel dizionario ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Denominare la voce `"GS0"` segue la convenzione comune di prefissare i nomi degli stati grafici con “GS”. Puoi scegliere qualsiasi nome PDF valido che non confligga con le chiavi esistenti. + +## Passo 7: Salva il documento PDF modificato + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +La chiamata `Save` scrive il file aggiornato in `output.pdf`. Aprire questo file in un visualizzatore PDF conferma che il nuovo stato grafico esiste; potrai riferirti ad esso in seguito con l'operatore `gs` nei flussi di contenuto. + +### Elenco completo del codice sorgente + +Mettendo tutto insieme, il programma completo è così: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Eseguendo il programma verrà stampata una riga di conferma e verrà prodotto `output.pdf` con lo stato grafico appena aggiunto. + +## Perché questo approccio funziona al meglio + +* **Modifica diretta del dizionario** – L'uso di `DictionaryEditor` evita la necessità di analizzare l'intero flusso di contenuto. Modifichi solo le risorse di cui ti interessa. +* **Primitive PDF tipizzate** – `CosPdfNumber`, `CosPdfName` e `CosPdfDictionary` garantiscono che il PDF generato sia conforme alla specifica PDF 1.7. +* **Sicurezza** – Il blocco `using` elimina l'oggetto `Document`, prevenendo blocchi di file che potrebbero corrompere build successive. +* **Estensibilità** – Una volta che lo stato grafico vuoto esiste, puoi riferirti ad esso da qualsiasi operatore di contenuto (`gs`) per cambiare opacità, modalità di fusione o altri parametri per i comandi di disegno selezionati. + +## Variazioni comuni e casi limite + +| Situazione | Modifica consigliata | +|-----------|-------------------| +| **Pagine multiple** | Esegui un ciclo su `pdfDocument.Pages` e ripeti l'inserimento del dizionario per ogni pagina che devi modificare. | +| **Nessuna voce ExtGState esistente** | `resourcesEditor["ExtGState"]` crea automaticamente un dizionario vuoto se non esiste. Non è necessario alcun codice aggiuntivo. | +| **Nome dello stato grafico diverso** | Sostituisci `"GS0"` con un nome che rispetti la tua convenzione, ad esempio `"MyTransparentState"`. | +| **Aggiungere solo uno stato vuoto** | Ometti l'array `parameters` e il ciclo `foreach`; il dizionario rimarrà vuoto. | +| **Lavorare con PDF criptati** | Fornisci la password quando costruisci `new Document(path, password)` prima di modificare le risorse. | + +## Verifica del risultato + +Puoi verificare che lo stato grafico sia stato aggiunto ispezionando il PDF con un visualizzatore a basso livello come **PDF‑Tron** o **iText Sharp**. Cerca una voce simile a: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Se la voce appare, l'operazione **create empty graphics state** è riuscita. + +## Conclusione + +Ora sai come **creare uno stato grafico vuoto** in un PDF usando C# e Aspose.Pdf. Il tutorial ha coperto ogni passaggio—dal caricamento del documento alla modifica del dizionario `ExtGState` e al salvataggio del risultato—spiegando la logica dietro ogni azione. + +Da qui puoi: + +* Usare il nuovo stato grafico nei flussi di contenuto (`gs /GS0`). +* Sperimentare con chiavi aggiuntive come `/SM` (stroke adjustment) o `/OPM` (overprint mode). +* Applicare la stessa tecnica ad altri tipi di risorse come `/XObject` o `/ColorSpace`. + +Buon hacking PDF, e sentiti libero di esplorare altri scenari **Aspose PDF graphics state** come cambiamenti dinamici di opacità o modalità di fusione personalizzate! + +## 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 e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive e a 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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/programming-with-operators/_index.md b/pdf/japanese/net/programming-with-operators/_index.md index fd024c4109..c48c304ae2 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 に空のグラフィックスステートを作成する方法](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) Aspose.PDF for .NET を使用して、C# で PDF の空のグラフィックスステートを作成する手順を解説します。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/japanese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/japanese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..d80883a6e3 --- /dev/null +++ b/pdf/japanese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-08-17 +description: C# と Aspose.Pdf を使用して PDF に空のグラフィックス状態を作成します。このステップバイステップガイドに従って、ExtGState + リソースを安全に編集してください。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: ja +lastmod: 2026-08-17 +og_description: C# を使用して PDF に空のグラフィックス状態を作成します。このチュートリアルでは、信頼性の高い PDF 変更のために Aspose.Pdf + で ExtGState リソースを編集する方法を示します。 +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: C#でPDFに空のグラフィックスステートを作成する – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: C#でPDFの空のグラフィックス状態を作成する方法 +url: /ja/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で PDF に空のグラフィックスステートを作成する方法 + +PDF に **空のグラフィックスステートを作成** する必要がある場合、このガイドでは C# と Aspose.Pdf を使用して正確にその方法を示します。ページの ExtGState 辞書に新しいエントリを追加し、既存のコンテンツに影響を与えない完全な実行可能サンプルをご覧いただけます。 + +PDF のグラフィックスステートを操作することは、透明度、ブレンドモード、またはオブジェクト単位でのその他の描画パラメータを制御したいときに一般的な要件です。以下のコードは推奨されるアプローチを示し、各ステップが重要である理由を説明し、遭遇しうる典型的なバリエーションもカバーします。 + +## 前提条件 + +開始する前に、以下を確認してください。 + +* .NET 6.0 以降(サンプルは .NET Core でもコンパイル可能です)。 +* Aspose.Pdf for .NET のライセンス(または一時的な評価キー)。 +* 修正したい `input.pdf` ファイルが格納されたフォルダー。 +* C# の構文と、リソース辞書などの PDF 概念に関する基本的な知識。 + +## 手順 1: プロジェクトをセットアップし名前空間をインポートする + +新しいコンソール アプリケーションを作成するか、既存プロジェクトにコードを統合します。Aspose.Pdf NuGet パッケージを追加します。 + +```bash +dotnet add package Aspose.Pdf +``` + +次に、必要な名前空間をインポートします。 + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +これらのインポートにより、**空のグラフィックスステート** エントリを作成するために必要な `Document`、`DictionaryEditor`、PDF プリミティブ クラスにアクセスできます。 + +## 手順 2: PDF ファイルが格納されたフォルダーを定義する + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +パスはご自身の PDF ファイルがある場所に置き換えてください。ディレクトリを変数に保持しておくことで、コードの再利用性とテストの容易さが向上します。 + +## 手順 3: ソース PDF ドキュメントを読み込む + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +`using` ステートメント内でドキュメントを開くことで、変更を保存した後にファイルハンドルが自動的に解放されます。 + +## 手順 4: 最初のページとその Resources 辞書にアクセスする + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` は最初のページを取得します(PDF のページ番号は 1 から始まります)。 +* `DictionaryEditor` は PDF 辞書の読み書きを便利に行うためのクラスです。 +* `ExtGState` エントリはページのすべてのグラフィックスステート オブジェクトを保持します。キーが存在しない場合、Aspose.Pdf は自動的に空の辞書を作成します。 + +## 手順 5: 新しい空のグラフィックスステート辞書を構築する + +追加するグラフィックスステートは空でも、透明度 (`CA`, `ca`) やブレンドモード (`BM`) などのパラメータで事前に設定しても構いません。このチュートリアルでは **空のグラフィックスステート** を作成し、辞書の動作を示すためにいくつかの典型的な値を設定します。 + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` は、任意のグラフィックスステート キーを格納できるクリーンなコンテナを作成します。 +* `CA`、`ca`、`BM` の追加はオプションです。真に空のステートが必要な場合は省略できます。コードは、後で描画を制御したいときにエントリを追加する方法を示しています。 + +## 手順 6: 新しいグラフィックスステートを ExtGState 辞書に挿入する + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +エントリ名を `"GS0"` とするのは、グラフィックスステート名に “GS” プレフィックスを付ける一般的な慣例に従っています。既存のキーと衝突しない有効な PDF 名であれば任意の名前を使用できます。 + +## 手順 7: 変更した PDF ドキュメントを保存する + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +`Save` 呼び出しにより、更新されたファイルが `output.pdf` に書き込まれます。このファイルを PDF ビューアで開くと、新しいグラフィックスステートが存在することが確認でき、コンテンツ ストリーム内で `gs` 演算子を使用して後から参照できます。 + +### 完全なソース リスティング + +すべてをまとめると、完全なプログラムは次のようになります。 + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +プログラムを実行すると確認メッセージが出力され、`output.pdf` に新たに追加されたグラフィックスステートが含まれます。 + +## このアプローチが最適な理由 + +* **辞書の直接編集** – `DictionaryEditor` を使用することで、コンテンツ ストリーム全体を解析する必要がなく、必要なリソースだけを変更できます。 +* **型安全な PDF プリミティブ** – `CosPdfNumber`、`CosPdfName`、`CosPdfDictionary` により、生成された PDF が PDF 1.7 仕様に準拠していることが保証されます。 +* **安全性** – `using` ブロックにより `Document` オブジェクトが確実に破棄され、ファイルロックやビルド時の破損を防止します。 +* **拡張性** – 空のグラフィックスステートが作成されたら、任意のコンテンツ 演算子 (`gs`) から参照して、透明度、ブレンドモード、その他のパラメータを選択的に変更できます。 + +## 一般的なバリエーションとエッジケース + +| 状況 | 推奨の調整 | +|-----------|-------------------| +| **複数ページ** | `pdfDocument.Pages` をループし、変更が必要な各ページに対して辞書挿入を繰り返します。 | +| **ExtGState エントリが存在しない** | `resourcesEditor["ExtGState"]` は存在しない場合に自動で空の辞書を作成します。追加コードは不要です。 | +| **異なるグラフィックスステート名** | `"GS0"` を、たとえば `"MyTransparentState"` のように命名規則に合わせた名前に置き換えます。 | +| **空のステートだけを追加** | `parameters` 配列と `foreach` ループを省略すれば、辞書は空のままになります。 | +| **暗号化された PDF の取り扱い** | リソースを編集する前に `new Document(path, password)` でパスワードを渡します。 | + +## 結果の検証 + +**PDF‑Tron** や **iText Sharp** などの低レベルビューアで PDF を調べることで、グラフィックスステートが追加されたか確認できます。以下のようなエントリを探してください。 + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +エントリが表示されていれば、**空のグラフィックスステートを作成** する操作は成功しています。 + +## 結論 + +これで C# と Aspose.Pdf を使用して PDF に **空のグラフィックスステートを作成** する方法が分かりました。チュートリアルでは、ドキュメントの読み込みから `ExtGState` 辞書の編集、結果の保存までのすべての手順をカバーし、各操作の根拠も解説しました。 + +今後は次のことが可能です。 + +* コンテンツ ストリームで新しいグラフィックスステートを使用する(例: `gs /GS0`)。 +* `/SM`(ストローク調整)や `/OPM`(オーバープリントモード)などの追加キーを試す。 +* 同様の手法を `/XObject` や `/ColorSpace` など他のリソースタイプにも適用する。 + +PDF ハッキングを楽しんでください。また、**Aspose PDF グラフィックスステート** に関する他のシナリオ(動的透明度変更やカスタムブレンドモードなど)もぜひ探求してください! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには、ステップバイステップの説明と完全なコード例が含まれており、API の追加機能を習得したり、独自プロジェクトで代替実装を検討したりするのに役立ちます。 + +- [Aspose.PDF for .NET を使用して PDF に破線を作成する方法:ステップバイステップ ガイド](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Aspose.PDF .NET を使用して PDF からグラフィックスを削除する方法:完全ガイド](/pdf/english/net/images-graphics/remove-graphics-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/korean/net/programming-with-operators/_index.md b/pdf/korean/net/programming-with-operators/_index.md index b7f4480864..2cb8ac8ec7 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에서 빈 그래픽 상태 만들기](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Aspose.PDF for .NET을 사용하여 C#에서 빈 그래픽 상태를 생성하는 방법을 단계별로 안내합니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/korean/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/korean/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..0a17a25065 --- /dev/null +++ b/pdf/korean/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-08-17 +description: C#와 Aspose.Pdf를 사용하여 PDF에 빈 그래픽 상태를 생성합니다. 이 단계별 가이드를 따라 ExtGState 리소스를 + 안전하게 편집하세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: ko +lastmod: 2026-08-17 +og_description: C#를 사용하여 PDF에 빈 그래픽 상태를 생성합니다. 이 튜토리얼에서는 신뢰할 수 있는 PDF 수정을 위해 Aspose.Pdf로 + ExtGState 리소스를 편집하는 방법을 보여줍니다. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: C#로 PDF에서 빈 그래픽 상태 만들기 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: C#를 사용하여 PDF에서 빈 그래픽 상태를 만드는 방법 +url: /ko/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#를 사용하여 PDF에서 빈 그래픽 상태 만들기 + +PDF에서 **빈 그래픽 상태 만들기**가 필요하다면, 이 가이드는 C#와 Aspose.Pdf를 사용하여 정확히 수행하는 방법을 보여줍니다. 기존 콘텐츠에 영향을 주지 않고 페이지의 ExtGState 사전에 새 항목을 추가하는 완전한 실행 가능한 예제를 확인할 수 있습니다. + +PDF 그래픽 상태를 다루는 것은 투명도, 블렌드 모드 또는 객체별 렌더링 매개변수를 제어하고자 할 때 흔히 요구되는 작업입니다. 아래 코드는 권장 접근 방식을 시연하고, 각 단계가 왜 중요한지 설명하며, 마주칠 수 있는 일반적인 변형을 다룹니다. + +## 전제 조건 + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +* .NET 6.0 이상 (샘플은 .NET Core에서도 컴파일됩니다). +* Aspose.Pdf for .NET 라이선스(또는 임시 평가 키). +* 수정하려는 `input.pdf` 파일이 들어 있는 폴더. +* C# 구문 및 리소스 사전과 같은 PDF 개념에 대한 기본적인 이해. + +## 1단계: 프로젝트 설정 및 네임스페이스 가져오기 + +새 콘솔 애플리케이션을 만들거나 기존 프로젝트에 코드를 통합합니다. Aspose.Pdf NuGet 패키지를 추가합니다: + +```bash +dotnet add package Aspose.Pdf +``` + +그런 다음 필요한 네임스페이스를 가져옵니다: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +이러한 임포트는 **빈 그래픽 상태 만들기** 항목을 생성하는 데 필요한 `Document`, `DictionaryEditor`, PDF 원시 클래스에 접근할 수 있게 해줍니다. + +## 2단계: PDF 파일이 들어 있는 폴더 정의 + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +경로를 자신의 PDF 파일이 위치한 곳으로 바꾸세요. 디렉터리를 변수에 저장하면 코드를 재사용하고 테스트하기가 쉬워집니다. + +## 3단계: 원본 PDF 문서 로드 + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +`using` 문 안에서 문서를 여는 것은 파일 핸들이 변경 사항을 저장한 뒤 자동으로 해제되도록 보장합니다. + +## 4단계: 첫 번째 페이지와 해당 Resources 사전 접근 + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]`은 첫 번째 페이지를 가져옵니다(PDF 페이지 번호는 1부터 시작). +* `DictionaryEditor`는 PDF 사전을 읽고 수정하는 편리한 방법을 제공합니다. +* `ExtGState` 항목은 페이지의 모든 그래픽‑상태 객체를 보관합니다. 키가 존재하지 않으면 Aspose.Pdf가 자동으로 빈 사전을 생성합니다. + +## 5단계: 새로운 빈 그래픽‑상태 사전 구축 + +추가하는 그래픽 상태는 투명도(`CA`, `ca`)나 블렌드 모드(`BM`)와 같은 매개변수로 미리 채우거나 비워둘 수 있습니다. 이 튜토리얼에서는 **빈 그래픽 상태**를 만든 뒤 몇 가지 일반적인 값을 설정하여 사전이 어떻게 동작하는지 보여줍니다. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary`는 어떤 그래픽‑상태 키든 채울 수 있는 깨끗한 컨테이너를 생성합니다. +* `CA`, `ca`, `BM`을 추가하는 것은 선택 사항이며, 진짜 빈 상태가 필요하면 생략할 수 있습니다. 코드는 나중에 렌더링을 제어하고자 할 때 항목을 추가하는 방법을 보여줍니다. + +## 6단계: 새 그래픽 상태를 ExtGState 사전에 삽입 + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +항목 이름을 `"GS0"`으로 지정하는 것은 그래픽‑상태 이름에 “GS” 접두사를 붙이는 일반적인 관례를 따릅니다. 기존 키와 충돌하지 않는 유효한 PDF 이름이면 어떤 것이든 사용할 수 있습니다. + +## 7단계: 수정된 PDF 문서 저장 + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +`Save` 호출은 업데이트된 파일을 `output.pdf`에 기록합니다. PDF 뷰어에서 이 파일을 열어 새 그래픽 상태가 존재함을 확인할 수 있으며, 이후 콘텐츠 스트림에서 `gs` 연산자를 사용해 참조할 수 있습니다. + +### 전체 소스 목록 + +모든 코드를 합치면 프로그램은 다음과 같습니다: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +프로그램을 실행하면 확인 메시지가 출력되고, 새 그래픽 상태가 추가된 `output.pdf`가 생성됩니다. + +## 이 접근 방식이 최적인 이유 + +* **직접 사전 편집** – `DictionaryEditor`를 사용하면 전체 콘텐츠 스트림을 파싱할 필요 없이 필요한 리소스만 수정합니다. +* **타입이 지정된 PDF 원시 객체** – `CosPdfNumber`, `CosPdfName`, `CosPdfDictionary`는 생성된 PDF가 PDF 1.7 사양을 준수하도록 보장합니다. +* **안전성** – `using` 블록이 `Document` 객체를 자동으로 해제해 파일 잠금으로 인한 빌드 오류를 방지합니다. +* **확장성** – 빈 그래픽 상태가 존재하면 언제든지 `gs` 연산자를 통해 불투명도, 블렌드 모드 또는 기타 매개변수를 선택된 그리기 명령에 적용할 수 있습니다. + +## 일반적인 변형 및 엣지 케이스 + +| 상황 | 권장 수정 | +|-----------|-------------------| +| **다중 페이지** | `pdfDocument.Pages`를 순회하면서 수정이 필요한 각 페이지에 대해 사전 삽입을 반복합니다. | +| **기존 ExtGState 항목 없음** | `resourcesEditor["ExtGState"]`는 항목이 없을 경우 자동으로 빈 사전을 생성합니다. 추가 코드가 필요하지 않습니다. | +| **다른 그래픽‑상태 이름** | `"GS0"`을 여러분의 명명 규칙에 맞는 이름, 예를 들어 `"MyTransparentState"` 로 교체합니다. | +| **빈 상태만 추가** | `parameters` 배열과 `foreach` 루프를 생략하면 사전이 비어 있게 유지됩니다. | +| **암호화된 PDF 작업** | 리소스를 편집하기 전에 `new Document(path, password)` 형태로 비밀번호를 전달합니다. | + +## 결과 확인 + +다음과 같은 저수준 뷰어(예: **PDF‑Tron** 또는 **iText Sharp**)로 PDF를 검사하여 그래픽 상태가 추가됐는지 확인할 수 있습니다. 아래와 같은 항목을 찾아보세요: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +해당 항목이 나타난다면 **빈 그래픽 상태 만들기** 작업이 성공적으로 수행된 것입니다. + +## 결론 + +이제 C#와 Aspose.Pdf를 사용하여 PDF에 **빈 그래픽 상태 만들기** 방법을 알게 되었습니다. 이 튜토리얼은 문서 로드부터 `ExtGState` 사전 편집, 저장까지 모든 단계를 다루었으며 각 행동의 이유도 설명했습니다. + +다음 단계: + +* 새 그래픽 상태를 콘텐츠 스트림(`gs /GS0`)에서 사용합니다. +* `/SM`(스트로크 조정)이나 `/OPM`(오버프린트 모드)과 같은 추가 키를 실험해 봅니다. +* 동일한 기법을 `/XObject` 또는 `/ColorSpace`와 같은 다른 리소스 유형에도 적용합니다. + +PDF 해킹을 즐기시고, 동적 투명도 변경이나 사용자 정의 블렌드 모드와 같은 **Aspose PDF 그래픽 상태** 시나리오도 탐색해 보세요! + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하며, 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Aspose.PDF for .NET을 사용하여 PDF에서 점선 만들기: 단계별 가이드](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Aspose.PDF .NET을 사용하여 PDF에서 그래픽 제거하기: 완전 가이드](/pdf/english/net/images-graphics/remove-graphics-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/programming-with-operators/_index.md b/pdf/polish/net/programming-with-operators/_index.md index 29f5701327..6e32b4c02a 100644 --- a/pdf/polish/net/programming-with-operators/_index.md +++ b/pdf/polish/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ 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. | +| [Jak utworzyć pusty stan graficzny w PDF przy użyciu C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Krok po kroku pokażemy, jak stworzyć pusty stan graficzny w pliku PDF przy użyciu Aspose.PDF dla .NET i języka C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/polish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/polish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..9a4e67e7e2 --- /dev/null +++ b/pdf/polish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2026-08-17 +description: Utwórz pusty stan graficzny w pliku PDF przy użyciu C# i Aspose.Pdf. + Postępuj zgodnie z tym przewodnikiem krok po kroku, aby bezpiecznie edytować zasoby + ExtGState. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: pl +lastmod: 2026-08-17 +og_description: Utwórz pusty stan graficzny w pliku PDF przy użyciu C#. Ten samouczek + pokazuje, jak edytować zasoby ExtGState przy użyciu Aspose.Pdf, aby uzyskać niezawodne + modyfikacje PDF. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Utwórz pusty stan graficzny w PDF przy użyciu C# – przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Jak utworzyć pusty stan graficzny w PDF przy użyciu C# +url: /pl/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak utworzyć pusty stan graficzny w PDF przy użyciu C# + +Jeśli potrzebujesz **utworzyć pusty stan graficzny** w PDF, ten przewodnik pokaże Ci dokładnie, jak to zrobić w C# i Aspose.Pdf. Zobaczysz kompletny, działający przykład, który dodaje nowy wpis do słownika ExtGState strony, nie wpływając na istniejącą zawartość. + +Praca ze stanami graficznymi PDF jest powszechnym wymogiem, gdy chcesz kontrolować przezroczystość, tryby mieszania lub inne parametry renderowania na poziomie pojedynczego obiektu. Poniższy kod demonstruje zalecaną metodę, wyjaśnia, dlaczego każdy krok ma znaczenie, i opisuje typowe warianty, które możesz napotkać. + +## Prerequisites + +Zanim rozpoczniesz, upewnij się, że masz: + +* .NET 6.0 lub nowszy (przykład kompiluje się także z .NET Core). +* Licencję Aspose.Pdf for .NET (lub tymczasowy klucz ewaluacyjny). +* Folder zawierający plik `input.pdf`, który chcesz zmodyfikować. +* Podstawową znajomość składni C# oraz koncepcji PDF, takich jak słowniki zasobów. + +## Step 1: Set up the project and import namespaces + +Utwórz nową aplikację konsolową lub włącz kod do istniejącego projektu. Dodaj pakiet NuGet Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Następnie zaimportuj wymagane przestrzenie nazw: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Te importy dają dostęp do klas `Document`, `DictionaryEditor` oraz prymitywów PDF potrzebnych do **utworzenia pustego stanu graficznego**. + +## Step 2: Define the folder that holds the PDF files + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Zastąp ścieżkę lokalizacją własnych plików PDF. Przechowywanie katalogu w zmiennej sprawia, że kod jest wielokrotnego użytku i łatwiejszy do testowania. + +## Step 3: Load the source PDF document + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Otwieranie dokumentu wewnątrz instrukcji `using` zapewnia automatyczne zwolnienie uchwytu pliku po zapisaniu zmian. + +## Step 4: Access the first page and its Resources dictionary + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` pobiera pierwszą stronę (numery stron PDF zaczynają się od 1). +* `DictionaryEditor` zapewnia wygodny sposób odczytu i modyfikacji słowników PDF. +* Wpis `ExtGState` przechowuje wszystkie obiekty stanu graficznego dla strony. Jeśli klucz nie istnieje, Aspose.Pdf automatycznie tworzy pusty słownik. + +## Step 5: Build a new empty graphics‑state dictionary + +Stan graficzny, który dodajesz, może być pusty lub wstępnie wypełniony parametrami, takimi jak przezroczystość (`CA`, `ca`) czy tryb mieszania (`BM`). W tym tutorialu tworzymy **pusty stan graficzny**, a następnie ustawiamy kilka typowych wartości, aby zilustrować działanie słownika. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` tworzy czysty kontener, który możesz wypełnić dowolnymi kluczami stanu graficznego. +* Dodanie `CA`, `ca` i `BM` jest opcjonalne; możesz je pominąć, jeśli naprawdę potrzebujesz pustego stanu. Kod pokazuje, jak dodać wpisy, gdy później zdecydujesz się kontrolować renderowanie. + +## Step 6: Insert the new graphics state into the ExtGState dictionary + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Nazwanie wpisu `"GS0"` podąża za powszechną konwencją prefiksowania nazw stanów graficznych „GS”. Możesz wybrać dowolną prawidłową nazwę PDF, która nie koliduje z istniejącymi kluczami. + +## Step 7: Save the modified PDF document + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +Wywołanie `Save` zapisuje zaktualizowany plik jako `output.pdf`. Otworzenie tego pliku w przeglądarce PDF potwierdzi, że nowy stan graficzny istnieje; możesz odwołać się do niego później operatorem `gs` w strumieniach zawartości. + +### Full source listing + +Łącząc wszystkie elementy, pełny program wygląda następująco: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Uruchomienie programu wypisuje linię potwierdzającą i tworzy `output.pdf` z nowo dodanym stanem graficznym. + +## Why this approach works best + +* **Direct dictionary editing** – Użycie `DictionaryEditor` eliminuje konieczność parsowania całego strumienia zawartości. Modyfikujesz tylko te zasoby, które Cię interesują. +* **Typed PDF primitives** – `CosPdfNumber`, `CosPdfName` i `CosPdfDictionary` gwarantują, że wygenerowany PDF jest zgodny ze specyfikacją PDF 1.7. +* **Safety** – Blok `using` zwalnia obiekt `Document`, zapobiegając blokadom plików, które mogłyby uszkodzić kolejne kompilacje. +* **Extensibility** – Gdy pusty stan graficzny istnieje, możesz odwołać się do niego z dowolnego operatora zawartości (`gs`), aby zmienić przezroczystość, tryb mieszania lub inne parametry wybranych poleceń rysowania. + +## Common variations and edge cases + +| Situation | Recommended tweak | +|-----------|-------------------| +| **Multiple pages** | Pętla po `pdfDocument.Pages` i powtórzenie wstawiania słownika dla każdej strony, którą chcesz zmodyfikować. | +| **No existing ExtGState entry** | `resourcesEditor["ExtGState"]` automatycznie tworzy pusty słownik, jeśli nie istnieje. Nie wymaga dodatkowego kodu. | +| **Different graphics‑state name** | Zastąp `"GS0"` nazwą pasującą do Twojej konwencji, np. `"MyTransparentState"`. | +| **Adding only an empty state** | Pomiń tablicę `parameters` oraz pętlę `foreach`; słownik pozostanie pusty. | +| **Working with encrypted PDFs** | Podaj hasło przy tworzeniu `new Document(path, password)` przed edycją zasobów. | + +## Verifying the result + +Możesz zweryfikować, że stan graficzny został dodany, przeglądając PDF w narzędziu niskopoziomowym, takim jak **PDF‑Tron** lub **iText Sharp**. Poszukaj wpisu podobnego do: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Jeśli wpis się pojawi, operacja **utworzenia pustego stanu graficznego** zakończyła się sukcesem. + +## Conclusion + +Teraz wiesz, jak **utworzyć pusty stan graficzny** w PDF przy użyciu C# i Aspose.Pdf. Tutorial omówił każdy krok – od załadowania dokumentu, przez edycję słownika `ExtGState`, po zapis wyniku – wyjaśniając przy tym uzasadnienie każdej czynności. + +Od tego momentu możesz: + +* Używać nowego stanu graficznego w strumieniach zawartości (`gs /GS0`). +* Eksperymentować z dodatkowymi kluczami, takimi jak `/SM` (korekta pędzla) lub `/OPM` (tryb nadruku). +* Zastosować tę samą technikę do innych typów zasobów, np. `/XObject` lub `/ColorSpace`. + +Miłego hakowania PDF‑ów i zachęcamy do eksploracji innych scenariuszy **Aspose PDF graphics state**, takich jak dynamiczne zmiany przezroczystości czy własne tryby mieszania! + +## What Should You Learn Next? + +Poniższe tutoriale obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu oraz szczegółowe wyjaśnienia, pomagające opanować dodatkowe funkcje API i poznać alternatywne podejścia w własnych projektach. + +- [Jak utworzyć linie przerywane w PDF przy użyciu Aspose.PDF dla .NET: przewodnik krok po kroku](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Jak usunąć grafikę z PDF przy użyciu Aspose.PDF .NET: kompletny przewodnik](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [Tworzenie i wypełnianie prostokątów w PDF 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/programming-with-operators/_index.md b/pdf/portuguese/net/programming-with-operators/_index.md index ad752bd34d..4a5d3cb50b 100644 --- a/pdf/portuguese/net/programming-with-operators/_index.md +++ b/pdf/portuguese/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ 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. | +| [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. | +| [Como criar um estado gráfico vazio em um PDF com C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Aprenda a criar um estado gráfico vazio em um PDF usando C# e Aspose.PDF. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/portuguese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/portuguese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..d5b294ebbc --- /dev/null +++ b/pdf/portuguese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-08-17 +description: Crie um estado gráfico vazio em um PDF usando C# e Aspose.Pdf. Siga este + guia passo a passo para editar recursos ExtGState com segurança. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: pt +lastmod: 2026-08-17 +og_description: Crie um estado gráfico vazio em um PDF usando C#. Este tutorial mostra + como editar recursos ExtGState com Aspose.Pdf para modificações confiáveis de PDF. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Crie um estado gráfico vazio em PDF com C# – guia passo a passo +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Como criar um estado gráfico vazio em um PDF com C# +url: /pt/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como criar um estado gráfico vazio em um PDF com C# + +Se você precisa **criar um estado gráfico vazio** em um PDF, este guia mostra exatamente como fazer isso com C# e Aspose.Pdf. Você verá um exemplo completo e executável que adiciona uma nova entrada ao dicionário ExtGState da página sem afetar o conteúdo existente. + +Trabalhar com estados gráficos de PDF é uma necessidade comum quando você deseja controlar transparência, modos de mesclagem ou outros parâmetros de renderização por objeto. O código abaixo demonstra a abordagem recomendada, explica por que cada passo é importante e cobre variações típicas que você pode encontrar. + +## Pré‑requisitos + +Antes de começar, certifique‑se de que você tem: + +* .NET 6.0 ou superior (o exemplo também compila com .NET Core). +* Uma licença do Aspose.Pdf for .NET (ou uma chave de avaliação temporária). +* Uma pasta que contenha um arquivo `input.pdf` que você deseja modificar. +* Familiaridade básica com a sintaxe C# e conceitos de PDF, como dicionários de recursos. + +## Etapa 1: Configurar o projeto e importar namespaces + +Crie um novo aplicativo de console ou integre o código em um projeto existente. Adicione o pacote NuGet Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Em seguida, importe os namespaces necessários: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Essas importações dão acesso às classes `Document`, `DictionaryEditor` e aos primitivos PDF necessários para **criar entradas de estado gráfico vazio**. + +## Etapa 2: Definir a pasta que contém os arquivos PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Substitua o caminho pela localização dos seus próprios arquivos PDF. Manter o diretório em uma variável torna o código reutilizável e mais fácil de testar. + +## Etapa 3: Carregar o documento PDF de origem + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Abrir o documento dentro de uma instrução `using` garante que o manipulador de arquivo seja liberado automaticamente após salvar as alterações. + +## Etapa 4: Acessar a primeira página e seu dicionário Resources + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` recupera a primeira página (os números de página PDF começam em 1). +* `DictionaryEditor` fornece uma maneira conveniente de ler e modificar dicionários PDF. +* A entrada `ExtGState` contém todos os objetos de estado gráfico da página. Se a chave não existir, o Aspose.Pdf cria um dicionário vazio automaticamente. + +## Etapa 5: Construir um novo dicionário de estado gráfico vazio + +O estado gráfico que você adiciona pode ser vazio ou pré‑populado com parâmetros como opacidade (`CA`, `ca`) ou modo de mesclagem (`BM`). Neste tutorial criamos um **estado gráfico vazio** e, em seguida, definimos alguns valores típicos para ilustrar como o dicionário funciona. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` cria um contêiner limpo que você pode preencher com quaisquer chaves de estado gráfico. +* Adicionar `CA`, `ca` e `BM` é opcional; você pode omiti‑los se realmente precisar de um estado vazio. O código mostra como adicionar entradas quando decidir controlar a renderização. + +## Etapa 6: Inserir o novo estado gráfico no dicionário ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Nomear a entrada como `"GS0"` segue a convenção comum de prefixar nomes de estado gráfico com “GS”. Você pode escolher qualquer nome PDF válido que não conflite com chaves existentes. + +## Etapa 7: Salvar o documento PDF modificado + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +A chamada `Save` grava o arquivo atualizado em `output.pdf`. Abrir este arquivo em um visualizador de PDF confirma que o novo estado gráfico existe; você pode referenciá‑lo posteriormente com o operador `gs` nos fluxos de conteúdo. + +### Listagem completa do código‑fonte + +Juntando tudo, o programa completo fica assim: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Executar o programa imprime uma linha de confirmação e produz `output.pdf` com o estado gráfico recém‑adicionado. + +## Por que essa abordagem funciona melhor + +* **Edição direta de dicionário** – Usar `DictionaryEditor` evita a necessidade de analisar todo o fluxo de conteúdo. Você modifica apenas os recursos que lhe interessam. +* **Primitivas PDF tipadas** – `CosPdfNumber`, `CosPdfName` e `CosPdfDictionary` garantem que o PDF gerado esteja em conformidade com a especificação PDF 1.7. +* **Segurança** – O bloco `using` descarta o objeto `Document`, prevenindo bloqueios de arquivo que poderiam corromper compilações subsequentes. +* **Extensibilidade** – Uma vez que o estado gráfico vazio exista, você pode referenciá‑lo a partir de qualquer operador de conteúdo (`gs`) para mudar opacidade, modo de mesclagem ou outros parâmetros de comandos de desenho selecionados. + +## Variações comuns e casos de borda + +| Situação | Ajuste recomendado | +|-----------|-------------------| +| **Múltiplas páginas** | Percorra `pdfDocument.Pages` e repita a inserção do dicionário para cada página que precisar modificar. | +| **Nenhuma entrada ExtGState existente** | `resourcesEditor["ExtGState"]` cria automaticamente um dicionário vazio se ele não existir. Nenhum código extra é necessário. | +| **Nome de estado gráfico diferente** | Substitua `"GS0"` por um nome que siga sua convenção, por exemplo, `"MyTransparentState"`. | +| **Adicionar apenas um estado vazio** | Omitir o array `parameters` e o loop `foreach`; o dicionário permanecerá vazio. | +| **Trabalhando com PDFs criptografados** | Forneça a senha ao construir `new Document(path, password)` antes de editar os recursos. | + +## Verificando o resultado + +Você pode confirmar que o estado gráfico foi adicionado inspecionando o PDF com um visualizador de baixo nível como **PDF‑Tron** ou **iText Sharp**. Procure uma entrada semelhante a: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Se a entrada aparecer, a operação **criar estado gráfico vazio** foi bem‑sucedida. + +## Conclusão + +Agora você sabe como **criar um estado gráfico vazio** em um PDF usando C# e Aspose.Pdf. O tutorial cobriu cada passo — desde carregar o documento até editar o dicionário `ExtGState` e salvar o resultado — explicando a lógica por trás de cada ação. + +A partir daqui você pode: + +* Usar o novo estado gráfico em fluxos de conteúdo (`gs /GS0`). +* Experimentar chaves adicionais como `/SM` (ajuste de traço) ou `/OPM` (modo de sobreimpressão). +* Aplicar a mesma técnica a outros tipos de recurso, como `/XObject` ou `/ColorSpace`. + +Boa exploração de PDFs, e sinta‑se à vontade para investigar outros cenários de **estado gráfico Aspose PDF**, como mudanças dinâmicas de opacidade ou modos de mesclagem personalizados! + +## 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 e funcionais 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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/programming-with-operators/_index.md b/pdf/russian/net/programming-with-operators/_index.md index 23208c3db4..969a3c4a8f 100644 --- a/pdf/russian/net/programming-with-operators/_index.md +++ b/pdf/russian/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ | --- | --- | | [Нарисовать 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-файле](./remove-graphics-objects/) Узнайте, как удалить графические объекты из файла PDF с помощью Aspose.PDF для .NET в этом пошаговом руководстве. Упростите свои задачи по обработке PDF. | +| [Как создать пустое графическое состояние в PDF с помощью C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Узнайте, как создать пустое графическое состояние в PDF с использованием Aspose.PDF для .NET и C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/russian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/russian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..44e585fb41 --- /dev/null +++ b/pdf/russian/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-08-17 +description: Создайте пустое графическое состояние в PDF с помощью C# и Aspose.Pdf. + Следуйте этому пошаговому руководству, чтобы безопасно редактировать ресурсы ExtGState. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: ru +lastmod: 2026-08-17 +og_description: Создайте пустое графическое состояние в PDF с помощью C#. Этот учебник + показывает, как редактировать ресурсы ExtGState с помощью Aspose.Pdf для надёжных + модификаций PDF. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Создание пустого графического состояния в PDF с помощью C# – пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Как создать пустое графическое состояние в PDF с помощью C# +url: /ru/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как создать пустое графическое состояние в PDF с помощью C# + +Если вам нужно **создать пустое графическое состояние** в PDF, это руководство покажет, как сделать это с помощью C# и Aspose.Pdf. Вы увидите полностью готовый, исполняемый пример, который добавляет новую запись в словарь ExtGState страницы, не затрагивая существующее содержимое. + +Работа с графическими состояниями PDF часто требуется, когда нужно управлять прозрачностью, режимами наложения или другими параметрами рендеринга для отдельных объектов. Приведённый ниже код демонстрирует рекомендуемый подход, объясняет, почему каждый шаг важен, и охватывает типичные варианты, с которыми вы можете столкнуться. + +## Требования + +Прежде чем начать, убедитесь, что у вас есть: + +* .NET 6.0 или новее (пример также компилируется с .NET Core). +* Лицензия Aspose.Pdf for .NET (или временный оценочный ключ). +* Папка, содержащая файл `input.pdf`, который вы хотите изменить. +* Базовые знания синтаксиса C# и концепций PDF, таких как словари ресурсов. + +## Шаг 1: Настройка проекта и импорт пространств имён + +Создайте новое консольное приложение или интегрируйте код в существующий проект. Добавьте пакет Aspose.Pdf через NuGet: + +```bash +dotnet add package Aspose.Pdf +``` + +Затем импортируйте необходимые пространства имён: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Эти импорты дают доступ к классам `Document`, `DictionaryEditor` и PDF‑примитивам, необходимым для **создания пустого графического состояния**. + +## Шаг 2: Определите папку, в которой находятся PDF‑файлы + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Замените путь на расположение ваших собственных PDF‑файлов. Хранение директории в переменной делает код переиспользуемым и упрощает тестирование. + +## Шаг 3: Загрузите исходный PDF‑документ + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Открытие документа внутри блока `using` гарантирует, что файловый дескриптор будет освобождён автоматически после сохранения изменений. + +## Шаг 4: Получите первую страницу и её словарь Resources + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` возвращает первую страницу (нумерация страниц PDF начинается с 1). +* `DictionaryEditor` предоставляет удобный способ чтения и изменения словарей PDF. +* Запись `ExtGState` содержит все объекты графических состояний для страницы. Если ключ отсутствует, Aspose.Pdf автоматически создаёт пустой словарь. + +## Шаг 5: Создайте новый пустой словарь графического состояния + +Графическое состояние, которое вы добавляете, может быть пустым или предварительно заполненным параметрами, такими как непрозрачность (`CA`, `ca`) или режим наложения (`BM`). В этом руководстве мы создаём **пустое графическое состояние**, а затем задаём несколько типичных значений для демонстрации работы словаря. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` создаёт чистый контейнер, который вы можете заполнить любыми ключами графического состояния. +* Добавление `CA`, `ca` и `BM` необязательно; их можно опустить, если действительно нужен пустой статус. Код показывает, как добавить записи, когда позже понадобится управлять рендерингом. + +## Шаг 6: Вставьте новое графическое состояние в словарь ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Имя записи `"GS0"` следует общепринятой конвенции префикса графических состояний «GS». Вы можете выбрать любое допустимое имя PDF, которое не конфликтует с существующими ключами. + +## Шаг 7: Сохраните изменённый PDF‑документ + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +Вызов `Save` записывает обновлённый файл в `output.pdf`. Открытие этого файла в просмотрщике PDF подтверждает наличие нового графического состояния; позже его можно будет ссылаться оператором `gs` в потоках содержимого. + +### Полный листинг исходного кода + +Объединив всё вместе, получаем полную программу: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Запуск программы выводит строку подтверждения и создаёт `output.pdf` с добавленным графическим состоянием. + +## Почему этот подход работает лучше всего + +* **Прямое редактирование словарей** – Использование `DictionaryEditor` избавляет от необходимости парсить весь поток содержимого. Вы изменяете только те ресурсы, которые вам нужны. +* **Типизированные PDF‑примитивы** – `CosPdfNumber`, `CosPdfName` и `CosPdfDictionary` гарантируют, что сгенерированный PDF соответствует спецификации PDF 1.7. +* **Безопасность** – Блок `using` освобождает объект `Document`, предотвращая блокировки файлов, которые могут повредить последующие сборки. +* **Расширяемость** – Как только пустое графическое состояние существует, вы можете ссылаться на него из любого оператора содержимого (`gs`), меняя непрозрачность, режим наложения или другие параметры для выбранных команд рисования. + +## Общие варианты и граничные случаи + +| Ситуация | Рекомендуемое изменение | +|-----------|-------------------| +| **Несколько страниц** | Выполните цикл по `pdfDocument.Pages` и повторите вставку словаря для каждой страницы, которую нужно изменить. | +| **Отсутствует запись ExtGState** | `resourcesEditor["ExtGState"]` автоматически создаёт пустой словарь, если он не существует. Дополнительный код не требуется. | +| **Другое имя графического состояния** | Замените `"GS0"` на имя, соответствующее вашей конвенции, например, `"MyTransparentState"`. | +| **Добавление только пустого состояния** | Опустите массив `parameters` и цикл `foreach`; словарь останется пустым. | +| **Работа с зашифрованными PDF** | Перед редактированием ресурсов передайте пароль при создании `new Document(path, password)`. | + +## Проверка результата + +Вы можете убедиться, что графическое состояние добавлено, проверив PDF в низкоуровневом просмотрщике, таком как **PDF‑Tron** или **iText Sharp**. Ищите запись, похожую на: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Если запись присутствует, операция **создания пустого графического состояния** выполнена успешно. + +## Заключение + +Теперь вы знаете, как **создать пустое графическое состояние** в PDF с помощью C# и Aspose.Pdf. Руководство охватило каждый шаг — от загрузки документа до редактирования словаря `ExtGState` и сохранения результата, объясняя логику каждого действия. + +Дальше вы можете: + +* Использовать новое графическое состояние в потоках содержимого (`gs /GS0`). +* Поэкспериментировать с дополнительными ключами, такими как `/SM` (коррекция штриха) или `/OPM` (режим наложения). +* Применить тот же приём к другим типам ресурсов, например `/XObject` или `/ColorSpace`. + +Удачной работы с PDF, и не стесняйтесь исследовать другие **сценарии графических состояний Aspose PDF**, такие как динамические изменения непрозрачности или пользовательские режимы наложения! + +## Что вам стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, помогая вам освоить дополнительные возможности 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/remove-graphics-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/spanish/net/programming-with-operators/_index.md b/pdf/spanish/net/programming-with-operators/_index.md index 20ff762b0b..a176ac9f94 100644 --- a/pdf/spanish/net/programming-with-operators/_index.md +++ b/pdf/spanish/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ Los tutoriales "Programación con Operadores" de Aspose.PDF para .NET le guiará | [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. +| [Cómo crear un estado gráfico vacío en un PDF con C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Aprenda a crear un estado gráfico vacío en un PDF usando Aspose.PDF para .NET con C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/spanish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/spanish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..6b12c29d81 --- /dev/null +++ b/pdf/spanish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-08-17 +description: Crea un estado gráfico vacío en un PDF usando C# y Aspose.Pdf. Sigue + esta guía paso a paso para editar los recursos ExtGState de forma segura. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: es +lastmod: 2026-08-17 +og_description: Crear un estado gráfico vacío en un PDF usando C#. Este tutorial muestra + cómo editar los recursos ExtGState con Aspose.Pdf para realizar modificaciones de + PDF fiables. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Crear un estado gráfico vacío en PDF con C# – guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Cómo crear un estado gráfico vacío en un PDF con C# +url: /es/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo crear un estado gráfico vacío en un PDF con C# + +Si necesitas **crear un estado gráfico vacío** en un PDF, esta guía te muestra exactamente cómo hacerlo con C# y Aspose.Pdf. Verás un ejemplo completo y ejecutable que añade una nueva entrada al diccionario ExtGState de la página sin afectar el contenido existente. + +Trabajar con estados gráficos de PDF es un requisito común cuando deseas controlar la transparencia, los modos de fusión u otros parámetros de renderizado por objeto. El código a continuación demuestra el enfoque recomendado, explica por qué cada paso es importante y cubre variaciones típicas que podrías encontrar. + +## Requisitos previos + +Antes de comenzar, asegúrate de tener: + +* .NET 6.0 o posterior (el ejemplo también compila con .NET Core). +* Una licencia de Aspose.Pdf para .NET (o una clave de evaluación temporal). +* Una carpeta que contenga un archivo `input.pdf` que quieras modificar. +* Familiaridad básica con la sintaxis de C# y conceptos de PDF como los diccionarios de recursos. + +## Paso 1: Configurar el proyecto e importar espacios de nombres + +Crea una nueva aplicación de consola o integra el código en un proyecto existente. Añade el paquete NuGet Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Luego importa los espacios de nombres requeridos: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Estas importaciones te dan acceso a las clases `Document`, `DictionaryEditor` y a los primitivos PDF necesarios para **crear un estado gráfico vacío**. + +## Paso 2: Definir la carpeta que contiene los archivos PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Reemplaza la ruta con la ubicación de tus propios archivos PDF. Mantener el directorio en una variable hace que el código sea reutilizable y más fácil de probar. + +## Paso 3: Cargar el documento PDF de origen + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Abrir el documento dentro de una sentencia `using` garantiza que el manejador del archivo se libere automáticamente después de guardar los cambios. + +## Paso 4: Acceder a la primera página y a su diccionario Resources + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` recupera la primera página (los números de página en PDF empiezan en 1). +* `DictionaryEditor` proporciona una forma cómoda de leer y modificar diccionarios PDF. +* La entrada `ExtGState` contiene todos los objetos de estado gráfico de la página. Si la clave no existe, Aspose.Pdf crea automáticamente un diccionario vacío. + +## Paso 5: Construir un nuevo diccionario de estado gráfico vacío + +El estado gráfico que añadas puede estar vacío o pre‑poblado con parámetros como opacidad (`CA`, `ca`) o modo de fusión (`BM`). En este tutorial creamos un **estado gráfico vacío** y luego establecemos algunos valores típicos para ilustrar cómo funciona el diccionario. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` crea un contenedor limpio que puedes rellenar con cualquier clave de estado gráfico. +* Añadir `CA`, `ca` y `BM` es opcional; puedes omitirlos si realmente necesitas un estado vacío. El código muestra cómo agregar entradas cuando luego decidas controlar el renderizado. + +## Paso 6: Insertar el nuevo estado gráfico en el diccionario ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Nombrar la entrada `"GS0"` sigue la convención común de prefijar los nombres de estado gráfico con “GS”. Puedes elegir cualquier nombre PDF válido que no choque con claves existentes. + +## Paso 7: Guardar el documento PDF modificado + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +La llamada `Save` escribe el archivo actualizado en `output.pdf`. Abrir este archivo en un visor de PDF confirma que el nuevo estado gráfico existe; podrás referenciarlo más adelante con el operador `gs` en los flujos de contenido. + +### Listado completo del código fuente + +Uniendo todo, el programa completo se ve así: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Ejecutar el programa muestra una línea de confirmación y genera `output.pdf` con el estado gráfico recién añadido. + +## Por qué este enfoque funciona mejor + +* **Edición directa de diccionarios** – Usar `DictionaryEditor` evita la necesidad de analizar todo el flujo de contenido. Modificas solo los recursos que te interesan. +* **Primitivos PDF tipados** – `CosPdfNumber`, `CosPdfName` y `CosPdfDictionary` garantizan que el PDF generado cumpla con la especificación PDF 1.7. +* **Seguridad** – El bloque `using` dispone del objeto `Document`, evitando bloqueos de archivo que podrían corromper compilaciones posteriores. +* **Extensibilidad** – Una vez que el estado gráfico vacío existe, puedes referenciarlo desde cualquier operador de contenido (`gs`) para cambiar la opacidad, el modo de fusión u otros parámetros de los comandos de dibujo seleccionados. + +## Variaciones comunes y casos límite + +| Situación | Ajuste recomendado | +|-----------|-------------------| +| **Múltiples páginas** | Recorre `pdfDocument.Pages` y repite la inserción del diccionario para cada página que necesites modificar. | +| **No hay entrada ExtGState existente** | `resourcesEditor["ExtGState"]` crea automáticamente un diccionario vacío si no existe. No se requiere código adicional. | +| **Nombre de estado gráfico diferente** | Reemplaza `"GS0"` por un nombre que coincida con tu convención, por ejemplo, `"MyTransparentState"`. | +| **Agregar solo un estado vacío** | Omite el arreglo `parameters` y el bucle `foreach`; el diccionario permanecerá vacío. | +| **Trabajar con PDFs encriptados** | Proporciona la contraseña al construir `new Document(path, password)` antes de editar los recursos. | + +## Verificando el resultado + +Puedes comprobar que el estado gráfico se añadió inspeccionando el PDF con un visor de bajo nivel como **PDF‑Tron** o **iText Sharp**. Busca una entrada similar a: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Si la entrada aparece, la operación **crear un estado gráfico vacío** se realizó con éxito. + +## Conclusión + +Ahora sabes cómo **crear un estado gráfico vacío** en un PDF usando C# y Aspose.Pdf. El tutorial cubrió cada paso—desde cargar el documento hasta editar el diccionario `ExtGState` y guardar el resultado—explicando la lógica detrás de cada acción. + +A partir de aquí puedes: + +* Usar el nuevo estado gráfico en flujos de contenido (`gs /GS0`). +* Experimentar con claves adicionales como `/SM` (ajuste de trazo) o `/OPM` (modo de sobreimpresión). +* Aplicar la misma técnica a otros tipos de recursos como `/XObject` o `/ColorSpace`. + +¡Feliz manipulación de PDFs, y siéntete libre de explorar otros escenarios de **estado gráfico de Aspose PDF** como cambios dinámicos de opacidad o modos de fusión personalizados! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían 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 características 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/) +- [Cómo eliminar gráficos de PDFs usando Aspose.PDF .NET: Guía completa](/pdf/english/net/images-graphics/remove-graphics-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/programming-with-operators/_index.md b/pdf/swedish/net/programming-with-operators/_index.md index 24b4881502..25582950ee 100644 --- a/pdf/swedish/net/programming-with-operators/_index.md +++ b/pdf/swedish/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ 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. | +| [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. | +| [Hur man skapar ett tomt grafikläge i en PDF med C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Lär dig hur du skapar ett tomt grafikläge i en PDF med C# i Aspose.PDF för .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/swedish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/swedish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..8681365bf3 --- /dev/null +++ b/pdf/swedish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-08-17 +description: Skapa ett tomt grafikstatus i en PDF med C# och Aspose.Pdf. Följ den + här steg‑för‑steg‑guiden för att säkert redigera ExtGState‑resurser. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: sv +lastmod: 2026-08-17 +og_description: Skapa ett tomt grafikläge i en PDF med C#. Denna handledning visar + hur du redigerar ExtGState‑resurser med Aspose.Pdf för pålitliga PDF‑modifieringar. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Skapa tomt grafikläge i PDF med C# – steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Hur man skapar ett tomt grafikstatus i en PDF med C# +url: /sv/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man skapar ett tomt grafikstillstånd i en PDF med C# + +Om du behöver **skapa ett tomt grafikstillstånd** i en PDF visar den här guiden exakt hur du gör det med C# och Aspose.Pdf. Du får ett komplett, körbart exempel som lägger till en ny post i sidans ExtGState‑ordbok utan att påverka befintligt innehåll. + +Att arbeta med PDF‑grafikstillstånd är ett vanligt krav när du vill kontrollera transparens, blandningslägen eller andra renderingsparametrar på objekt‑nivå. Koden nedan demonstrerar den rekommenderade metoden, förklarar varför varje steg är viktigt och tar upp typiska variationer du kan stöta på. + +## Förutsättningar + +Innan du börjar, se till att du har: + +* .NET 6.0 eller senare (exemplet kompileras även med .NET Core). +* En Aspose.Pdf for .NET‑licens (eller en tillfällig evalueringsnyckel). +* En mapp som innehåller en `input.pdf`‑fil du vill modifiera. +* Grundläggande kunskap om C#‑syntax och PDF‑koncept som resurser‑ordböcker. + +## Steg 1: Ställ in projektet och importera namnrymder + +Skapa ett nytt konsolprogram eller integrera koden i ett befintligt projekt. Lägg till Aspose.Pdf‑NuGet‑paketet: + +```bash +dotnet add package Aspose.Pdf +``` + +Importera sedan de nödvändiga namnrymderna: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Dessa importeringar ger dig åtkomst till `Document`, `DictionaryEditor` och PDF‑primitiva klasser som behövs för att **skapa ett tomt grafikstillstånd**. + +## Steg 2: Definiera mappen som innehåller PDF‑filerna + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Byt ut sökvägen mot platsen för dina egna PDF‑filer. Att hålla katalogen i en variabel gör koden återanvändbar och enklare att testa. + +## Steg 3: Läs in källdokumentet + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Att öppna dokumentet inom ett `using`‑statement säkerställer att filhandtaget frigörs automatiskt efter att du har sparat ändringarna. + +## Steg 4: Åtkomst till den första sidan och dess Resources‑ordbok + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` hämtar den första sidan (PDF‑sidnummer börjar på 1). +* `DictionaryEditor` ger ett bekvämt sätt att läsa och modifiera PDF‑ordböcker. +* `ExtGState`‑posten innehåller alla grafik‑tillståndsobjekt för sidan. Om nyckeln saknas skapar Aspose.Pdf automatiskt en tom ordbok. + +## Steg 5: Bygg en ny tom grafik‑tillståndsordbok + +Grafik‑tillståndet du lägger till kan vara tomt eller förifyllt med parametrar som opacitet (`CA`, `ca`) eller blandningsläge (`BM`). I den här handledningen skapar vi ett **tomt grafikstillstånd** och sätter sedan några typiska värden för att illustrera hur ordboken fungerar. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` skapar en ren behållare som du kan fylla med vilka grafik‑tillståndsnycklar som helst. +* Att lägga till `CA`, `ca` och `BM` är valfritt; du kan utelämna dem om du verkligen behöver ett tomt tillstånd. Koden visar hur du lägger till poster när du senare vill styra rendering. + +## Steg 6: Infoga det nya grafik‑tillståndet i ExtGState‑ordboken + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Att namnge posten `"GS0"` följer den vanliga konventionen att prefixa grafik‑tillståndsnamn med “GS”. Du kan välja vilket giltigt PDF‑namn som helst så länge det inte kolliderar med befintliga nycklar. + +## Steg 7: Spara det modifierade PDF‑dokumentet + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +`Save`‑anropet skriver den uppdaterade filen till `output.pdf`. När du öppnar den här filen i en PDF‑visare bekräftas att det nya grafik‑tillståndet finns; du kan referera till det senare med `gs`‑operatorn i innehållsströmmar. + +### Fullständig källkod + +När allt sätts ihop ser det kompletta programmet ut så här: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +När programmet körs skrivs en bekräftelsesats ut och `output.pdf` skapas med det nyss tillagda grafik‑tillståndet. + +## Varför denna metod fungerar bäst + +* **Direkt ordboksredigering** – Med `DictionaryEditor` undviker du att behöva parsra hela innehållsströmmen. Du modifierar bara de resurser du bryr dig om. +* **Typade PDF‑primitiver** – `CosPdfNumber`, `CosPdfName` och `CosPdfDictionary` garanterar att den genererade PDF‑filen följer PDF 1.7‑specifikationen. +* **Säkerhet** – `using`‑blocket disponerar `Document`‑objektet, vilket förhindrar fil‑lås som kan korrupta efterföljande byggen. +* **Utbyggbarhet** – När det tomma grafik‑tillståndet finns kan du referera till det från vilken innehållsoperator (`gs`) som helst för att ändra opacitet, blandningsläge eller andra parametrar för valda ritkommandon. + +## Vanliga variationer och kantfall + +| Situation | Rekommenderad justering | +|-----------|------------------------| +| **Flera sidor** | Loopa över `pdfDocument.Pages` och upprepa ordboksinsättningen för varje sida du behöver modifiera. | +| **Ingen befintlig ExtGState‑post** | `resourcesEditor["ExtGState"]` skapar automatiskt en tom ordbok om den saknas. Ingen extra kod behövs. | +| **Annat grafik‑tillståndsnamn** | Byt ut `"GS0"` mot ett namn som matchar din namngivningskonvention, t.ex. `"MyTransparentState"`. | +| **Endast ett tomt tillstånd** | Utelämna `parameters`‑arrayen och `foreach`‑loopen; ordboken förblir tom. | +| **Arbeta med krypterade PDF‑filer** | Ange lösenordet när du konstruerar `new Document(path, password)` innan du redigerar resurser. | + +## Verifiera resultatet + +Du kan verifiera att grafik‑tillståndet har lagts till genom att inspektera PDF‑filen med en låg‑nivå‑visare som **PDF‑Tron** eller **iText Sharp**. Leta efter en post liknande: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Om posten visas har **skapa tomt grafikstillstånd**‑operationen lyckats. + +## Slutsats + +Du vet nu hur du **skapar ett tomt grafikstillstånd** i en PDF med C# och Aspose.Pdf. Handledningen gick igenom varje steg – från att läsa in dokumentet till att redigera `ExtGState`‑ordboken och spara resultatet – samtidigt som den förklarade motivet bakom varje åtgärd. + +Härifrån kan du: + +* Använda det nya grafik‑tillståndet i innehållsströmmar (`gs /GS0`). +* Experimentera med ytterligare nycklar som `/SM` (stroke‑justering) eller `/OPM` (overprint‑läge). +* Tillämpa samma teknik på andra resurstyp‑er som `/XObject` eller `/ColorSpace`. + +Lycka till med PDF‑hackandet, och utforska gärna andra **Aspose PDF graphics state**‑scenarier såsom dynamiska opacitetsändringar eller anpassade blandningslägen! + +## Vad bör du lära dig härnäst? + +De följande handledningarna 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. + +- [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/) +- [How to Remove Graphics from PDFs Using Aspose.PDF .NET: A Complete Guide](/pdf/english/net/images-graphics/remove-graphics-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/thai/net/programming-with-operators/_index.md b/pdf/thai/net/programming-with-operators/_index.md index b18b824bb2..98ae08284b 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#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | เรียนรู้วิธีสร้างสถานะกราฟิกเปล่าใน PDF ด้วย C# {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/thai/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/thai/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..b605033c43 --- /dev/null +++ b/pdf/thai/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-08-17 +description: สร้างสถานะกราฟิกว่างใน PDF ด้วย C# และ Aspose.Pdf. ทำตามคู่มือขั้นตอนต่อขั้นตอนนี้เพื่อแก้ไขทรัพยากร + ExtGState อย่างปลอดภัย. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: th +lastmod: 2026-08-17 +og_description: สร้างสถานะกราฟิกเปล่าใน PDF ด้วย C#. บทเรียนนี้แสดงวิธีแก้ไขทรัพยากร + ExtGState ด้วย Aspose.Pdf เพื่อการแก้ไข PDF ที่น่าเชื่อถือ. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: สร้างสถานะกราฟิกเปล่าใน PDF ด้วย C# – คู่มือแบบขั้นตอนต่อขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: วิธีสร้างสถานะกราฟิกว่างใน PDF ด้วย C# +url: /th/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีสร้างกราฟิกสเตตว่างใน PDF ด้วย C# + +หากคุณต้องการ **create empty graphics state** ใน PDF คำแนะนำนี้จะแสดงให้คุณเห็นขั้นตอนที่ทำได้โดยใช้ C# และ Aspose.Pdf คุณจะได้เห็นตัวอย่างที่ทำงานได้เต็มรูปแบบซึ่งเพิ่มรายการใหม่ลงในพจนานุกรม ExtGState ของหน้าโดยไม่กระทบเนื้อหาที่มีอยู่ + +การทำงานกับกราฟิกสเตตของ PDF เป็นความต้องการทั่วไปเมื่อคุณต้องการควบคุมความโปร่งใส, โหมดผสม, หรือพารามิเตอร์การเรนเดอร์อื่น ๆ ในระดับวัตถุ โค้ดด้านล่างจะแสดงแนวทางที่แนะนำ, อธิบายว่าทำไมแต่ละขั้นตอนจึงสำคัญ, และครอบคลุมการเปลี่ยนแปลงทั่วไปที่คุณอาจพบ + +## ข้อกำหนดเบื้องต้น + +* .NET 6.0 หรือใหม่กว่า (ตัวอย่างสามารถคอมไพล์กับ .NET Core ได้เช่นกัน). +* ใบอนุญาต Aspose.Pdf for .NET (หรือคีย์ประเมินผลชั่วคราว). +* โฟลเดอร์ที่มีไฟล์ `input.pdf` ที่คุณต้องการแก้ไข. +* ความคุ้นเคยพื้นฐานกับไวยากรณ์ C# และแนวคิด PDF เช่น พจนานุกรม resources. + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และนำเข้า namespaces + +สร้างแอปพลิเคชันคอนโซลใหม่หรือรวมโค้ดเข้าในโปรเจกต์ที่มีอยู่แล้ว เพิ่มแพคเกจ NuGet ของ Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +จากนั้นนำเข้า namespaces ที่จำเป็น: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +การนำเข้าดังกล่าวทำให้คุณเข้าถึงคลาส `Document`, `DictionaryEditor` และคลาส primitive ของ PDF ที่จำเป็นสำหรับการสร้างรายการ **create empty graphics state** + +## ขั้นตอนที่ 2: กำหนดโฟลเดอร์ที่เก็บไฟล์ PDF + +แทนที่เส้นทางด้วยตำแหน่งที่ตั้งของไฟล์ PDF ของคุณเอง การเก็บไดเรกทอรีในตัวแปรทำให้โค้ดสามารถนำกลับมาใช้ใหม่และง่ายต่อการทดสอบ. + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +## ขั้นตอนที่ 3: โหลดเอกสาร PDF ต้นฉบับ + +การเปิดเอกสารภายในคำสั่ง `using` ทำให้แน่ใจว่าการจัดการไฟล์จะถูกปล่อยอัตโนมัติหลังจากบันทึกการเปลี่ยนแปลง. + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +## ขั้นตอนที่ 4: เข้าถึงหน้าแรกและพจนานุกรม Resources ของมัน + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +- `Pages[1]` ดึงหน้าที่หนึ่ง (เลขหน้าของ PDF เริ่มที่ 1). +- `DictionaryEditor` ให้วิธีที่สะดวกในการอ่านและแก้ไขพจนานุกรมของ PDF. +- รายการ `ExtGState` เก็บวัตถุ graphics‑state ทั้งหมดสำหรับหน้า หากคีย์ไม่มีอยู่ Aspose.Pdf จะสร้างพจนานุกรมว่างโดยอัตโนมัติ. + +## ขั้นตอนที่ 5: สร้างพจนานุกรม graphics‑state ว่างใหม่ + +กราฟิกสเตตที่คุณเพิ่มสามารถเป็นว่างหรือมีพารามิเตอร์ล่วงหน้า เช่น ความทึบ (`CA`, `ca`) หรือโหมดผสม (`BM`). ในบทแนะนำนี้เราจะสร้าง **empty graphics state** แล้วตั้งค่าบางค่าเพื่อแสดงวิธีการทำงานของพจนานุกรม. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +- `CosPdfDictionary.CreateEmptyDictionary` สร้างคอนเทนเนอร์ที่ว่างเปล่าซึ่งคุณสามารถเติมด้วยคีย์ graphics‑state ใด ๆ. +- การเพิ่ม `CA`, `ca`, และ `BM` เป็นตัวเลือก; คุณสามารถละเว้นได้หากต้องการสเตตว่างจริง ๆ โค้ดแสดงวิธีเพิ่มรายการเมื่อคุณต้องการควบคุมการเรนเดอร์ในภายหลัง. + +## ขั้นตอนที่ 6: แทรกกราฟิกสเตตใหม่ลงในพจนานุกรม ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +การตั้งชื่อรายการเป็น `"GS0"` สอดคล้องกับแนวปฏิบัติทั่วไปที่ใส่คำนำหน้า “GS” ให้กับชื่อกราฟิกสเตต คุณสามารถเลือกชื่อ PDF ที่ถูกต้องใด ๆ ที่ไม่ซ้ำกับคีย์ที่มีอยู่. + +## ขั้นตอนที่ 7: บันทึกเอกสาร PDF ที่แก้ไขแล้ว + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +คำสั่ง `Save` จะเขียนไฟล์ที่อัปเดตไปยัง `output.pdf`. การเปิดไฟล์นี้ในโปรแกรมดู PDF จะยืนยันว่ากราฟิกสเตตใหม่มีอยู่; คุณสามารถอ้างอิงมันต่อไปด้วยโอเปอเรเตอร์ `gs` ในสตรีมเนื้อหา. + +### รายการซอร์สเต็มรูปแบบ + +เมื่อรวมทุกอย่างเข้าด้วยกัน โปรแกรมเต็มรูปแบบจะเป็นดังนี้: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +การรันโปรแกรมจะแสดงบรรทัดยืนยันและสร้างไฟล์ `output.pdf` พร้อมกราฟิกสเตตที่เพิ่มใหม่. + +## ทำไมวิธีนี้ถึงทำงานได้ดีที่สุด + +- **การแก้ไขพจนานุกรมโดยตรง** – การใช้ `DictionaryEditor` ช่วยหลีกเลี่ยงการต้องพาร์สสตรีมเนื้อหาทั้งหมด คุณจะแก้ไขเฉพาะ resources ที่ต้องการเท่านั้น. +- **PDF primitives ที่กำหนดประเภท** – `CosPdfNumber`, `CosPdfName`, และ `CosPdfDictionary` รับประกันว่า PDF ที่สร้างขึ้นสอดคล้องกับสเปค PDF 1.7. +- **ความปลอดภัย** – บล็อก `using` จะทำลายอ็อบเจ็กต์ `Document` ป้องกันการล็อกไฟล์ที่อาจทำให้การสร้างต่อไปเสียหาย. +- **ความสามารถขยาย** – เมื่อกราฟิกสเตตว่างมีอยู่แล้ว คุณสามารถอ้างอิงจากโอเปอเรเตอร์เนื้อหาใด ๆ (`gs`) เพื่อเปลี่ยนความทึบ, โหมดผสม, หรือพารามิเตอร์อื่น ๆ สำหรับคำสั่งวาดที่เลือก. + +## การเปลี่ยนแปลงทั่วไปและกรณีขอบ + +| สถานการณ์ | การปรับแต่งที่แนะนำ | +|-----------|-------------------| +| **หลายหน้า** | วนลูปผ่าน `pdfDocument.Pages` และทำการแทรกพจนานุกรมซ้ำสำหรับแต่ละหน้าที่คุณต้องการแก้ไข. | +| **ไม่มีรายการ ExtGState อยู่แล้ว** | `resourcesEditor["ExtGState"]` จะสร้างพจนานุกรมว่างโดยอัตโนมัติหากไม่มีอยู่ ไม่จำเป็นต้องเขียนโค้ดเพิ่มเติม. | +| **ชื่อ graphics‑state ที่แตกต่าง** | แทนที่ `"GS0"` ด้วยชื่อที่สอดคล้องกับแนวปฏิบัติของคุณ เช่น `"MyTransparentState"`. | +| **เพิ่มเฉพาะสเตตว่าง** | ละเว้นอาร์เรย์ `parameters` และลูป `foreach`; พจนานุกรมจะคงเป็นว่าง. | +| **ทำงานกับ PDF ที่เข้ารหัส** | ระบุรหัสผ่านเมื่อสร้าง `new Document(path, password)` ก่อนแก้ไข resources. | + +## การตรวจสอบผลลัพธ์ + +คุณสามารถตรวจสอบว่ากราฟิกสเตตถูกเพิ่มโดยการตรวจสอบ PDF ด้วยโปรแกรมดูระดับต่ำเช่น **PDF‑Tron** หรือ **iText Sharp** ค้นหารายการที่คล้ายกับ: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +หากรายการปรากฏ การดำเนินการ **create empty graphics state** สำเร็จ. + +## สรุป + +ตอนนี้คุณรู้วิธี **create empty graphics state** ใน PDF ด้วย C# และ Aspose.Pdf แล้ว บทแนะนำได้ครอบคลุมทุกขั้นตอน—from การโหลดเอกสารจนถึงการแก้ไขพจนานุกรม `ExtGState` และการบันทึกผลลัพธ์—พร้อมอธิบายเหตุผลของแต่ละการกระทำ. + +จากนี้คุณสามารถ: + +* ใช้กราฟิกสเตตใหม่ในสตรีมเนื้อหา (`gs /GS0`). +* ทดลองใช้คีย์เพิ่มเติมเช่น `/SM` (การปรับเส้น) หรือ `/OPM` (โหมดพิมพ์ซ้อน). +* นำเทคนิคเดียวกันไปใช้กับประเภท resource อื่น ๆ เช่น `/XObject` หรือ `/ColorSpace`. + +ขอให้สนุกกับการทำงานกับ PDF และอย่าลังเลที่จะสำรวจสถานการณ์ **Aspose PDF graphics state** อื่น ๆ เช่น การเปลี่ยนความทึบแบบไดนามิกหรือโหมดผสมแบบกำหนดเอง! + +## สิ่งที่คุณควรเรียนต่อไป + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการนำไปใช้แบบอื่นในโครงการของคุณ. + +- [วิธีสร้างเส้นประใน PDF ด้วย Aspose.PDF for .NET: คู่มือขั้นตอนต่อขั้นตอน](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [วิธีลบกราฟิกจาก PDF ด้วย Aspose.PDF .NET: คู่มือเต็ม](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [สร้างและเติมสี่เหลี่ยมใน PDF ด้วย Aspose.PDF for .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/turkish/net/programming-with-operators/_index.md b/pdf/turkish/net/programming-with-operators/_index.md index 20dfde302d..8b27bf69b9 100644 --- a/pdf/turkish/net/programming-with-operators/_index.md +++ b/pdf/turkish/net/programming-with-operators/_index.md @@ -23,6 +23,7 @@ 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. | +| [C# ile PDF'de boş grafik durumu oluşturma](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Aspose.PDF for .NET ile C# kullanarak PDF içinde boş bir grafik durumu nasıl oluşturulur? | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/turkish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/turkish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..6f9bb9735a --- /dev/null +++ b/pdf/turkish/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-08-17 +description: C# ve Aspose.Pdf kullanarak bir PDF'de boş grafik durumu oluşturun. ExtGState + kaynaklarını güvenli bir şekilde düzenlemek için bu adım adım kılavuzu izleyin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: tr +lastmod: 2026-08-17 +og_description: C# kullanarak bir PDF'de boş grafik durumu oluşturun. Bu öğreticide, + güvenilir PDF değişiklikleri için Aspose.Pdf ile ExtGState kaynaklarını nasıl düzenleyeceğiniz + gösterilmektedir. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: C# ile PDF'de boş grafik durumu oluşturma – adım adım rehber +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: C# ile PDF'de boş grafik durumu nasıl oluşturulur +url: /tr/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# ile PDF'de boş grafik durumu nasıl oluşturulur + +PDF'de **boş grafik durumu** oluşturmanız gerekiyorsa, bu kılavuz C# ve Aspose.Pdf ile bunu tam olarak nasıl yapacağınızı gösterir. Sayfanın ExtGState sözlüğüne yeni bir giriş ekleyen, mevcut içeriği etkilemeyen eksiksiz, çalıştırılabilir bir örnek göreceksiniz. + +PDF grafik durumlarıyla çalışmak, şeffaflığı, karışım modlarını veya nesne bazında diğer render parametrelerini kontrol etmek istediğinizde yaygın bir gereksinimdir. Aşağıdaki kod önerilen yaklaşımı gösterir, her adımın neden önemli olduğunu açıklar ve karşılaşabileceğiniz tipik varyasyonları kapsar. + +## Önkoşullar + +* .NET 6.0 veya daha yenisi (örnek .NET Core ile de derlenir). +* Bir Aspose.Pdf for .NET lisansı (veya geçici bir değerlendirme anahtarı). +* `input.pdf` dosyasını içeren bir klasör. +* C# sözdizimi ve kaynak sözlükleri gibi PDF kavramlarına temel aşinalık. + +## Adım 1: Projeyi kurun ve ad alanlarını içe aktarın + +Yeni bir konsol uygulaması oluşturun veya kodu mevcut bir projeye entegre edin. Aspose.Pdf NuGet paketini ekleyin: + +```bash +dotnet add package Aspose.Pdf +``` + +Ardından gerekli ad alanlarını içe aktarın: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Bu içe aktarmalar, **boş grafik durumu** girişlerini oluşturmak için gereken `Document`, `DictionaryEditor` ve PDF ilkel sınıflarına erişim sağlar. + +## Adım 2: PDF dosyalarını tutan klasörü tanımlayın + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Yolu, kendi PDF dosyalarınızın konumuyla değiştirin. Dizini bir değişkende tutmak kodun yeniden kullanılabilir ve test edilmesini kolaylaştırır. + +## Adım 3: Kaynak PDF belgesini yükleyin + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +`using` ifadesi içinde belgeyi açmak, değişiklikleri kaydettikten sonra dosya tutamacının otomatik olarak serbest bırakılmasını sağlar. + +## Adım 4: İlk sayfaya ve onun Resources sözlüğüne erişin + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` ilk sayfayı alır (PDF sayfa numaraları 1'den başlar). +* `DictionaryEditor` PDF sözlüklerini okumanın ve değiştirmenin pratik bir yolunu sunar. +* `ExtGState` girişi, sayfa için tüm grafik‑durumu nesnelerini tutar. Anahtar mevcut değilse, Aspose.Pdf otomatik olarak boş bir sözlük oluşturur. + +## Adım 5: Yeni bir boş grafik‑durumu sözlüğü oluşturun + +Eklediğiniz grafik durumu boş olabilir veya şeffaflık (`CA`, `ca`) veya karışım modu (`BM`) gibi parametrelerle önceden doldurulmuş olabilir. Bu öğreticide bir **boş grafik durumu** oluşturuyor ve sözlüğün nasıl çalıştığını göstermek için birkaç tipik değer ayarlıyoruz. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` istediğiniz grafik‑durumu anahtarlarıyla doldurabileceğiniz temiz bir kapsayıcı oluşturur. +* `CA`, `ca` ve `BM` eklemek isteğe bağlıdır; gerçekten boş bir duruma ihtiyacınız varsa bunları atlayabilirsiniz. Kod, render'ı daha sonra kontrol etmeye karar verdiğinizde girişlerin nasıl ekleneceğini gösterir. + +## Adım 6: Yeni grafik durumunu ExtGState sözlüğüne ekleyin + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +`"GS0"` adını vermek, grafik‑durumu adlarının “GS” ile ön eklenmesi yaygın konvansiyonunu izler. Mevcut anahtarlarla çakışmayan herhangi bir geçerli PDF adını seçebilirsiniz. + +## Adım 7: Değiştirilen PDF belgesini kaydedin + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +`Save` çağrısı güncellenmiş dosyayı `output.pdf` olarak yazar. Bu dosyayı bir PDF görüntüleyicide açmak, yeni grafik durumunun var olduğunu doğrular; daha sonra içerik akışlarında `gs` operatörüyle ona başvurabilirsiniz. + +### Tam kaynak listesi + +Her şeyi bir araya getirdiğimizde, tam program şöyle görünür: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Programı çalıştırmak bir onay satırı yazdırır ve yeni eklenen grafik durumu ile `output.pdf` oluşturur. + +## Neden bu yaklaşım en iyisidir + +* **Doğrudan sözlük düzenleme** – `DictionaryEditor` kullanmak, tüm içerik akışını ayrıştırma ihtiyacını ortadan kaldırır. Sadece ilgilendiğiniz kaynakları değiştirirsiniz. +* **Tiplenmiş PDF ilkelikleri** – `CosPdfNumber`, `CosPdfName` ve `CosPdfDictionary`, oluşturulan PDF'nin PDF 1.7 spesifikasyonuna uygun olmasını garantiler. +* **Güvenlik** – `using` bloğu `Document` nesnesini serbest bırakır, sonraki derlemeleri bozabilecek dosya kilitlerini önler. +* **Genişletilebilirlik** – Boş grafik durumu oluşturulduktan sonra, seçili çizim komutları için şeffaflık, karışım modu veya diğer parametreleri değiştirmek amacıyla herhangi bir içerik operatöründen (`gs`) ona başvurabilirsiniz. + +## Yaygın varyasyonlar ve kenar durumları + +| Situation | Recommended tweak | +|-----------|-------------------| +| **Birden fazla sayfa** | `pdfDocument.Pages` üzerinde döngü yapın ve değiştirmeniz gereken her sayfa için sözlük eklemesini tekrarlayın. | +| **Mevcut ExtGState girişi yok** | `resourcesEditor["ExtGState"]` mevcut değilse otomatik olarak boş bir sözlük oluşturur. Ek kod gerekmez. | +| **Farklı grafik‑durumu adı** | `"GS0"` yerine adlandırma konvansiyonunuza uyan bir ad kullanın, ör. `"MyTransparentState"`. | +| **Yalnızca boş bir durum eklemek** | `parameters` dizisini ve `foreach` döngüsünü atlayın; sözlük boş kalacaktır. | +| **Şifreli PDF'lerle çalışmak** | Kaynakları düzenlemeden önce `new Document(path, password)` oluştururken şifreyi sağlayın. | + +## Sonucu doğrulama + +Grafik durumunun eklendiğini, **PDF‑Tron** veya **iText Sharp** gibi düşük seviyeli bir görüntüleyiciyle PDF'yi inceleyerek doğrulayabilirsiniz. Şuna benzer bir giriş arayın: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Giriş görünürse, **boş grafik durumu oluşturma** işlemi başarılı olmuştur. + +## Sonuç + +Artık C# ve Aspose.Pdf kullanarak bir PDF'de **boş grafik durumu** nasıl oluşturulacağını biliyorsunuz. Öğretici, belgeyi yüklemekten `ExtGState` sözlüğünü düzenlemeye ve sonucu kaydetmeye kadar her adımı kapsadı ve her eylemin mantığını açıkladı. + +Bundan sonra şunları yapabilirsiniz: + +* Yeni grafik durumunu içerik akışlarında (`gs /GS0`) kullanın. +* `/SM` (çizgi ayarı) veya `/OPM` (üst baskı modu) gibi ek anahtarlarla deney yapın. +* Aynı tekniği `/XObject` veya `/ColorSpace` gibi diğer kaynak türlerine uygulayın. + +İyi PDF keşifleri, ve dinamik şeffaflık değişiklikleri veya özel karışım modları gibi diğer **Aspose PDF grafik durumu** senaryolarını keşfetmekten çekinmeyin! + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren eksiksiz çalışan kod örnekleri sunar. + +- [Aspose.PDF for .NET ile PDF'lerde Kesikli Çizgiler Nasıl Oluşturulur: Adım Adım Kılavuz](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Aspose.PDF .NET ile PDF'lerden Grafik Nasıl Kaldırılır: Tam Kılavuz](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [Aspose.PDF for .NET ile PDF'lerde Dikdörtgen Oluşturma ve Doldurma: Adım Adım Kılavuz](/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/programming-with-operators/_index.md b/pdf/vietnamese/net/programming-with-operators/_index.md index bae1c8435c..a4503d5a8d 100644 --- a/pdf/vietnamese/net/programming-with-operators/_index.md +++ b/pdf/vietnamese/net/programming-with-operators/_index.md @@ -22,7 +22,8 @@ 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. | +| [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. | +| [Cách tạo trạng thái đồ họa trống trong PDF bằng C#](./how-to-create-empty-graphics-state-in-a-pdf-with-c/) | Hướng dẫn tạo một trạng thái đồ họa trống trong PDF bằng C# sử dụng Aspose.PDF cho .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/pdf/vietnamese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md b/pdf/vietnamese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md new file mode 100644 index 0000000000..d1394b3103 --- /dev/null +++ b/pdf/vietnamese/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-08-17 +description: Tạo trạng thái đồ họa trống trong PDF bằng C# và Aspose.Pdf. Thực hiện + theo hướng dẫn từng bước này để chỉnh sửa tài nguyên ExtGState một cách an toàn. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create empty graphics state +- Aspose PDF graphics state +- C# modify PDF resources +- add ExtGState dictionary +- PDF page resources editing +language: vi +lastmod: 2026-08-17 +og_description: Tạo trạng thái đồ họa trống trong PDF bằng C#. Hướng dẫn này chỉ cách + chỉnh sửa tài nguyên ExtGState với Aspose.Pdf để thực hiện các sửa đổi PDF đáng + tin cậy. +og_image_alt: Screenshot of C# code that adds an empty graphics state to a PDF document +og_title: Tạo trạng thái đồ họa trống trong PDF bằng C# – hướng dẫn từng bước +schemas: +- author: Aspose + dateModified: '2026-08-17' + description: Create empty graphics state in a PDF using C# and Aspose.Pdf. Follow + this step‑by‑step guide to edit ExtGState resources safely. + headline: How to create empty graphics state in a PDF with C# + type: TechArticle +tags: +- Aspose.Pdf +- C# +- PDF manipulation +title: Cách tạo trạng thái đồ họa rỗng trong PDF bằng C# +url: /vi/net/programming-with-operators/how-to-create-empty-graphics-state-in-a-pdf-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách tạo trạng thái đồ họa trống trong PDF bằng C# + +Nếu bạn cần **tạo trạng thái đồ họa trống** trong một PDF, hướng dẫn này sẽ chỉ cho bạn cách thực hiện chính xác bằng C# và Aspose.Pdf. Bạn sẽ thấy một ví dụ hoàn chỉnh, có thể chạy được, thêm một mục mới vào từ điển ExtGState của trang mà không ảnh hưởng đến nội dung hiện có. + +Làm việc với trạng thái đồ họa PDF là một yêu cầu phổ biến khi bạn muốn kiểm soát độ trong suốt, chế độ hòa trộn, hoặc các tham số render khác trên cơ sở từng đối tượng. Đoạn mã dưới đây minh họa cách tiếp cận được khuyến nghị, giải thích lý do mỗi bước quan trọng, và đề cập đến các biến thể thường gặp mà bạn có thể gặp phải. + +## Yêu cầu trước + +* .NET 6.0 hoặc phiên bản mới hơn (mẫu này cũng biên dịch được với .NET Core). +* Giấy phép Aspose.Pdf cho .NET (hoặc khóa đánh giá tạm thời). +* Một thư mục chứa tệp `input.pdf` mà bạn muốn sửa đổi. +* Kiến thức cơ bản về cú pháp C# và các khái niệm PDF như từ điển tài nguyên. + +## Bước 1: Thiết lập dự án và nhập không gian tên + +Tạo một ứng dụng console mới hoặc tích hợp mã vào dự án hiện có. Thêm gói NuGet Aspose.Pdf: + +```bash +dotnet add package Aspose.Pdf +``` + +Sau đó nhập các không gian tên cần thiết: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; +``` + +Các import này cho phép bạn truy cập các lớp `Document`, `DictionaryEditor` và các primitive PDF cần thiết để **tạo trạng thái đồ họa trống**. + +## Bước 2: Xác định thư mục chứa các tệp PDF + +```csharp +// Step 1: Define the folder that contains the PDF files +string dataDir = @"C:\PdfSamples\"; +``` + +Thay thế đường dẫn bằng vị trí các tệp PDF của bạn. Giữ thư mục trong một biến giúp mã có thể tái sử dụng và dễ kiểm thử hơn. + +## Bước 3: Tải tài liệu PDF nguồn + +```csharp +// Step 2: Load the source PDF document +using (var pdfDocument = new Document(dataDir + "input.pdf")) +{ + // All subsequent operations happen inside this using block +``` + +Mở tài liệu trong một câu lệnh `using` đảm bảo rằng tay cầm tệp được giải phóng tự động sau khi bạn lưu các thay đổi. + +## Bước 4: Truy cập trang đầu tiên và từ điển Resources của nó + +```csharp + // Step 3: Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); +``` + +* `Pages[1]` lấy trang đầu tiên (số trang PDF bắt đầu từ 1). +* `DictionaryEditor` cung cấp cách tiện lợi để đọc và sửa đổi các từ điển PDF. +* Mục `ExtGState` chứa tất cả các đối tượng graphics‑state cho trang. Nếu khóa không tồn tại, Aspose.Pdf sẽ tự động tạo một từ điển trống. + +## Bước 5: Xây dựng một từ điển graphics‑state trống mới + +Trạng thái đồ họa bạn thêm có thể là trống hoặc đã được điền sẵn các tham số như độ trong suốt (`CA`, `ca`) hoặc chế độ hòa trộn (`BM`). Trong hướng dẫn này, chúng tôi tạo một **trạng thái đồ họa trống** và sau đó đặt một vài giá trị điển hình để minh họa cách hoạt động của từ điển. + +```csharp + // Step 4: Create a new empty graphics‑state dictionary and set its parameters + var newGraphicsState = CosPdfDictionary.CreateEmptyDictionary(pdfDocument); + var parameters = new[] + { + new KeyValuePair("CA", new CosPdfNumber(1)), // Stroke opacity + new KeyValuePair("ca", new CosPdfNumber(0.5)), // Fill opacity + new KeyValuePair("BM", new CosPdfName("Normal")) // Blend mode + }; + foreach (var p in parameters) + newGraphicsState.Add(p); +``` + +* `CosPdfDictionary.CreateEmptyDictionary` tạo một container sạch mà bạn có thể điền bất kỳ khóa graphics‑state nào. +* Việc thêm `CA`, `ca` và `BM` là tùy chọn; bạn có thể bỏ qua chúng nếu thực sự cần một trạng thái trống. Đoạn mã cho thấy cách thêm các mục khi bạn sau này quyết định kiểm soát việc render. + +## Bước 6: Chèn trạng thái đồ họa mới vào từ điển ExtGState + +```csharp + // Step 5: Add the new graphics state to the page's ExtGState dictionary (e.g., name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); +``` + +Đặt tên mục `"GS0"` tuân theo quy ước chung là đặt tiền tố “GS” cho tên graphics‑state. Bạn có thể chọn bất kỳ tên PDF hợp lệ nào mà không trùng với các khóa hiện có. + +## Bước 7: Lưu tài liệu PDF đã sửa đổi + +```csharp + // Step 6: Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); +} +``` + +Lệnh `Save` ghi tệp đã cập nhật vào `output.pdf`. Mở tệp này trong trình xem PDF sẽ xác nhận rằng trạng thái đồ họa mới tồn tại; bạn có thể tham chiếu tới nó sau này bằng toán tử `gs` trong các luồng nội dung. + +### Danh sách mã nguồn đầy đủ + +Kết hợp mọi thứ lại, chương trình hoàn chỉnh trông như sau: + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Operators; + +class Program +{ + static void Main() + { + // Define the folder that contains the PDF files + string dataDir = @"C:\PdfSamples\"; + + // Load the source PDF document + using (var pdfDocument = new Document(dataDir + "input.pdf")) + { + // Get the first page and its Resources dictionary + var firstPage = pdfDocument.Pages[1]; + var resourcesEditor = new DictionaryEditor(firstPage.Resources); + var extGStateDict = resourcesEditor["ExtGState"].ToCosPdfDictionary(); + + // Create a new empty graphics‑state dictionary and set its parameters + var 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); + + // Add the new graphics state to the page's ExtGState dictionary (name it "GS0") + extGStateDict.Add("GS0", newGraphicsState); + + // Save the modified PDF document + pdfDocument.Save(dataDir + "output.pdf"); + } + + Console.WriteLine("Empty graphics state created and saved to output.pdf"); + } +} +``` + +Chạy chương trình sẽ in ra một dòng xác nhận và tạo ra `output.pdf` với trạng thái đồ họa mới được thêm. + +## Tại sao cách tiếp cận này là tốt nhất + +* **Chỉnh sửa từ điển trực tiếp** – Sử dụng `DictionaryEditor` tránh việc phải phân tích toàn bộ luồng nội dung. Bạn chỉ sửa đổi các tài nguyên mà bạn quan tâm. +* **Primitive PDF có kiểu** – `CosPdfNumber`, `CosPdfName` và `CosPdfDictionary` đảm bảo PDF được tạo tuân thủ chuẩn PDF 1.7. +* **An toàn** – Khối `using` giải phóng đối tượng `Document`, ngăn chặn khóa tệp có thể làm hỏng các bản build tiếp theo. +* **Mở rộng** – Khi trạng thái đồ họa trống đã tồn tại, bạn có thể tham chiếu tới nó từ bất kỳ toán tử nội dung nào (`gs`) để thay đổi độ trong suốt, chế độ hòa trộn, hoặc các tham số khác cho các lệnh vẽ đã chọn. + +## Các biến thể phổ biến và trường hợp đặc biệt + +| Tình huống | Điều chỉnh đề xuất | +|-----------|-------------------| +| **Nhiều trang** | Lặp qua `pdfDocument.Pages` và lặp lại việc chèn từ điển cho mỗi trang bạn cần sửa đổi. | +| **Không có mục ExtGState hiện có** | `resourcesEditor["ExtGState"]` tự động tạo một từ điển trống nếu nó không tồn tại. Không cần mã bổ sung. | +| **Tên graphics‑state khác** | Thay `"GS0"` bằng một tên phù hợp với quy ước đặt tên của bạn, ví dụ `"MyTransparentState"`. | +| **Chỉ thêm một trạng thái trống** | Bỏ qua mảng `parameters` và vòng lặp `foreach`; từ điển sẽ vẫn trống. | +| **Làm việc với PDF được mã hoá** | Cung cấp mật khẩu khi khởi tạo `new Document(path, password)` trước khi chỉnh sửa tài nguyên. | + +## Xác minh kết quả + +Bạn có thể xác minh rằng trạng thái đồ họa đã được thêm bằng cách kiểm tra PDF bằng một trình xem cấp thấp như **PDF‑Tron** hoặc **iText Sharp**. Tìm một mục tương tự như: + +``` +/ExtGState << /GS0 << /CA 1 /ca 0.5 /BM /Normal >> >> +``` + +Nếu mục này xuất hiện, thao tác **tạo trạng thái đồ họa trống** đã thành công. + +## Kết luận + +Bây giờ bạn đã biết cách **tạo trạng thái đồ họa trống** trong PDF bằng C# và Aspose.Pdf. Hướng dẫn đã bao phủ mọi bước — từ tải tài liệu, chỉnh sửa từ điển `ExtGState` cho tới lưu kết quả — đồng thời giải thích lý do đằng sau mỗi hành động. + +Từ đây bạn có thể: + +* Sử dụng trạng thái đồ họa mới trong các luồng nội dung (`gs /GS0`). +* Thử nghiệm các khóa bổ sung như `/SM` (điều chỉnh nét) hoặc `/OPM` (chế độ in chồng). +* Áp dụng kỹ thuật tương tự cho các loại tài nguyên khác như `/XObject` hoặc `/ColorSpace`. + +Chúc bạn vui vẻ khi làm việc với PDF, và hãy tự do khám phá các kịch bản **trạng thái đồ họa Aspose PDF** khác như thay đổi độ trong suốt động hoặc chế độ hòa trộn tùy chỉnh! + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoạt động đầy đủ với các 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. + +- [Cách tạo đường nét đứt trong PDF bằng Aspose.PDF cho .NET: Hướng dẫn từng bước](/pdf/english/net/images-graphics/create-dashed-lines-aspose-pdf-net/) +- [Cách xóa đồ họa khỏi PDF bằng Aspose.PDF .NET: Hướng dẫn đầy đủ](/pdf/english/net/images-graphics/remove-graphics-aspose-pdf-net/) +- [Tạo và tô hình chữ nhật trong PDF bằng Aspose.PDF cho .NET: Hướng dẫn từng bước](/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