diff --git a/html/arabic/net/advanced-features/_index.md b/html/arabic/net/advanced-features/_index.md index 49f4375d3d..1895f1b7a7 100644 --- a/html/arabic/net/advanced-features/_index.md +++ b/html/arabic/net/advanced-features/_index.md @@ -47,6 +47,9 @@ Aspose.HTML for .NET هي أداة قوية تتيح للمطورين العمل ### [كيفية دمج الخطوط برمجيًا في C# – دليل خطوة بخطوة](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) تعلم كيفية دمج خطوط متعددة برمجيًا في C# باستخدام Aspose.HTML لإنشاء مستندات HTML غنية ومتنوعة. +### [إنشاء خط عريض مائل في C# – دليل خطوة بخطوة](./create-bold-italic-font-in-c-step-by-step-guide/) +تعلم كيفية إنشاء خطوط عريضة ومائلة برمجيًا في C# باستخدام Aspose.HTML لتصميم مستندات HTML غنية. + ## خاتمة يفتح برنامج Aspose.HTML for .NET الباب أمام عالم من الاحتمالات عندما يتعلق الأمر بالعمل مع مستندات HTML في تطبيقات .NET. ستزودك دروس الميزات المتقدمة هذه بالمعرفة والمهارات اللازمة لتسخير الإمكانات الكاملة لبرنامج Aspose.HTML. ارتقِ بمشاريع التطوير الخاصة بك، ووفر الوقت، وأنشئ حلولاً رائعة باستخدام برنامج Aspose.HTML for .NET. ابدأ بدروسنا التعليمية اليوم وارتق بتطوير الويب الخاص بك إلى المستوى التالي. diff --git a/html/arabic/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/arabic/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..78b1cd5174 --- /dev/null +++ b/html/arabic/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-08-15 +description: إنشاء خط عريض مائل في C# بسرعة. تعلّم كيفية إنشاء خط في C# بنمطين عريض + ومائل باستخدام الفئة المدمجة Font. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: ar +lastmod: 2026-08-15 +og_description: إنشاء خط عريض مائل في C# مع مثال واضح. يوضح هذا الدرس كيفية إنشاء + خط في C# باستخدام علامات FontStyle ويشرح الأخطاء الشائعة. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: إنشاء خط عريض ومائل في C# – دليل البرمجة الكامل +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: إنشاء خط عريض مائل في C# – دليل خطوة بخطوة +url: /ar/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء خط عريض مائل في C# – دليل خطوة بخطوة + +إذا كنت بحاجة إلى **إنشاء خط عريض مائل** في C#، فإن هذا الدليل يوضح لك بالضبط كيفية القيام بذلك. ستشاهد مثالًا كاملاً قابلاً للتنفيذ يوضح أيضًا كيفية **إنشاء خط في C#** باستخدام فئة .NET القياسية `Font`. + +التعامل مع الخطوط المخصصة جزء روتيني من بناء تطبيقات سطح المكتب على Windows، أو إنشاء ملفات PDF، أو عرض HTML على الخادم. بحلول نهاية هذا الدرس ستتمكن من إنشاء خط يكون عريضًا ومائلًا في آنٍ واحد، وتفهم لماذا يُستخدم العامل الثنائي `|`، وتتعامل مع الحالات الشائعة مثل عدم وجود عائلة الخط المطلوبة. + +## ما ستتعلمه + +* كيفية استيراد المساحات الاسمية المطلوبة لمعالجة الخطوط. +* صيغة دمج `FontStyle.Bold` و `FontStyle.Italic`. +* كيفية التحقق من أن الخط تم إنشاؤه بنجاح. +* نصائح للتعامل مع الحالات البديلة عندما لا تكون العائلة المطلوبة مثبتة. + +لا توجد مكتبات خارجية مطلوبة—كل شيء يستخدم مكتبة الفئات الأساسية لـ .NET Framework / .NET Core. + +## المتطلبات المسبقة + +* .NET 6.0 SDK أو أحدث (الكود يعمل أيضًا على .NET Framework 4.6+). +* محرر شفرة أو بيئة تطوير متكاملة (Visual Studio، VS Code، Rider، إلخ). +* إلمام أساسي بصياغة C#. + +إذا كنت تستوفي هذه المتطلبات، يمكنك متابعة الخطوات دون أي إعداد إضافي. + +## الخطوة 1: إضافة توجيهات `using` اللازمة + +فئة `Font` موجودة في مساحة الاسم `System.Drawing`، والتي هي جزء من حزمة NuGet `System.Drawing.Common` لـ .NET Core/.NET 5+. أضف مساحة الاسم في أعلى ملفك: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **لماذا هذه الخطوة مهمة** – بدون سطر `using System.Drawing;` لا يستطيع المترجم العثور على `Font` أو `FontStyle`، مما ينتج عنه خطأ “type or namespace name could not be found”. + +## الخطوة 2: دمج الأنماط العريضة والمائلة باستخدام عامل OR الثنائي + +في .NET، `FontStyle` هو تعداد (enum) مُعلَّم بصفة `[Flags]`. هذا يعني أنه يمكنك دمج قيم متعددة باستخدام العامل `|` (OR الثنائي): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### الشرح + +* `"Arial"` – اسم عائلة الخط. إذا لم يكن النظام يحتوي على Arial مثبتًا، فإن المُنشئ يلجأ إلى الخط الافتراضي. +* `12` – حجم النقطة. +* `FontStyle.Bold | FontStyle.Italic` – يجمع علمي النمطين. العامل `|` يدمج التمثيل الثنائي لكل علم، مُنتجًا قيمة واحدة تمثل “عريض + مائل”. + +> **نصيحة احترافية:** استخدم دائمًا أسماء التعداد (`FontStyle.Bold`) بدلًا من الأرقام السحرية؛ فهذا يحسّن قابلية القراءة ويمنع الأخطاء عندما تتغير قيم التعداد. + +## الخطوة 3: التحقق من الخط المُنشأ (اختياري لكن مُستحسن) + +طباعة خصائص الخط تساعدك على التأكد من أن دمج الأنماط نجح، خاصةً عند تصحيح الأخطاء على جهاز جديد. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**الناتج المتوقع** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +إذا كان الناتج يُظهر كلًا من `Bold` و `Italic`، فإن الخط تم إنشاؤه بشكل صحيح. + +## الخطوة 4: عرض سلسلة تجريبية (تأكيد بصري) + +عند تشغيل تطبيق كونسول لا يمكنك رؤية نمط الحروف فعليًا، لكن يمكنك إنشاء صورة لإثبات النتيجة. المقتطف التالي يرسم “Hello, World!” باستخدام الخط العريض‑المائل ويحفظه كملف *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +بعد تشغيل البرنامج، افتح *sample.png* لترى النص مُظهرًا بنمط الخط العريض المائل. + +![نص عينة مُظهر بخط عريض مائل](sample.png) + +*نص بديل للصورة: لقطة شاشة لنص مُظهر بخط Arial عريض مائل في نافذة كونسول C#* – هذا النص البديل يفي بمتطلبات تحسين محركات البحث للصور. + +## الخطوة 5: معالجة الفشل عند عدم توفر عائلة الخط + +إذا لم تكن العائلة المطلوبة (مثل “Arial”) مثبتة، فإن مُنشئ `Font` يرمي استثناءً من نوع `ArgumentException`. غلف عملية الإنشاء داخل كتلة `try/catch` واستخدم خطًا بديلًا معروفًا مثل “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**لماذا نتعامل مع هذا؟** في البيئات الحاوية أو بدون واجهة رسومية قد تختلف مجموعة الخطوط الافتراضية عن تلك الموجودة على سطح المكتب التقليدي. توفير بديل يمنع تعطل البرنامج في وقت التشغيل ويضمن تناسق النمط. + +## مثال كامل قابل للتنفيذ + +بدمج كل ما سبق، إليك برنامج كامل يمكنك نسخه، لصقه، وتشغيله: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### كيفية التشغيل + +1. احفظ الشفرة في ملف باسم `Program.cs`. +2. افتح طرفية في مجلد الملف. +3. نفّذ `dotnet new console -n FontDemo` (إذا كنت بحاجة إلى هيكل مشروع). +4. استبدل `Program.cs` المُولد بالشفرة أعلاه. +5. نفّذ `dotnet add package System.Drawing.Common` (مطلوب لـ .NET Core/5+). +6. ابنِ وشغّل باستخدام `dotnet run`. + +ستظهر لك مخرجات الكونسول التي تؤكد خصائص الخط، وسيظهر ملف `sample.png` في مجلد المشروع. + +## المشكلات الشائعة وكيفية تجنّبها + +| المشكلة | لماذا تحدث | الحل | +|---------|------------|------| +| **عدم وجود حزمة `System.Drawing.Common`** | .NET Core لا يتضمن `System.Drawing` بشكل افتراضي. | نفّذ `dotnet add package System.Drawing.Common`. | +| **عائلة الخط غير مثبتة** | صور Docker بدون واجهة رسومية غالبًا ما تفتقر إلى خطوط Windows. | استخدم خطًا بديلًا أو ثبّت الخطوط المطلوبة داخل الحاوية. | +| **استخدام غير صحيح لـ `|`** | استخدام `+` بدلًا من `|` ينتج عنه دمج غير صالح. | دائمًا دمج قيم `FontStyle` باستخدام عامل OR الثنائي (`|`). | +| **عدم تحرير كائن `Font`** | عدم استدعاء `Dispose` قد يتسبب في تسريب موارد GDI. | ضع `Font` داخل كتلة `using` أو استدعِ `font.Dispose()` بعد الانتهاء. | + +## الخلاصة + +أنت الآن تعرف كيف **تنشئ خطًا عريضًا مائلًا** في C# وكيف **تنشئ خطًا في C#** بطريقة آمنة وفعّالة. غطّى الدرس استيراد مساحة الاسم الصحيحة، دمج أعلام `FontStyle`، التحقق من النتيجة، عرض عينة بصرية، ومعالجة حالات عدم وجود عائلة الخط. + +الخطوات التالية التي قد تستكشفها: + +* **إنشاء خطوط مسطّرة أو مشطوبة** – أضف `FontStyle.Underline` أو `FontStyle.Strikeout`. +* **استخدام خطوط TrueType مخصصة** – حمّل ملف `.ttf` باستخدام `PrivateFontCollection`. +* **تطبيق الخطوط في WinForms أو WPF أو توليد PDF** – يمكن تمرير كائن `Font` نفسه إلى عناصر التحكم أو المكتبات الخارجية. + +لا تتردد في تجربة عائلات، أحجام، وتوليفات نمطية مختلفة. إذا واجهت مشاكل، راجع جدول “المشكلات الشائعة” أو تحقق من الوثائق الرسمية لـ [.NET documentation for System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). برمجة سعيدة! + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تُكمل التقنيات التي تم استعراضها في هذا الدليل. كل مصدر يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/arabic/net/working-with-html-documents/_index.md b/html/arabic/net/working-with-html-documents/_index.md index 30c32a306e..f0a7a458c5 100644 --- a/html/arabic/net/working-with-html-documents/_index.md +++ b/html/arabic/net/working-with-html-documents/_index.md @@ -37,8 +37,11 @@ url: /ar/net/working-with-html-documents/ الآن، دعنا ننتقل بمهاراتك إلى المستوى التالي. إن تحرير مستندات HTML مهمة شائعة بين مطوري الويب، ويعمل Aspose.HTML على تبسيط هذه العملية بشكل كبير. في هذا القسم، سنغطي إنشاء المستندات ومعالجتها وتصميمها. ستكتشف كيفية تحسين مظهر ووظائف محتوى الويب الخاص بك، مما يجعله جذابًا وسهل الاستخدام. ### [كيفية حفظ HTML في C# – دليل كامل باستخدام معالج موارد مخصص](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + ### [كيفية جعل العنوان غامقًا باستخدام CSS و C# – دليل خطوة بخطوة كامل](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [إنشاء معالج موارد مخصص في C# لتحميل HTML](./create-custom-resource-handler-in-c-for-html-loading/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/arabic/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/arabic/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..d62262b2de --- /dev/null +++ b/html/arabic/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-08-15 +description: إنشاء معالج موارد مخصص بلغة C# لإدارة موارد HTML مثل الصور وCSS. تعلّم + HTMLLoadOptions، تدفقات الذاكرة، وتحميل HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: ar +lastmod: 2026-08-15 +og_description: إنشاء معالج موارد مخصص في C# للتحكم في طريقة تدفق موارد HTML. يوضح + هذا الدرس إعداد HTMLLoadOptions، ومعالجة تدفق الذاكرة، وتحميل HTMLDocument بمنطق + مخصص. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: إنشاء معالج موارد مخصص في C# – دليل كامل لإدارة موارد HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: إنشاء معالج موارد مخصص في C# لتحميل HTML +url: /ar/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء معالج موارد مخصص في C# لتحميل HTML + +إذا كنت بحاجة إلى **إنشاء معالج موارد مخصص** لملفات HTML، فإن هذا الدليل يوضح لك الطريقة بالضبط. ستتعلم كيفية اعتراض الصور، CSS، وغيرها من الأصول أثناء تحميل مستند HTML، باستخدام `HTMLLoadOptions` وتدفق قائم على الذاكرة. + +يغطي الدرس كل ما يلزم لتنفيذ معالج قابل لإعادة الاستخدام، وتكوين خيارات التحميل، والتحقق من أن الموارد قد تم التقاطها بشكل صحيح. لا تحتاج إلى وثائق خارجية—فقط الشيفرة أدناه والشروحات. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث +- إلمام أساسي بـ C# +- مرجع لمكتبة معالجة HTML التي توفر `HTMLDocument`، `HtmlLoadOptions`، و `ResourceHandler` (مثل GroupDocs.Viewer for .NET) + +## نظرة عامة على الحل + +سنقوم بـ: + +1. **إنشاء معالج موارد مخصص** عن طريق وراثة `ResourceHandler`. +2. تكوين `HTMLLoadOptions` لاستخدام المعالج. +3. تحميل ملف HTML باستخدام `HTMLDocument` بينما يوفر المعالج تدفقًا لكل مورد. +4. (اختياري) حفظ الموارد المستلمة على القرص للتحقق منها. + +كل خطوة تتضمن الشيفرة الكاملة والسبب وراءها. + +## الخطوة 1: تعريف فئة معالج الموارد المخصص + +إنشاء معالج مخصص يعني تجاوز `HandleResource` حتى تتمكن المكتبة من كتابة بايتات المورد إلى تدفق تتحكم فيه. استخدام `MemoryStream` يبقي البيانات في الذاكرة، وهو مثالي للاختبار أو المعالجة اللاحقة. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**لماذا هذا مهم:** +تجاوز `HandleResource` يمنحك التحكم الكامل في مكان توجيه بيانات الموارد. إذا احتجت لاحقًا إلى تخزين الصور مؤقتًا، أو تحويل CSS، أو تسجيل استخدام الموارد، يمكنك استبدال `MemoryStream` بأي تنفيذ تدفق مخصص. + +## الخطوة 2: تكوين `HTMLLoadOptions` لاستخدام المعالج + +`HTMLLoadOptions` يتيح لك ربط المعالج بسلسلة تحميل المستند. ضبط خاصية `ResourceHandler` يخبر العارض باستدعاء `MyHandler` لكل أصل خارجي. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**لماذا هذا مهم:** +بدون تعيين `ResourceHandler`، سيكتب العارض الموارد إلى موقعه الافتراضي (غالبًا مجلد مؤقت). بتحديد معالجك الخاص، **تنشئ معالج موارد مخصص** يتماشى مع استراتيجية التخزين في تطبيقك. + +## الخطوة 3: تحميل مستند HTML باستخدام الخيارات المكوَّنة + +الآن قم بتحميل ملف HTML. سيستدعي العارض `MyHandler.HandleResource` لكل مورد يصادفه. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +في هذه المرحلة يتم تحليل محتوى HTML، وتُدفّق جميع الموارد الخارجية إلى مخازن الذاكرة التي يوفرها `MyHandler`. + +## الخطوة 4 (اختياري): الوصول إلى الموارد الملتقطة + +إذا كنت بحاجة إلى فحص أو حفظ الموارد، يمكنك تعديل `MyHandler` لتخزين كل `MemoryStream` في قاموس مفتاحه اسم المورد. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +بعد التحميل، يمكنك التجول عبر `handler.Resources` وكتابة كل منها إلى القرص: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**لماذا هذا مهم:** +تخزين الموارد يتيح المعالجة اللاحقة مثل تحسين الصور، تصغير CSS، أو الأرشفة. كما يوفر تحققًا ملموسًا من أن منطق **إنشاء معالج موارد مخصص** يعمل كما هو متوقع. + +## الخطوة 5: التنظيف + +يجب التخلص من كل من `HTMLDocument` وأي تدفقات لتفريغ الموارد غير المُدارة. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## مثال كامل قابل للتنفيذ + +فيما يلي برنامج مكتمل يوضح جميع الخطوات من تعريف الفئة إلى استخراج الموارد. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**الناتج المتوقع** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +تسرد وحدة التحكم كل مورد قام العارض بتدفقه عبر معالجك المخصص، مؤكدًا أن سير عمل **إنشاء معالج موارد مخصص** قد نجح. + +## أسئلة شائعة وحالات خاصة + +| السؤال | الجواب | +|----------|--------| +| *ماذا لو كان المورد كبيرًا (مثل صورة عالية الدقة)؟* | استبدل `MemoryStream` بـ `FileStream` يشير إلى مجلد مؤقت. هذا يمنع استهلاك الذاكرة بشكل مفرط. | +| *هل يمكنني تصفية الموارد حسب النوع؟* | داخل `HandleResource`، افحص `info.MimeType` أو `info.Extension` وأعد `null` للأنواع غير المرغوبة. إرجاع `null` يخبر العارض بتخطي المورد. | +| *هل يلزم ضمان أمان الخيوط (thread safety)؟* | إذا تم استخدام نفس نسخة المعالج عبر عمليات تحميل متزامنة متعددة، احمِ قاموس `Resources` باستخدام قفل أو استخدم مجموعة متزامنة. | +| *كيف أدعم عناوين URL النسبية؟* | يحتوي `ResourceInfo` على عنوان URL الأصلي؛ يمكنك دمجه مع المسار الأساسي لملف HTML لحل الإشارات النسبية قبل التخزين. | + +## الخلاصة + +أصبحت الآن تعرف كيف **تنشئ معالج موارد مخصص** في C# لتحميل HTML، وتُكوّن `HTMLLoadOptions`، وتلتقط الأصول المتدفقة، وتُنظف الموارد بشكل مسؤول. يتيح لك هذا النمط التحكم الكامل في إدارة الموارد، مما يفتح أمامك سيناريوهات مثل معالجة الصور أثناء التشغيل، إعادة كتابة CSS، أو التخزين الآمن. + +بعد ذلك، استكشف المواضيع ذات الصلة مثل **تحميل HTMLDocument** بخيارات عرض مختلفة، أو وسّع المعالج إلى تنفيذات **معالج موارد C#** التي تكتب مباشرة إلى التخزين السحابي. جرّب طريقة `HandleResource` لتتناسب مع سير عمل الموارد الخاص بمشروعك. + +## ماذا يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تُكمل التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/chinese/net/advanced-features/_index.md b/html/chinese/net/advanced-features/_index.md index 25b0274006..a844d46488 100644 --- a/html/chinese/net/advanced-features/_index.md +++ b/html/chinese/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Aspose.HTML for .NET 是一款功能强大的工具,允许开发人员以编 了解如何使用 Aspose.HTML for .NET 从 JSON 数据动态生成 HTML 文档。在您的 .NET 应用程序中充分利用 HTML 操作的强大功能。 ### [在 C# 中以编程方式合并字体 – 步骤指南](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) 了解如何使用 Aspose.HTML for .NET 在 C# 中合并字体文件,提供完整代码示例和操作步骤。 +### [在 C# 中创建粗斜体字体 – 步骤指南](./create-bold-italic-font-in-c-step-by-step-guide/) +了解如何在 C# 中使用 Aspose.HTML 创建粗斜体字体的步骤指南。 ## 结论 diff --git a/html/chinese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/chinese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..ccd0a1331e --- /dev/null +++ b/html/chinese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-08-15 +description: 快速在 C# 中创建粗斜体字体。了解如何使用内置的 Font 类在 C# 中创建带粗体和斜体样式的字体。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: zh +lastmod: 2026-08-15 +og_description: 在 C# 中创建粗斜体字体并提供清晰示例。本教程展示如何使用 FontStyle 标志在 C# 中创建字体,并解释常见的陷阱。 +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: 在 C# 中创建粗斜体字体 – 完整编码指南 +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: 在 C# 中创建粗斜体字体 – 步骤指南 +url: /zh/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建粗斜体字体 – 步骤指南 + +如果你需要在 C# 中 **创建粗斜体字体**,本指南将手把手教你如何实现。你将看到一个完整、可运行的示例,同时演示如何使用标准 .NET `Font` 类 **在 C# 中创建字体**。 + +在 Windows 桌面应用、生成 PDF 或在服务器端渲染 HTML 时,使用自定义字体是常见需求。阅读完本教程后,你将能够实例化既粗体又斜体的字体,理解为何使用位运算符 `|`,并处理如字体族缺失等常见边界情况。 + +## 你将学到 + +* 如何导入处理字体所需的命名空间。 +* `FontStyle.Bold` 与 `FontStyle.Italic` 的组合语法。 +* 如何验证字体是否成功创建。 +* 当请求的字体族未安装时的回退处理技巧。 + +无需外部库——全部使用 .NET Framework / .NET Core 基础类库。 + +## 前置条件 + +* .NET 6.0 SDK 或更高(代码同样适用于 .NET Framework 4.6+)。 +* 代码编辑器或 IDE(Visual Studio、VS Code、Rider 等)。 +* 基本的 C# 语法了解。 + +满足以上条件后,即可按步骤操作,无需额外配置。 + +## 步骤 1:添加必要的 using 指令 + +`Font` 类位于 `System.Drawing` 命名空间,它是 `System.Drawing.Common` NuGet 包在 .NET Core/.NET 5+ 中的组成部分。请在文件顶部加入该命名空间: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **为什么这一步重要** – 若缺少 `using System.Drawing;`,编译器将找不到 `Font` 或 `FontStyle`,导致 “type or namespace name could not be found” 错误。 + +## 步骤 2:使用位或运算符组合粗体和斜体样式 + +在 .NET 中,`FontStyle` 是标记了 `[Flags]` 特性的枚举。这意味着可以使用 `|`(位或)运算符合并多个值: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### 说明 + +* `"Arial"` – 字体族名称。如果系统未安装 Arial,构造函数会回退到默认字体。 +* `12` – 字号(磅)。 +* `FontStyle.Bold | FontStyle.Italic` – 将两个样式标志合并。`|` 运算符会把每个标志的二进制表示合并,生成表示 “粗体 + 斜体” 的单一值。 + +> **小技巧**:始终使用枚举名称(`FontStyle.Bold`)而非魔法数字;这样可提升可读性,并防止枚举值变动导致的 bug。 + +## 步骤 3:验证创建的字体(可选但推荐) + +打印字体属性可以帮助确认样式组合是否成功,尤其在新机器上调试时非常有用。 + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**预期输出** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +如果输出同时列出 `Bold` 和 `Italic`,说明字体已正确创建。 + +## 步骤 4:渲染示例字符串(可视化确认) + +在控制台应用中看不到实际字形样式,但可以生成图片来证明结果。下面的代码片段使用粗斜体字体绘制 “Hello, World!” 并保存为 *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +程序运行后,打开 *sample.png* 即可看到带有粗斜体样式的文本。 + +![Sample text rendered with bold italic font](sample.png) + +*图片替代文字:在 C# 控制台窗口中使用粗斜体 Arial 字体渲染的文本截图* – 该 alt 文本满足 SEO 要求。 + +## 步骤 5:当字体族不可用时的优雅回退 + +如果请求的字体族(例如 “Arial”)未安装,`Font` 构造函数会抛出 `ArgumentException`。请将创建代码放入 `try/catch` 块,并回退到已知安全的字体,如 “Segoe UI”。 + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**为何需要处理?** 在容器化或无头环境中,默认字体集合可能与普通桌面不同。提供回退可以防止运行时崩溃,确保样式一致。 + +## 完整可运行示例 + +将所有内容整合后,下面是一段可以直接复制、粘贴并运行的完整程序: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### 运行方式 + +1. 将代码保存为 `Program.cs`。 +2. 在文件所在目录打开终端。 +3. 执行 `dotnet new console -n FontDemo`(如需创建项目骨架)。 +4. 用上述代码替换生成的 `Program.cs`。 +5. 运行 `dotnet add package System.Drawing.Common`(.NET Core/5+ 必需)。 +6. 使用 `dotnet run` 构建并运行。 + +你将看到控制台输出的字体属性,并在项目文件夹中生成 `sample.png`。 + +## 常见陷阱及规避方法 + +| 陷阱 | 产生原因 | 解决方案 | +|------|----------|----------| +| **缺少 `System.Drawing.Common` 包** | .NET Core 默认不包含 `System.Drawing`。 | 运行 `dotnet add package System.Drawing.Common`。 | +| **字体族未安装** | 无头 Docker 镜像通常缺少 Windows 字体。 | 使用回退字体或在容器中安装所需字体。 | +| **错误使用 `|`** | 使用 `+` 而非 `|` 会导致无效组合。 | 始终使用位或运算符 (`|`) 合并 `FontStyle` 值。 | +| **未释放 `Font` 对象** | 不调用 `Dispose` 会泄漏 GDI 资源。 | 将 `Font` 包装在 `using` 块中,或在使用完后调用 `font.Dispose()`。 | + +## 结论 + +现在你已经掌握了在 C# 中 **创建粗斜体字体** 的方法,并能够安全、高效地 **在 C# 中创建字体**。本教程涵盖了导入正确命名空间、组合 `FontStyle` 标志、验证结果、渲染可视化示例以及处理缺失字体族的技巧。 + +接下来,你可以进一步探索: + +* **创建下划线或删除线字体** – 添加 `FontStyle.Underline` 或 `FontStyle.Strikeout`。 +* **使用自定义 TrueType 字体** – 通过 `PrivateFontCollection` 加载 `.ttf` 文件。 +* **在 WinForms、WPF 或 PDF 生成中使用字体** – 同一个 `Font` 对象即可传递给 UI 控件或第三方库。 + +尽情尝试不同的字体族、大小和样式组合吧。如遇问题,请回顾 “常见陷阱” 表格或查阅官方 [.NET 文档 for System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font)。祝编码愉快! + +## 接下来该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,提供完整的代码示例和逐步解释,帮助你掌握更多 API 功能并在项目中探索替代实现方案。 + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/chinese/net/working-with-html-documents/_index.md b/html/chinese/net/working-with-html-documents/_index.md index fcca91c844..6b1c0b3787 100644 --- a/html/chinese/net/working-with-html-documents/_index.md +++ b/html/chinese/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ HTML 文档是 Web 的支柱,能够有效地创建和操作 HTML 文档是任 现在,让我们将您的技能提升到一个新的水平。编辑 HTML 文档是 Web 开发人员的常见任务,而 Aspose.HTML 大大简化了此过程。在本节中,我们将介绍文档创建、操作和样式。您将了解如何增强 Web 内容的外观和功能,使其更具吸引力且用户友好。 ### [如何在 C# 中保存 HTML – 使用自定义资源处理程序的完整指南](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [在 C# 中创建用于 HTML 加载的自定义资源处理程序](./create-custom-resource-handler-in-c-for-html-loading/) + ### [使用 CSS 和 C# 加粗标题 – 完整分步指南](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/chinese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/chinese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..57a3e367f4 --- /dev/null +++ b/html/chinese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-08-15 +description: 在 C# 中创建自定义资源处理程序,以管理 HTML 资源(如图像和 CSS)。学习 HTMLLoadOptions、内存流以及 HTMLDocument + 的加载。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: zh +lastmod: 2026-08-15 +og_description: 在 C# 中创建自定义资源处理程序,以控制 HTML 资源的流式传输。本教程展示了 HTMLLoadOptions 的设置、内存流处理以及使用自定义逻辑加载 + HTMLDocument。 +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: 在 C# 中创建自定义资源处理程序 – HTML 资源管理完整指南 +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: 在 C# 中创建用于 HTML 加载的自定义资源处理程序 +url: /zh/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建用于 HTML 加载的自定义资源处理器 + +如果您需要 **创建自定义资源处理器** 来处理 HTML 文件,本指南将手把手教您如何实现。您将学习在加载 HTML 文档时拦截图像、CSS 以及其他资源,使用 `HTMLLoadOptions` 和基于内存的流。 + +本教程涵盖实现可复用处理器、配置加载选项以及验证资源是否被正确捕获的全部内容。无需外部文档——只需下面的代码和说明即可。 + +## 前提条件 + +- .NET 6.0 或更高版本 +- 基本的 C# 使用经验 +- 已引用提供 `HTMLDocument`、`HtmlLoadOptions` 和 `ResourceHandler` 的 HTML 处理库(例如 GroupDocs.Viewer for .NET) + +## 解决方案概览 + +我们将: + +1. 通过继承 `ResourceHandler` **创建自定义资源处理器**。 +2. 配置 `HTMLLoadOptions` 以使用该处理器。 +3. 使用 `HTMLDocument` 加载 HTML 文件,处理器为每个资源提供流。 +4. (可选)将接收到的资源保存到磁盘以进行验证。 + +每一步都包含完整的源代码及其背后的原理说明。 + +## 步骤 1:定义自定义资源处理器类 + +创建自定义处理器意味着重写 `HandleResource`,让库能够将资源字节写入您控制的流。使用 `MemoryStream` 可将数据保存在内存中,适合测试或后续处理。 + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**为什么重要:** +重写 `HandleResource` 让您完全掌控资源数据的去向。如果以后需要缓存图像、转换 CSS 或记录资源使用情况,只需将 `MemoryStream` 替换为任意自定义流实现即可。 + +## 步骤 2:配置 `HTMLLoadOptions` 使用该处理器 + +`HTMLLoadOptions` 允许您将处理器插入加载管道。设置 `ResourceHandler` 属性即可让查看器在遇到每个外部资源时调用 `MyHandler`。 + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**为什么重要:** +如果不分配 `ResourceHandler`,查看器会将资源写入默认位置(通常是临时文件夹)。通过指定自己的处理器,您 **创建自定义资源处理器** 的行为,从而符合应用的存储策略。 + +## 步骤 3:使用已配置的选项加载 HTML 文档 + +现在加载 HTML 文件。查看器会为每个遇到的资源调用 `MyHandler.HandleResource`。 + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +此时 HTML 内容已被解析,所有外部资源都已流入 `MyHandler` 提供的内存缓冲区。 + +## 步骤 4(可选):访问捕获的资源 + +如果需要检查或持久化资源,可以修改 `MyHandler`,将每个 `MemoryStream` 按资源名称存入字典。 + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +加载完成后,您可以遍历 `handler.Resources` 并将每个资源写入磁盘: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**为什么重要:** +存储资源可用于后处理,例如图像优化、CSS 压缩或归档。它还能直观验证 **create custom resource handler** 逻辑是否如预期工作。 + +## 步骤 5:清理 + +`HTMLDocument` 与任何流都应在使用完毕后释放,以释放非托管资源。 + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## 完整可运行示例 + +下面是一段自包含的程序,演示了从类定义到资源提取的全部步骤。 + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**预期输出** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +控制台会列出查看器通过您的自定义处理器流式传输的每个资源,确认 **create custom resource handler** 工作流已成功。 + +## 常见问题与边缘情况 + +| 问题 | 回答 | +|----------|--------| +| *如果资源很大(例如高分辨率图片)怎么办?* | 将 `MemoryStream` 替换为指向临时文件夹的 `FileStream`,以防止内存占用过高。 | +| *我可以按类型过滤资源吗?* | 在 `HandleResource` 中检查 `info.MimeType` 或 `info.Extension`,对不需要的类型返回 `null`。返回 `null` 会让查看器跳过该资源。 | +| *是否需要线程安全?* | 如果同一处理器实例在多个并发加载中使用,请使用锁保护 `Resources` 字典,或改用并发集合。 | +| *如何支持相对 URL?* | `ResourceInfo` 包含原始 URL,您可以将其与 HTML 文件的基路径组合,以在存储前解析相对引用。 | + +## 结论 + +现在您已经掌握了在 C# 中 **创建自定义资源处理器** 以加载 HTML、配置 `HTMLLoadOptions`、捕获流式资源并负责任地进行清理的完整方法。此模式让您对资源管理拥有完整控制,可用于实时图像处理、CSS 重写或安全存储等场景。 + +接下来,您可以进一步探索 **HTMLDocument 加载** 的不同渲染选项,或扩展处理器实现 **C# resource handler**,直接写入云存储。尝试自定义 `HandleResource` 方法,以匹配项目的特定资源工作流。 + +## 接下来您应该学习什么? + +以下教程与本指南所示技术密切相关,帮助您进一步掌握 API 功能并探索替代实现方式。 + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/czech/net/advanced-features/_index.md b/html/czech/net/advanced-features/_index.md index 4910caec07..60185b4d02 100644 --- a/html/czech/net/advanced-features/_index.md +++ b/html/czech/net/advanced-features/_index.md @@ -44,7 +44,8 @@ Naučte se převádět HTML do PDF, XPS a obrázků pomocí Aspose.HTML pro .NET Naučte se používat Aspose.HTML pro .NET k dynamickému generování HTML dokumentů z dat JSON. Využijte sílu manipulace s HTML ve svých aplikacích .NET. ### [Vytvořte paměťový stream v C# – Průvodce tvorbou vlastního streamu](./create-memory-stream-c-custom-stream-creation-guide/) Naučte se, jak vytvořit vlastní paměťový stream v C# pomocí Aspose.HTML a efektivně manipulovat s HTML dokumenty. - +### [Vytvořte tučné kurzívní písmo v C# – krok za krokem](./create-bold-italic-font-in-c-step-by-step-guide/) +Naučte se, jak pomocí Aspose.HTML v C# vytvořit text s tučným a kurzívním stylem. ## Závěr diff --git a/html/czech/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/czech/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..2d0e19208f --- /dev/null +++ b/html/czech/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-08-15 +description: Rychle vytvořte tučný kurzívní font v C#. Naučte se, jak vytvořit font + v C# s tučným a kurzívním stylem pomocí vestavěné třídy Font. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: cs +lastmod: 2026-08-15 +og_description: Vytvořte tučný kurzívní font v C# s jasným příkladem. Tento tutoriál + ukazuje, jak vytvořit font v C# pomocí příznaků FontStyle a vysvětluje běžné úskalí. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Vytvořte tučný kurzívní font v C# – kompletní průvodce programováním +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Vytvořte tučné kurzívní písmo v C# – krok za krokem průvodce +url: /cs/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření tučného kurzívy písma v C# – krok za krokem průvodce + +Pokud potřebujete **vytvořit tučné kurzívní písmo** v C#, tento průvodce vám přesně ukáže, jak na to. Uvidíte kompletní, spustitelný příklad, který také demonstruje, jak **vytvořit písmo v C#** pomocí standardní třídy .NET `Font`. + +Práce s vlastním písmem je běžnou součástí tvorby Windows desktop aplikací, generování PDF nebo renderování HTML na serveru. Na konci tohoto tutoriálu budete schopni vytvořit instanci písma, které je zároveň tučné i kurzívní, pochopit, proč se používá bitový operátor `|`, a řešit běžné okrajové případy, jako jsou chybějící rodiny písem. + +## Co se naučíte + +* Jak importovat požadované jmenné prostory pro práci s písmy. +* Syntaxe pro kombinaci `FontStyle.Bold` a `FontStyle.Italic`. +* Jak ověřit, že písmo bylo úspěšně vytvořeno. +* Tipy pro zpracování náhrad, když požadovaná rodina není nainstalována. + +Není potřeba žádná externí knihovna – vše používá základní knihovnu tříd .NET Framework / .NET Core. + +## Požadavky + +* .NET 6.0 SDK nebo novější (kód také funguje na .NET Framework 4.6+). +* Editor kódu nebo IDE (Visual Studio, VS Code, Rider, atd.). +* Základní znalost syntaxe C#. + +Pokud splňujete tyto požadavky, můžete postupovat podle kroků bez dalšího nastavení. + +## Krok 1: Přidejte potřebné using direktivy + +Třída `Font` se nachází v jmenném prostoru `System.Drawing`, který je součástí NuGet balíčku `System.Drawing.Common` pro .NET Core/.NET 5+. Přidejte jmenný prostor na začátek souboru: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Proč je tento krok důležitý** – Bez řádku `using System.Drawing;` kompilátor nemůže najít `Font` ani `FontStyle`, což vede k chybě „type or namespace name could not be found“. + +## Krok 2: Kombinujte tučné a kurzívní styly pomocí bitového OR operátoru + +V .NET je `FontStyle` výčtový typ označený atributem `[Flags]`. To znamená, že můžete kombinovat více hodnot pomocí operátoru `|` (bitový OR): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Vysvětlení + +* `"Arial"` – název rodiny písma. Pokud systém nemá nainstalováno Arial, konstruktor přejde na výchozí písmo. +* `12` – velikost v bodech. +* `FontStyle.Bold | FontStyle.Italic` – kombinuje dva stylové příznaky. Operátor `|` sloučí binární reprezentaci každého příznaku a vytvoří jedinou hodnotu představující „tučné + kurzívní“. + +> **Tip:** Vždy používejte názvy výčtových typů (`FontStyle.Bold`) místo magických čísel; zvyšuje to čitelnost a zabraňuje chybám, když se hodnoty výčtu změní. + +## Krok 3: Ověřte vytvořené písmo (volitelné, ale doporučené) + +Vytištění vlastností písma vám pomůže potvrdit, že kombinace stylů byla úspěšná, zejména při ladění na novém počítači. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Očekávaný výstup** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Pokud výstup obsahuje jak `Bold`, tak `Italic`, písmo bylo vytvořeno správně. + +## Krok 4: Vykreslete ukázkový řetězec (vizuální potvrzení) + +Když spustíte konzolovou aplikaci, nevidíte skutečné stylování glyfů, ale můžete vygenerovat obrázek, který výsledek dokáže. Následující úryvek vykreslí „Hello, World!“ pomocí tučně‑kurzívního písma a uloží jej jako *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Po spuštění programu otevřete *sample.png*, abyste viděli text vykreslený s tučným kurzívním stylem. + +![Ukázkový text vykreslený tučným kurzívním písmem](sample.png) + +*Text alt obrázku: Screenshot textu vykresleného tučným kurzívním písmem Arial v C# konzolovém okně* – tento alt text splňuje SEO požadavek na alt text obrázku. + +## Krok 5: Elegantní náhrada, když není rodina písma dostupná + +Pokud požadovaná rodina (např. „Arial“) není nainstalována, konstruktor `Font` vyhodí `ArgumentException`. Zabalte vytvoření do bloku `try/catch` a přejděte na známé bezpečné písmo, jako je „Segoe UI“. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Proč to řešit?** +V kontejnerizovaných nebo bezhlavých prostředích se výchozí sada písem může lišit od typického desktopu. Poskytnutí náhrady zabraňuje pádům během běhu a zajišťuje konzistentní stylování. + +## Kompletní, spustitelný příklad + +Spojením všech částí zde máte kompletní program, který můžete zkopírovat, vložit a spustit: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Jak spustit + +1. Uložte kód do souboru s názvem `Program.cs`. +2. Otevřete terminál ve složce souboru. +3. Spusťte `dotnet new console -n FontDemo` (pokud potřebujete kostru projektu). +4. Nahraďte vygenerovaný `Program.cs` kódem výše. +5. Spusťte `dotnet add package System.Drawing.Common` (vyžadováno pro .NET Core/5+). +6. Sestavte a spusťte pomocí `dotnet run`. + +Uvidíte výstup v konzoli potvrzující vlastnosti písma a `sample.png` se objeví ve složce projektu. + +## Časté úskalí a jak se jim vyhnout + +| Problém | Proč k tomu dochází | Oprava | +|---------|---------------------|--------| +| **Chybějící balíček `System.Drawing.Common`** | .NET Core ve výchozím nastavení neobsahuje `System.Drawing`. | Spusťte `dotnet add package System.Drawing.Common`. | +| **Rodina písma není nainstalována** | Headless Docker obrazy často postrádají Windows písma. | Použijte náhradní písmo nebo nainstalujte požadovaná písma v kontejneru. | +| **Nesprávné použití `|`** | Použití `+` místo `|` vede k neplatné kombinaci. | Vždy kombinujte hodnoty `FontStyle` pomocí bitového OR operátoru (`|`). | +| **Uvolňování objektu `Font`** | Nepoužití `Dispose` může způsobit únik GDI zdrojů. | Zabalte `Font` do bloku `using` nebo zavolejte `font.Dispose()` po dokončení. | + +## Závěr + +Nyní víte, jak **vytvořit tučné kurzívní písmo** v C# a jak **vytvořit písmo v C#** bezpečně a efektivně. Tutoriál pokryl import správného jmenného prostoru, kombinaci příznaků `FontStyle`, ověření výsledku, vykreslení vizuálního vzorku a zpracování chybějících rodin písem. + +Dále můžete zkoumat: + +* **Vytváření podtržených nebo přeškrtnutých písem** – přidejte `FontStyle.Underline` nebo `FontStyle.Strikeout`. +* **Používání vlastních TrueType písem** – načtěte soubor `.ttf` pomocí `PrivateFontCollection`. +* **Použití písem ve WinForms, WPF nebo generování PDF** – stejný objekt `Font` může být předán UI kontrolám nebo knihovnám třetích stran. + +Neváhejte experimentovat s různými rodinami, velikostmi a kombinacemi stylů. Pokud narazíte na problémy, podívejte se znovu na tabulku „Časté úskalí“ nebo zkontrolujte oficiální [.NET dokumentaci pro System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Šťastné kódová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 průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s krok‑za‑krokem vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/czech/net/working-with-html-documents/_index.md b/html/czech/net/working-with-html-documents/_index.md index c00dc46971..dcbd4cfff0 100644 --- a/html/czech/net/working-with-html-documents/_index.md +++ b/html/czech/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ Nyní posuňte vaše dovednosti na další úroveň. Úpravy HTML dokumentů jso ### [Jak uložit HTML v C# – Kompletní průvodce pomocí vlastního resource handleru](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [Jak zvýraznit nadpis tučným písmem pomocí CSS a C# – Kompletní průvodce krok za krokem](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Vytvořit vlastní resource handler v C# pro načítání HTML](./create-custom-resource-handler-in-c-for-html-loading/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/czech/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/czech/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..e3d0cbcc1e --- /dev/null +++ b/html/czech/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-08-15 +description: Vytvořte vlastní obslužný program zdrojů v C# pro správu HTML zdrojů, + jako jsou obrázky a CSS. Naučte se HTMLLoadOptions, paměťové proudy a načítání HTMLDocumentu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: cs +lastmod: 2026-08-15 +og_description: Vytvořte vlastní obslužný program zdrojů v C# pro řízení způsobu streamování + HTML zdrojů. Tento tutoriál ukazuje nastavení HTMLLoadOptions, práci s paměťovým + streamem a načítání HTMLDocument s vlastní logikou. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Vytvořte vlastní manipulátor zdrojů v C# – kompletní průvodce správou HTML + zdrojů +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Vytvořte vlastní obslužný program zdrojů v C# pro načítání HTML +url: /cs/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvořte vlastní manipulátor zdrojů v C# pro načítání HTML + +Pokud potřebujete **vytvořit vlastní manipulátor zdrojů** pro soubory HTML, tento průvodce vám přesně ukáže, jak na to. Naučíte se zachytávat obrázky, CSS a další aktiva při načítání HTML dokumentu pomocí `HTMLLoadOptions` a paměťového proudu. + +Tutoriál pokrývá vše potřebné k implementaci znovupoužitelného manipulátoru, nastavení možností načítání a ověření, že zdroje jsou zachyceny správně. Není potřeba žádná externí dokumentace – stačí kód níže a vysvětlení. + +## Požadavky + +- .NET 6.0 nebo novější +- Základní znalost C# +- Odkaz na knihovnu pro zpracování HTML, která poskytuje `HTMLDocument`, `HtmlLoadOptions` a `ResourceHandler` (např. GroupDocs.Viewer pro .NET) + +## Přehled řešení + +Budeme: + +1. **Vytvořit vlastní manipulátor zdrojů** podtříděním `ResourceHandler`. +2. Nastavit `HTMLLoadOptions` tak, aby používal manipulátor. +3. Načíst soubor HTML pomocí `HTMLDocument`, zatímco manipulátor poskytuje proud pro každý zdroj. +4. (Volitelné) Uložit získané zdroje na disk pro ověření. + +Každý krok obsahuje kompletní zdrojový kód a odůvodnění. + +## Krok 1: Definujte třídu vlastního manipulátoru zdrojů + +Vytvoření vlastního manipulátoru znamená přepsání metody `HandleResource`, aby knihovna mohla zapisovat bajty zdroje do proudu, který ovládáte. Použití `MemoryStream` udržuje data v paměti, což je ideální pro testování nebo další zpracování. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Proč je to důležité:** +Přepsání `HandleResource` vám dává úplnou kontrolu nad tím, kam data zdroje směřují. Pokud později potřebujete kešovat obrázky, transformovat CSS nebo logovat využití zdrojů, můžete `MemoryStream` nahradit libovolnou vlastní implementací proudu. + +## Krok 2: Nastavte `HTMLLoadOptions` pro použití manipulátoru + +`HTMLLoadOptions` vám umožňuje připojit manipulátor do načítacího řetězce. Nastavením vlastnosti `ResourceHandler` řeknete prohlížeči, aby volal `MyHandler` pro každý externí asset. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Proč je to důležité:** +Bez přiřazení `ResourceHandler` by prohlížeč zapisoval zdroje do výchozího umístění (často do dočasné složky). Specifikací vlastního manipulátoru **vytvoříte vlastní manipulátor zdrojů**, který odpovídá strategii ukládání vaší aplikace. + +## Krok 3: Načtěte HTML dokument s nakonfigurovanými možnostmi + +Nyní načtěte soubor HTML. Prohlížeč zavolá `MyHandler.HandleResource` pro každý zdroj, na který narazí. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +V tomto okamžiku je HTML obsah parsován a všechny externí zdroje byly streamovány do paměťových bufferů poskytnutých `MyHandler`. + +## Krok 4 (volitelné): Přístup k zachyceným zdrojům + +Pokud potřebujete zdroje prohlédnout nebo uložit, můžete upravit `MyHandler`, aby ukládal každý `MemoryStream` do slovníku s klíčem podle názvu zdroje. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Po načtení můžete iterovat přes `handler.Resources` a každý zapsat na disk: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Proč je to důležité:** +Ukládání zdrojů umožňuje následné zpracování, jako je optimalizace obrázků, minifikace CSS nebo archivace. Také poskytuje hmatatelné ověření, že logika **vytvořit vlastní manipulátor zdrojů** funguje podle očekávání. + +## Krok 5: Vyčištění + +Jak `HTMLDocument`, tak i všechny proudy by měly být uvolněny (disposed), aby se uvolnily neřízené zdroje. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Kompletní spustitelný příklad + +Níže je samostatný program, který demonstruje všechny kroky od definice třídy po extrakci zdrojů. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Očekávaný výstup** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Konzole vypíše každý zdroj, který prohlížeč streamoval přes váš vlastní manipulátor, což potvrzuje, že workflow **vytvořit vlastní manipulátor zdrojů** byl úspěšný. + +## Časté otázky a okrajové případy + +| Otázka | Odpověď | +|----------|--------| +| *Co když je zdroj velký (např. obrázek s vysokým rozlišením)?* | Nahraďte `MemoryStream` `FileStream`, který ukazuje na dočasnou složku. Tím se zabrání nadměrné spotřebě paměti. | +| *Mohu filtrovat zdroje podle typu?* | Uvnitř `HandleResource` zkontrolujte `info.MimeType` nebo `info.Extension` a vraťte `null` pro nechtěné typy. Vrácení `null` řekne prohlížeči, aby zdroj přeskočil. | +| *Je vyžadována bezpečnost vláken?* | Pokud je stejná instance manipulátoru používána při více souběžných načítáních, chraňte slovník `Resources` pomocí zámku nebo použijte souběžnou kolekci. | +| *Jak podpořit relativní URL?* | `ResourceInfo` obsahuje původní URL; můžete jej kombinovat se základní cestou HTML souboru k vyřešení relativních odkazů před uložením. | + +## Závěr + +Nyní víte, jak **vytvořit vlastní manipulátor zdrojů** v C# pro načítání HTML, nakonfigurovat `HTMLLoadOptions`, zachytit streamované assety a odpovědně uvolnit prostředky. Tento vzor vám dává plnou kontrolu nad správou zdrojů, umožňující scénáře jako zpracování obrázků za běhu, přepisování CSS nebo bezpečné ukládání. + +Dále prozkoumejte související témata jako **načítání HTMLDocument** s různými možnostmi renderování, nebo rozšiřte manipulátor na implementace **C# resource handler**, které zapisují přímo do cloudového úložiště. Experimentujte s metodou `HandleResource` manipulátoru, aby odpovídala specifickému workflow zdrojů ve vašem projektu. + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční příklady 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. + +- [Vytvořit HTML ze stringu v C# – Průvodce vlastním manipulátorem zdrojů](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Vlastní manipulátor zdrojů v C# – Tutoriál převodu HTML do ZIP](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [Jak uložit HTML v C# – Kompletní průvodce s použitím vlastního manipulátoru zdrojů](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/dutch/net/advanced-features/_index.md b/html/dutch/net/advanced-features/_index.md index 5fe1ed4d29..f9e65c22d0 100644 --- a/html/dutch/net/advanced-features/_index.md +++ b/html/dutch/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Leer hoe u HTML naar PDF, XPS en afbeeldingen converteert met Aspose.HTML voor . Leer hoe u Aspose.HTML voor .NET kunt gebruiken om dynamisch HTML-documenten te genereren uit JSON-gegevens. Benut de kracht van HTML-manipulatie in uw .NET-toepassingen. ### [Lettertypen combineren via code in C# – Stapsgewijze handleiding](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Leer hoe u lettertypen programmatically combineert in C# met Aspose.HTML, inclusief voorbeeldcode en stapsgewijze instructies. +### [Maak vet cursief lettertype in C# – stapsgewijze handleiding](./create-bold-italic-font-in-c-step-by-step-guide/) +Leer hoe u een vet cursief lettertype maakt in C# met Aspose.HTML, stap voor stap. ## Conclusie diff --git a/html/dutch/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/dutch/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..9d0055ca82 --- /dev/null +++ b/html/dutch/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-08-15 +description: Maak snel een vet‑cursief lettertype in C#. Leer hoe je een lettertype + in C# maakt met vet‑ en cursief‑stijlen met behulp van de ingebouwde Font‑klasse. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: nl +lastmod: 2026-08-15 +og_description: Maak een vet cursief lettertype in C# met een duidelijk voorbeeld. + Deze tutorial laat zien hoe je een lettertype maakt in C# met behulp van FontStyle‑vlaggen + en legt veelvoorkomende valkuilen uit. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Maak een vet cursief lettertype in C# – volledige programmeergids +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Maak een vet‑cursief lettertype in C# – stapsgewijze handleiding +url: /nl/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vet cursief lettertype maken in C# – stapsgewijze gids + +Als je **vet cursief lettertype wilt maken** in C#, laat deze gids je precies zien hoe je dat doet. Je ziet een volledig, uitvoerbaar voorbeeld dat ook laat zien hoe je **lettertype maakt in C#** met de standaard .NET `Font`-klasse. + +Werken met aangepaste lettertypen is een routineonderdeel van het bouwen van Windows desktop‑apps, het genereren van PDF’s of het renderen van HTML op de server. Aan het einde van deze tutorial kun je een lettertype instantiëren dat zowel vet als cursief is, begrijp je waarom de bitwise `|`‑operator wordt gebruikt, en kun je veelvoorkomende randgevallen afhandelen, zoals ontbrekende lettertypefamilies. + +Er zijn geen externe bibliotheken nodig — alles maakt gebruik van de .NET Framework / .NET Core basis‑class‑library. + +## Wat je zult leren + +* Hoe je de benodigde namespaces voor lettertype‑verwerking importeert. +* De syntaxis om `FontStyle.Bold` en `FontStyle.Italic` te combineren. +* Hoe je verifieert dat het lettertype succesvol is aangemaakt. +* Tips voor fallback‑afhandeling wanneer de gevraagde familie niet geïnstalleerd is. + +Er zijn geen externe bibliotheken nodig — alles maakt gebruik van de .NET Framework / .NET Core basis‑class‑library. + +## Vereisten + +* .NET 6.0 SDK of later (de code werkt ook op .NET Framework 4.6+). +* Een code‑editor of IDE (Visual Studio, VS Code, Rider, enz.). +* Basiskennis van C#‑syntaxis. + +Als je aan deze vereisten voldoet, kun je de stappen volgen zonder extra configuratie. + +## Stap 1: Voeg de benodigde using‑directieven toe + +De `Font`‑klasse bevindt zich in de `System.Drawing`‑namespace, die deel uitmaakt van het `System.Drawing.Common`‑NuGet‑pakket voor .NET Core/.NET 5+. Voeg de namespace toe aan de bovenkant van je bestand: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Waarom deze stap belangrijk is** – Zonder de regel `using System.Drawing;` kan de compiler `Font` of `FontStyle` niet vinden, wat resulteert in een “type or namespace name could not be found”‑fout. + +## Stap 2: Combineer vet en cursief stijlen met de bitwise OR‑operator + +In .NET is `FontStyle` een enum gemarkeerd met het `[Flags]`‑attribuut. Dit betekent dat je meerdere waarden kunt combineren met de `|` (bitwise OR)‑operator: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Uitleg + +* `\"Arial\"` – de naam van de lettertypefamilie. Als het systeem Arial niet geïnstalleerd heeft, valt de constructor terug op het standaardlettertype. +* `12` – puntgrootte. +* `FontStyle.Bold | FontStyle.Italic` – combineert de twee stijl‑flags. De `|`‑operator voegt de binaire representatie van elke flag samen, waardoor een enkele waarde ontstaat die “vet + cursief” vertegenwoordigt. + +> **Pro tip:** Gebruik altijd de enum‑namen (`FontStyle.Bold`) in plaats van magische getallen; dit verbetert de leesbaarheid en voorkomt bugs wanneer de enum‑waarden veranderen. + +## Stap 3: Verifieer het aangemaakte lettertype (optioneel maar aanbevolen) + +Het afdrukken van de eigenschappen van het lettertype helpt je te bevestigen dat de stijlcombinatie geslaagd is, vooral bij het debuggen op een nieuwe machine. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Verwachte output** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Als de output zowel `Bold` als `Italic` vermeldt, is het lettertype correct aangemaakt. + +## Stap 4: Render een voorbeeldstring (visuele bevestiging) + +Wanneer je een console‑app uitvoert kun je de daadwerkelijke glyph‑styling niet zien, maar je kunt een afbeelding genereren om het resultaat te bewijzen. Het volgende fragment tekent “Hello, World!” met het vet‑cursieve lettertype en slaat het op als *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Na het uitvoeren van het programma, open *sample.png* om de tekst te zien die is gerenderd met de vet‑cursieve stijl. + +![Voorbeeldtekst gerenderd met vet cursief lettertype](sample.png) + +*Afbeeldings‑alt‑tekst: Screenshot van tekst gerenderd met een vet‑cursief Arial‑lettertype in een C#‑console‑venster* – deze alt‑tekst voldoet aan de SEO‑vereiste voor afbeeldings‑alt‑tekst. + +## Stap 5: Elegante fallback wanneer de lettertypefamilie niet beschikbaar is + +Als de gevraagde familie (bijv. “Arial”) niet geïnstalleerd is, gooit de `Font`‑constructor een `ArgumentException`. Plaats de creatie in een `try/catch`‑blok en val terug op een bekend veilig lettertype zoals “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Waarom dit afhandelen?** In gecontaineriseerde of headless omgevingen kan de standaardset lettertypen verschillen van een typische desktop. Het bieden van een fallback voorkomt runtime‑crashes en zorgt voor consistente styling. + +## Volledig, uitvoerbaar voorbeeld + +Alles samengevoegd, hier is een compleet programma dat je kunt kopiëren, plakken en uitvoeren: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Hoe uit te voeren + +1. Sla de code op in een bestand met de naam `Program.cs`. +2. Open een terminal in de map van het bestand. +3. Voer `dotnet new console -n FontDemo` uit (als je een project‑scaffold nodig hebt). +4. Vervang de gegenereerde `Program.cs` door de bovenstaande code. +5. Voer `dotnet add package System.Drawing.Common` uit (vereist voor .NET Core/5+). +6. Bouw en voer uit met `dotnet run`. + +Je ziet de console‑output die de lettertype‑eigenschappen bevestigt, en `sample.png` verschijnt in de projectmap. + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +| Valkuil | Waarom het gebeurt | Oplossing | +|---------|--------------------|-----------| +| **Ontbrekend `System.Drawing.Common`‑pakket** | .NET Core bevat `System.Drawing` niet standaard. | Voer `dotnet add package System.Drawing.Common` uit. | +| **Lettertypefamilie niet geïnstalleerd** | Headless Docker‑images missen vaak Windows‑lettertypen. | Gebruik een fallback‑lettertype of installeer de benodigde lettertypen in de container. | +| **Onjuiste gebruik van `|`** | Het gebruiken van `+` in plaats van `|` leidt tot een ongeldige combinatie. | Combineer `FontStyle`‑waarden altijd met de bitwise OR‑operator (`|`). | +| **Het `Font`‑object niet vrijgeven** | Het niet aanroepen van `Dispose` kan GDI‑bronnen lekken. | Plaats `Font` in een `using`‑blok of roep `font.Dispose()` aan nadat je klaar bent. | + +## Conclusie + +Je weet nu hoe je **vet cursief lettertype kunt maken** in C# en hoe je **lettertype maakt in C#** veilig en efficiënt. De tutorial behandelde het importeren van de juiste namespace, het combineren van `FontStyle`‑flags, het verifiëren van het resultaat, het renderen van een visueel voorbeeld, en het afhandelen van ontbrekende lettertypefamilies. + +Vervolgens kun je verkennen: + +* **Onderstreepte of doorgestreepte lettertypen maken** – voeg `FontStyle.Underline` of `FontStyle.Strikeout` toe. +* **Aangepaste TrueType‑lettertypen gebruiken** – laad een `.ttf`‑bestand met `PrivateFontCollection`. +* **Lettertypen toepassen in WinForms, WPF of PDF‑generatie** – hetzelfde `Font`‑object kan worden doorgegeven aan UI‑controls of externe bibliotheken. + +Voel je vrij om te experimenteren met verschillende families, groottes en stijlcombinaties. Als je problemen tegenkomt, raadpleeg dan opnieuw de tabel “Veelvoorkomende valkuilen” of bekijk de officiële [.NET‑documentatie voor System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Veel programmeerplezier! + +## 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 complete werkende code‑voorbeelden met stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe je lettertypen programmatically combineert in C# – stapsgewijze gids](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [HTML‑document maken met opgemaakte tekst en exporteren naar PDF – volledige gids](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [docx naar png converteren – zip‑archief maken c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/dutch/net/working-with-html-documents/_index.md b/html/dutch/net/working-with-html-documents/_index.md index 36eb73e4af..d39483494d 100644 --- a/html/dutch/net/working-with-html-documents/_index.md +++ b/html/dutch/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ Zodra u de basis onder de knie hebt, gaan we dieper in op het creatieproces. In Laten we nu uw vaardigheden naar een hoger niveau tillen. Het bewerken van HTML-documenten is een veelvoorkomende taak voor webontwikkelaars, en Aspose.HTML vereenvoudigt dit proces aanzienlijk. In deze sectie behandelen we het maken, manipuleren en stylen van documenten. U ontdekt hoe u het uiterlijk en de functionaliteit van uw webcontent kunt verbeteren, waardoor deze aantrekkelijk en gebruiksvriendelijk wordt. ### [HTML opslaan in C# – Complete gids met een aangepaste resourcehandler](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [Aangepaste resourcehandler maken in C# voor HTML laden](./create-custom-resource-handler-in-c-for-html-loading/) + ### [Koptekst vet maken met CSS & C# – Complete stapsgewijze handleiding](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) Leer hoe u met CSS en C# kopteksten vet maakt in een .NET‑applicatie, stap voor stap met voorbeeldcode. diff --git a/html/dutch/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/dutch/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..a32630bb92 --- /dev/null +++ b/html/dutch/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-08-15 +description: Maak een aangepaste resourcehandler in C# om HTML‑resources zoals afbeeldingen + en CSS te beheren. Leer HTMLLoadOptions, geheugenstromen en het laden van HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: nl +lastmod: 2026-08-15 +og_description: Maak een aangepaste resourcehandler in C# om te bepalen hoe HTML‑resources + worden gestreamd. Deze tutorial toont de configuratie van HTMLLoadOptions, het omgaan + met geheugenstreams en het laden van HTMLDocument met aangepaste logica. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Maak een aangepaste resourcehandler in C# – volledige gids voor HTML‑resourcebeheer +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Maak een aangepaste resourcehandler in C# voor het laden van HTML +url: /nl/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak aangepaste resourcehandler in C# voor HTML laden + +Als je **create custom resource handler** voor HTML‑bestanden moet maken, laat deze gids je precies zien hoe. Je leert afbeeldingen, CSS en andere assets te onderscheppen tijdens het laden van een HTML‑document, met behulp van `HTMLLoadOptions` en een geheugen‑gebaseerde stream. + +De tutorial behandelt alles wat nodig is om een herbruikbare handler te implementeren, laadopties te configureren en te verifiëren dat resources correct worden vastgelegd. Er is geen externe documentatie nodig—alleen de onderstaande code en de uitleg. + +## Vereisten + +- .NET 6.0 of later +- Basiskennis van C# +- Een referentie naar de HTML‑verwerkingsbibliotheek die `HTMLDocument`, `HtmlLoadOptions` en `ResourceHandler` levert (bijv. GroupDocs.Viewer voor .NET) + +## Overzicht van de oplossing + +We zullen: + +1. **Create a custom resource handler** door `ResourceHandler` te subklassen. +2. Configure `HTMLLoadOptions` om de handler te gebruiken. +3. Laad een HTML‑bestand met `HTMLDocument` terwijl de handler een stream levert voor elke resource. +4. (Optioneel) Sla ontvangen resources op schijf voor verificatie. + +Elke stap bevat volledige broncode en de reden erachter. + +## Stap 1: Definieer de custom resource handler‑klasse + +Een custom handler maken betekent dat je `HandleResource` overschrijft zodat de bibliotheek resource‑bytes naar een door jou beheerde stream kan schrijven. Het gebruik van een `MemoryStream` houdt de gegevens in het geheugen, wat ideaal is voor testen of verdere verwerking. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Waarom dit belangrijk is:** +Het overschrijven van `HandleResource` geeft je volledige controle over waar resource‑data naartoe gaat. Als je later afbeeldingen wilt cachen, CSS wilt transformeren of resource‑gebruik wilt loggen, kun je de `MemoryStream` vervangen door een willekeurige custom stream‑implementatie. + +## Stap 2: Configure `HTMLLoadOptions` om de handler te gebruiken + +`HTMLLoadOptions` stelt je in staat de handler in de laad‑pipeline te koppelen. Het instellen van de eigenschap `ResourceHandler` vertelt de viewer om `MyHandler` aan te roepen voor elk extern asset. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Waarom dit belangrijk is:** +Zonder het toewijzen van `ResourceHandler` zou de viewer resources naar de standaardlocatie schrijven (meestal een tijdelijke map). Door je eigen handler op te geven, creëer je **custom resource handler**‑gedrag dat aansluit bij de opslagstrategie van je applicatie. + +## Stap 3: Laad het HTML‑document met de geconfigureerde opties + +Laad nu het HTML‑bestand. De viewer zal `MyHandler.HandleResource` aanroepen voor elke resource die het tegenkomt. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Op dit punt is de HTML‑inhoud geparseerd en zijn alle externe resources gestreamd naar de geheugen‑buffers die door `MyHandler` worden geleverd. + +## Stap 4 (optioneel): Toegang tot de vastgelegde resources + +Als je de resources wilt inspecteren of bewaren, kun je `MyHandler` aanpassen om elke `MemoryStream` op te slaan in een dictionary met de resource‑naam als sleutel. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Na het laden kun je itereren over `handler.Resources` en elk naar schijf schrijven: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Waarom dit belangrijk is:** +Het opslaan van resources maakt post‑processing mogelijk, zoals beeldoptimalisatie, CSS‑minimalisatie of archivering. Het biedt ook een tastbare verificatie dat de **create custom resource handler**‑logica werkt zoals bedoeld. + +## Stap 5: Opruimen + +Zowel `HTMLDocument` als eventuele streams moeten worden disposed om niet‑geheugengebonden resources vrij te geven. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Volledig uitvoerbaar voorbeeld + +Hieronder staat een zelfstandige programma‑voorbeeld dat alle stappen van klasse‑definitie tot resource‑extractie demonstreert. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Verwachte output** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +De console geeft elke resource weer die de viewer via jouw custom handler heeft gestreamd, wat bevestigt dat de **create custom resource handler**‑workflow geslaagd is. + +## Veelgestelde vragen en randgevallen + +| Vraag | Antwoord | +|----------|--------| +| *Wat als een resource groot is (bijv. een hoge‑resolutie afbeelding)?* | Vervang `MemoryStream` door een `FileStream` die naar een tijdelijke map wijst. Dit voorkomt overmatig geheugenverbruik. | +| *Kan ik resources filteren op type?* | Binnen `HandleResource` inspecteer je `info.MimeType` of `info.Extension` en retourneer je `null` voor ongewenste types. Het retourneren van `null` vertelt de viewer de resource over te slaan. | +| *Is thread‑veiligheid vereist?* | Als dezelfde handler‑instantie wordt gebruikt bij meerdere gelijktijdige loads, bescherm dan de `Resources`‑dictionary met een lock of gebruik een thread‑veilige collectie. | +| *Hoe ondersteun ik relatieve URL's?* | `ResourceInfo` bevat de originele URL; je kunt deze combineren met het basispad van het HTML‑bestand om relatieve verwijzingen op te lossen voordat je ze opslaat. | + +## Conclusie + +Je weet nu hoe je **create custom resource handler** in C# voor HTML‑laden kunt maken, `HTMLLoadOptions` kunt configureren, gestreamde assets kunt vastleggen en verantwoord kunt opruimen. Dit patroon geeft je volledige controle over resource‑beheer, waardoor scenario's zoals on‑the‑fly beeldverwerking, CSS‑herwerking of veilige opslag mogelijk zijn. + +Vervolgens kun je gerelateerde onderwerpen verkennen, zoals **HTMLDocument loading** met verschillende renderopties, of de handler uitbreiden naar **C# resource handler**‑implementaties die direct naar cloud‑opslag schrijven. Experimenteer met de `HandleResource`‑methode van de handler om deze aan te passen aan de specifieke resource‑workflow van je project. + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met 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. + +- [HTML maken vanuit string in C# – Custom Resource Handler gids](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – HTML naar ZIP converteren tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [Hoe HTML opslaan in C# – Complete gids met een Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/english/net/advanced-features/_index.md b/html/english/net/advanced-features/_index.md index e5c2af7f81..c947e9a799 100644 --- a/html/english/net/advanced-features/_index.md +++ b/html/english/net/advanced-features/_index.md @@ -44,7 +44,8 @@ Learn how to convert HTML to PDF, XPS, and images with Aspose.HTML for .NET. Ste Learn how to use Aspose.HTML for .NET to dynamically generate HTML documents from JSON data. Harness the power of HTML manipulation in your .NET applications. ### [Create memory stream c# – Custom stream creation guide](./create-memory-stream-c-custom-stream-creation-guide/) Learn how to create a memory stream in C# using Aspose.HTML for .NET, with step-by-step examples and best practices. - +### [Create bold italic font in C# – step‑by‑step guide](./create-bold-italic-font-in-c-step-by-step-guide/) +Learn how to generate bold and italic fonts in C# using Aspose.HTML, with step‑by‑step code examples and best practices. ## Conclusion diff --git a/html/english/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/english/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..e2edb93572 --- /dev/null +++ b/html/english/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-08-15 +description: Create bold italic font in C# quickly. Learn how to create font in C# + with bold and italic styles using the built‑in Font class. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: en +lastmod: 2026-08-15 +og_description: Create bold italic font in C# with a clear example. This tutorial + shows how to create font in C# using FontStyle flags and explains common pitfalls. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Create bold italic font in C# – complete coding guide +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Create bold italic font in C# – step‑by‑step guide +url: /net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create bold italic font in C# – step‑by‑step guide + +If you need to **create bold italic font** in C#, this guide shows you exactly how to do it. You’ll see a complete, runnable example that also demonstrates how to **create font in C#** using the standard .NET `Font` class. + +Working with custom fonts is a routine part of building Windows desktop apps, generating PDFs, or rendering HTML on the server. By the end of this tutorial you will be able to instantiate a font that is both bold and italic, understand why the bitwise `|` operator is used, and handle common edge cases such as missing font families. + +## What you’ll learn + +* How to import the required namespaces for font handling. +* The syntax for combining `FontStyle.Bold` and `FontStyle.Italic`. +* How to verify that the font was created successfully. +* Tips for fallback handling when the requested family isn’t installed. + +No external libraries are required—everything uses the .NET Framework / .NET Core base class library. + +## Prerequisites + +* .NET 6.0 SDK or later (the code also works on .NET Framework 4.6+). +* A code editor or IDE (Visual Studio, VS Code, Rider, etc.). +* Basic familiarity with C# syntax. + +If you meet these prerequisites, you can follow the steps without any additional setup. + +## Step 1: Add the necessary using directives + +The `Font` class lives in the `System.Drawing` namespace, which is part of the `System.Drawing.Common` NuGet package for .NET Core/.NET 5+. Add the namespace at the top of your file: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Why this step matters** – Without the `using System.Drawing;` line the compiler cannot locate `Font` or `FontStyle`, resulting in a “type or namespace name could not be found” error. + +## Step 2: Combine bold and italic styles with the bitwise OR operator + +In .NET, `FontStyle` is an enum marked with the `[Flags]` attribute. This means you can combine multiple values using the `|` (bitwise OR) operator: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Explanation + +* `"Arial"` – the font family name. If the system does not have Arial installed, the constructor falls back to the default font. +* `12` – point size. +* `FontStyle.Bold | FontStyle.Italic` – combines the two style flags. The `|` operator merges the binary representation of each flag, producing a single value that represents “bold + italic”. + +> **Pro tip:** Always use the enum names (`FontStyle.Bold`) rather than magic numbers; this improves readability and prevents bugs when the enum values change. + +## Step 3: Verify the created font (optional but recommended) + +Printing the font’s properties helps you confirm that the style combination succeeded, especially when debugging on a new machine. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Expected output** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +If the output lists both `Bold` and `Italic`, the font was created correctly. + +## Step 4: Render a sample string (visual confirmation) + +When you run a console app you can’t see the actual glyph styling, but you can generate an image to prove the result. The following snippet draws “Hello, World!” using the bold‑italic font and saves it as *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +After the program runs, open *sample.png* to see the text rendered with the bold italic style. + +![Sample text rendered with bold italic font](sample.png) + +*Image alt text: Screenshot of text rendered with a bold italic Arial font in a C# console window* – this alt text satisfies the SEO requirement for image alt text. + +## Step 5: Graceful fallback when the font family is unavailable + +If the requested family (e.g., “Arial”) isn’t installed, the `Font` constructor throws an `ArgumentException`. Wrap the creation in a `try/catch` block and fall back to a known safe font such as “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Why handle this?** In containerized or headless environments the default set of fonts can differ from a typical desktop. Providing a fallback prevents runtime crashes and ensures consistent styling. + +## Full, runnable example + +Putting everything together, here is a complete program you can copy, paste, and run: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### How to run + +1. Save the code to a file named `Program.cs`. +2. Open a terminal in the file’s directory. +3. Execute `dotnet new console -n FontDemo` (if you need a project scaffold). +4. Replace the generated `Program.cs` with the code above. +5. Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). +6. Build and run with `dotnet run`. + +You’ll see the console output confirming the font properties, and `sample.png` will appear in the project folder. + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| **Missing `System.Drawing.Common` package** | .NET Core does not include `System.Drawing` by default. | Run `dotnet add package System.Drawing.Common`. | +| **Font family not installed** | Headless Docker images often lack Windows fonts. | Use a fallback font or install the required fonts in the container. | +| **Incorrect use of `|`** | Using `+` instead of `|` results in an invalid combination. | Always combine `FontStyle` values with the bitwise OR operator (`|`). | +| **Disposing the `Font` object** | Not calling `Dispose` can leak GDI resources. | Wrap `Font` in a `using` block or call `font.Dispose()` after you’re done. | + +## Conclusion + +You now know how to **create bold italic font** in C# and how to **create font in C#** safely and efficiently. The tutorial covered importing the right namespace, combining `FontStyle` flags, verifying the result, rendering a visual sample, and handling missing font families. + +Next, you might explore: + +* **Creating underlined or strike‑through fonts** – add `FontStyle.Underline` or `FontStyle.Strikeout`. +* **Using custom TrueType fonts** – load a `.ttf` file with `PrivateFontCollection`. +* **Applying fonts in WinForms, WPF, or PDF generation** – the same `Font` object can be passed to UI controls or third‑party libraries. + +Feel free to experiment with different families, sizes, and style combinations. If you run into issues, revisit the “Common pitfalls” table or check the official [.NET documentation for System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Happy coding! + + +## 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. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/english/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/og-image.png b/html/english/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/og-image.png new file mode 100644 index 0000000000..1ddb4ae8a7 Binary files /dev/null and b/html/english/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/og-image.png differ diff --git a/html/english/net/working-with-html-documents/_index.md b/html/english/net/working-with-html-documents/_index.md index 7fb231926d..cc4f8a1390 100644 --- a/html/english/net/working-with-html-documents/_index.md +++ b/html/english/net/working-with-html-documents/_index.md @@ -37,6 +37,7 @@ Once you've grasped the basics, we'll delve deeper into the creation process. In Now, let's take your skills to the next level. Editing HTML documents is a common task for web developers, and Aspose.HTML simplifies this process significantly. In this section, we'll cover document creation, manipulation, and styling. You'll discover how to enhance the appearance and functionality of your web content, making it engaging and user-friendly. ### [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +### [Create custom resource handler in C# for HTML loading](./create-custom-resource-handler-in-c-for-html-loading/) ### [How to Bold Heading with CSS & C# – Complete Step‑by‑Step Guide](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/english/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/english/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..65b167fbc8 --- /dev/null +++ b/html/english/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-08-15 +description: Create custom resource handler in C# to manage HTML resources like images + and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: en +lastmod: 2026-08-15 +og_description: Create custom resource handler in C# to control how HTML resources + are streamed. This tutorial shows HTMLLoadOptions setup, memory stream handling, + and loading HTMLDocument with custom logic. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Create custom resource handler in C# – full guide for HTML resource management +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Create custom resource handler in C# for HTML loading +url: /net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create custom resource handler in C# for HTML loading + +If you need to **create custom resource handler** for HTML files, this guide shows you exactly how. You’ll learn to intercept images, CSS, and other assets while loading an HTML document, using `HTMLLoadOptions` and a memory‑based stream. + +The tutorial covers everything required to implement a reusable handler, configure load options, and verify that resources are captured correctly. No external documentation is needed—just the code below and the explanations. + +## Prerequisites + +- .NET 6.0 or later +- Basic familiarity with C# +- A reference to the HTML processing library that provides `HTMLDocument`, `HtmlLoadOptions`, and `ResourceHandler` (e.g., GroupDocs.Viewer for .NET) + +## Overview of the solution + +We will: + +1. **Create a custom resource handler** by subclassing `ResourceHandler`. +2. Configure `HTMLLoadOptions` to use the handler. +3. Load an HTML file with `HTMLDocument` while the handler supplies a stream for each resource. +4. (Optional) Store received resources to disk for verification. + +Each step includes full source code and the reasoning behind it. + +## Step 1: Define the custom resource handler class + +Creating a custom handler means overriding `HandleResource` so the library can write resource bytes to a stream you control. Using a `MemoryStream` keeps the data in memory, which is ideal for testing or further processing. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Why this matters:** +Overriding `HandleResource` gives you complete control over where resource data goes. If you later need to cache images, transform CSS, or log resource usage, you can replace the `MemoryStream` with any custom stream implementation. + +## Step 2: Configure `HTMLLoadOptions` to use the handler + +`HTMLLoadOptions` lets you plug the handler into the loading pipeline. Setting the `ResourceHandler` property tells the viewer to invoke `MyHandler` for every external asset. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Why this matters:** +Without assigning `ResourceHandler`, the viewer would write resources to its default location (often a temporary folder). By specifying your own handler, you **create custom resource handler** behavior that aligns with your application’s storage strategy. + +## Step 3: Load the HTML document with the configured options + +Now load the HTML file. The viewer will call `MyHandler.HandleResource` for each resource it encounters. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +At this point the HTML content is parsed, and all external resources have been streamed into the memory buffers supplied by `MyHandler`. + +## Step 4 (optional): Access the captured resources + +If you need to inspect or persist the resources, you can modify `MyHandler` to store each `MemoryStream` in a dictionary keyed by the resource name. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +After loading, you can iterate over `handler.Resources` and write each to disk: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Why this matters:** +Storing resources enables post‑processing such as image optimization, CSS minification, or archiving. It also provides a tangible verification that the **create custom resource handler** logic works as intended. + +## Step 5: Clean up + +Both `HTMLDocument` and any streams should be disposed to free unmanaged resources. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Full runnable example + +Below is a self‑contained program that demonstrates all steps from class definition to resource extraction. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Expected output** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +The console lists each resource that the viewer streamed through your custom handler, confirming that the **create custom resource handler** workflow succeeded. + +## Common questions and edge cases + +| Question | Answer | +|----------|--------| +| *What if a resource is large (e.g., high‑resolution image)?* | Replace `MemoryStream` with a `FileStream` pointing to a temporary folder. This prevents excessive memory consumption. | +| *Can I filter resources by type?* | Inside `HandleResource`, inspect `info.MimeType` or `info.Extension` and return `null` for unwanted types. Returning `null` tells the viewer to skip the resource. | +| *Is thread safety required?* | If the same handler instance is used across multiple concurrent loads, protect the `Resources` dictionary with a lock or use a concurrent collection. | +| *How do I support relative URLs?* | `ResourceInfo` contains the original URL; you can combine it with the base path of the HTML file to resolve relative references before storing. | + +## Conclusion + +You now know how to **create custom resource handler** in C# for HTML loading, configure `HTMLLoadOptions`, capture streamed assets, and clean up responsibly. This pattern gives you full control over resource management, enabling scenarios such as on‑the‑fly image processing, CSS rewriting, or secure storage. + +Next, explore related topics like **HTMLDocument loading** with different rendering options, or extend the handler to **C# resource handler** implementations that write directly to cloud storage. Experiment with the handler’s `HandleResource` method to fit your project’s specific resource workflow. + + +## 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. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/english/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/og-image.png b/html/english/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/og-image.png new file mode 100644 index 0000000000..8d189e8100 Binary files /dev/null and b/html/english/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/og-image.png differ diff --git a/html/french/net/advanced-features/_index.md b/html/french/net/advanced-features/_index.md index 9b226c5310..1cb21a1e2d 100644 --- a/html/french/net/advanced-features/_index.md +++ b/html/french/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Découvrez comment convertir du HTML en PDF, XPS et images avec Aspose.HTML pour Découvrez comment utiliser Aspose.HTML pour .NET pour générer dynamiquement des documents HTML à partir de données JSON. Exploitez la puissance de la manipulation HTML dans vos applications .NET. ### [Comment combiner des polices programmatiquement en C# – Guide étape par étape](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Apprenez à combiner plusieurs polices en C# avec Aspose.HTML, étape par étape, incluant des exemples de code et des FAQ. +### [Créer une police gras italique en C# – guide étape par étape](./create-bold-italic-font-in-c-step-by-step-guide/) +Apprenez à créer une police en gras et italique en C# avec Aspose.HTML, grâce à un guide détaillé pas à pas. ## Conclusion diff --git a/html/french/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/french/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..280325ad0c --- /dev/null +++ b/html/french/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-08-15 +description: Créez rapidement une police en gras et italique en C#. Apprenez comment + créer une police en C# avec les styles gras et italique en utilisant la classe Font + intégrée. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: fr +lastmod: 2026-08-15 +og_description: Créer une police en gras italique en C# avec un exemple clair. Ce + tutoriel montre comment créer une police en C# en utilisant les indicateurs FontStyle + et explique les pièges courants. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Créer une police gras et italique en C# – guide complet de programmation +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Créer une police en gras italique en C# – guide étape par étape +url: /fr/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer une police gras italique en C# – guide étape par étape + +Si vous avez besoin de **créer une police gras italique** en C#, ce guide vous montre exactement comment le faire. Vous verrez un exemple complet et exécutable qui montre également comment **créer une police en C#** en utilisant la classe standard .NET `Font`. + +Travailler avec des polices personnalisées est une partie courante de la création d'applications de bureau Windows, de la génération de PDF ou du rendu HTML sur le serveur. À la fin de ce tutoriel, vous serez capable d'instancier une police à la fois en gras et en italique, comprendre pourquoi l'opérateur binaire `|` est utilisé, et gérer les cas limites courants tels que les familles de polices manquantes. + +## Ce que vous apprendrez + +* Comment importer les espaces de noms requis pour la gestion des polices. +* La syntaxe pour combiner `FontStyle.Bold` et `FontStyle.Italic`. +* Comment vérifier que la police a été créée avec succès. +* Conseils pour la gestion des polices de secours lorsque la famille demandée n’est pas installée. + +Aucune bibliothèque externe n’est requise — tout utilise la bibliothèque de classes de base du .NET Framework / .NET Core. + +## Prérequis + +* .NET 6.0 SDK ou ultérieur (le code fonctionne également sur .NET Framework 4.6+). +* Un éditeur de code ou un IDE (Visual Studio, VS Code, Rider, etc.). +* Une connaissance de base de la syntaxe C#. + +Si vous remplissez ces prérequis, vous pouvez suivre les étapes sans configuration supplémentaire. + +## Étape 1 : Ajouter les directives using nécessaires + +La classe `Font` se trouve dans l’espace de noms `System.Drawing`, qui fait partie du package NuGet `System.Drawing.Common` pour .NET Core/.NET 5+. Ajoutez l’espace de noms en haut de votre fichier : + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Pourquoi cette étape est importante** – Sans la ligne `using System.Drawing;`, le compilateur ne peut pas localiser `Font` ou `FontStyle`, ce qui entraîne une erreur « type ou nom d’espace de noms introuvable ». + +## Étape 2 : Combiner les styles gras et italique avec l’opérateur OU binaire + +Dans .NET, `FontStyle` est une énumération marquée avec l’attribut `[Flags]`. Cela signifie que vous pouvez combiner plusieurs valeurs en utilisant l’opérateur `|` (OU binaire) : + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Explication + +* `"Arial"` – le nom de la famille de police. Si le système n’a pas Arial installé, le constructeur revient à la police par défaut. +* `12` – taille en points. +* `FontStyle.Bold | FontStyle.Italic` – combine les deux indicateurs de style. L’opérateur `|` fusionne la représentation binaire de chaque indicateur, produisant une valeur unique qui représente « gras + italique ». + +> **Astuce :** Utilisez toujours les noms d’énumération (`FontStyle.Bold`) plutôt que des nombres magiques ; cela améliore la lisibilité et évite les bugs lorsque les valeurs d’énumération changent. + +## Étape 3 : Vérifier la police créée (optionnel mais recommandé) + +Afficher les propriétés de la police vous aide à confirmer que la combinaison de styles a réussi, surtout lors du débogage sur une nouvelle machine. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Sortie attendue** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Si la sortie indique à la fois `Bold` et `Italic`, la police a été créée correctement. + +## Étape 4 : Rendre une chaîne d’exemple (confirmation visuelle) + +Lorsque vous exécutez une application console, vous ne pouvez pas voir le style réel des glyphes, mais vous pouvez générer une image pour prouver le résultat. Le fragment suivant dessine « Hello, World! » en utilisant la police gras‑italique et l’enregistre sous *sample.png* : + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Après l’exécution du programme, ouvrez *sample.png* pour voir le texte rendu avec le style gras italique. + +![Texte d'exemple rendu avec une police gras italique](sample.png) + +*Texte alternatif de l’image : Capture d’écran du texte rendu avec une police Arial gras italique dans une fenêtre console C#* – ce texte alternatif satisfait l’exigence SEO pour le texte alternatif des images. + +## Étape 5 : Repli élégant lorsque la famille de police est indisponible + +Si la famille demandée (par ex., « Arial ») n’est pas installée, le constructeur `Font` lève une `ArgumentException`. Enveloppez la création dans un bloc `try/catch` et revenez à une police sûre connue comme « Segoe UI ». + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Pourquoi gérer cela ?** Dans les environnements conteneurisés ou sans interface graphique, l’ensemble de polices par défaut peut différer d’un bureau typique. Fournir un repli empêche les plantages à l’exécution et assure un style cohérent. + +## Exemple complet, exécutable + +En rassemblant tout, voici un programme complet que vous pouvez copier, coller et exécuter : + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Comment exécuter + +1. Enregistrez le code dans un fichier nommé `Program.cs`. +2. Ouvrez un terminal dans le répertoire du fichier. +3. Exécutez `dotnet new console -n FontDemo` (si vous avez besoin d’une structure de projet). +4. Remplacez le `Program.cs` généré par le code ci‑dessus. +5. Exécutez `dotnet add package System.Drawing.Common` (requis pour .NET Core/5+). +6. Compilez et exécutez avec `dotnet run`. + +Vous verrez la sortie console confirmant les propriétés de la police, et `sample.png` apparaîtra dans le dossier du projet. + +## Pièges courants et comment les éviter + +| Piège | Pourquoi cela se produit | Solution | +|-------|--------------------------|----------| +| **Package `System.Drawing.Common` manquant** | .NET Core n’inclut pas `System.Drawing` par défaut. | Exécutez `dotnet add package System.Drawing.Common`. | +| **Famille de police non installée** | Les images Docker sans interface graphique manquent souvent des polices Windows. | Utilisez une police de secours ou installez les polices requises dans le conteneur. | +| **Utilisation incorrecte de `|`** | Utiliser `+` au lieu de `|` entraîne une combinaison invalide. | Combinez toujours les valeurs `FontStyle` avec l’opérateur OU binaire (`|`). | +| **Libération de l’objet `Font`** | Ne pas appeler `Dispose` peut provoquer des fuites de ressources GDI. | Enveloppez `Font` dans un bloc `using` ou appelez `font.Dispose()` après utilisation. | + +## Conclusion + +Vous savez maintenant comment **créer une police gras italique** en C# et comment **créer une police en C#** de manière sûre et efficace. Le tutoriel a couvert l’importation du bon espace de noms, la combinaison des indicateurs `FontStyle`, la vérification du résultat, le rendu d’un exemple visuel, et la gestion des familles de polices manquantes. + +Vous pourriez maintenant explorer : + +* **Créer des polices soulignées ou barrées** – ajoutez `FontStyle.Underline` ou `FontStyle.Strikeout`. +* **Utiliser des polices TrueType personnalisées** – chargez un fichier `.ttf` avec `PrivateFontCollection`. +* **Appliquer des polices dans WinForms, WPF ou la génération de PDF** – le même objet `Font` peut être passé aux contrôles UI ou aux bibliothèques tierces. + +N’hésitez pas à expérimenter avec différentes familles, tailles et combinaisons de styles. Si vous rencontrez des problèmes, consultez à nouveau le tableau « Pièges courants » ou vérifiez la documentation officielle [.NET pour System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Bon codage ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Comment combiner des polices de manière programmatique en C# – Guide étape par étape](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Créer un document HTML avec texte stylisé et l’exporter en PDF – Guide complet](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convertir docx en png – créer une archive zip tutoriel C#](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/french/net/working-with-html-documents/_index.md b/html/french/net/working-with-html-documents/_index.md index e18bb71d72..951459c8a7 100644 --- a/html/french/net/working-with-html-documents/_index.md +++ b/html/french/net/working-with-html-documents/_index.md @@ -41,6 +41,10 @@ Maintenant, passons à un niveau supérieur de compétences. L'édition de docum Apprenez à enregistrer du HTML en C# en utilisant un gestionnaire de ressources personnalisé pour contrôler le flux de sortie et les ressources liées. ### [Comment mettre en gras un titre avec CSS & C# – Guide complet étape par étape](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Créer un gestionnaire de ressources personnalisé en C# pour le chargement du HTML](./create-custom-resource-handler-in-c-for-html-loading/) + +Apprenez à créer un gestionnaire de ressources personnalisé en C# pour charger du HTML de manière contrôlée. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/french/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/french/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..aacd35c82d --- /dev/null +++ b/html/french/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-08-15 +description: Créer un gestionnaire de ressources personnalisé en C# pour gérer les + ressources HTML telles que les images et le CSS. Apprenez HTMLLoadOptions, les flux + mémoire et le chargement de HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: fr +lastmod: 2026-08-15 +og_description: Créer un gestionnaire de ressources personnalisé en C# pour contrôler + la diffusion des ressources HTML. Ce tutoriel montre la configuration de HTMLLoadOptions, + la gestion des flux mémoire et le chargement de HTMLDocument avec une logique personnalisée. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Créer un gestionnaire de ressources personnalisé en C# – guide complet pour + la gestion des ressources HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Créer un gestionnaire de ressources personnalisé en C# pour le chargement HTML +url: /fr/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un gestionnaire de ressources personnalisé en C# pour le chargement HTML + +Si vous devez **créer un gestionnaire de ressources personnalisé** pour les fichiers HTML, ce guide vous montre exactement comment faire. Vous apprendrez à intercepter les images, les CSS et d’autres actifs lors du chargement d’un document HTML, en utilisant `HTMLLoadOptions` et un flux basé sur la mémoire. + +Le tutoriel couvre tout ce qui est nécessaire pour implémenter un gestionnaire réutilisable, configurer les options de chargement et vérifier que les ressources sont correctement capturées. Aucun document externe n’est requis — seulement le code ci‑dessous et les explications. + +## Prérequis + +- .NET 6.0 ou version ultérieure +- Connaissances de base en C# +- Une référence à la bibliothèque de traitement HTML qui fournit `HTMLDocument`, `HtmlLoadOptions` et `ResourceHandler` (par ex., GroupDocs.Viewer for .NET) + +## Vue d’ensemble de la solution + +Nous allons : + +1. **Créer un gestionnaire de ressources personnalisé** en sous‑classant `ResourceHandler`. +2. Configurer `HTMLLoadOptions` pour utiliser ce gestionnaire. +3. Charger un fichier HTML avec `HTMLDocument` pendant que le gestionnaire fournit un flux pour chaque ressource. +4. (Optionnel) Stocker les ressources reçues sur le disque pour vérification. + +Chaque étape comprend le code source complet et le raisonnement qui la sous-tend. + +## Étape 1 : Définir la classe du gestionnaire de ressources personnalisé + +Créer un gestionnaire personnalisé signifie surcharger `HandleResource` afin que la bibliothèque puisse écrire les octets de la ressource dans un flux que vous contrôlez. L’utilisation d’un `MemoryStream` garde les données en mémoire, ce qui est idéal pour les tests ou un traitement ultérieur. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Pourquoi c’est important :** +La surcharge de `HandleResource` vous donne un contrôle total sur l’endroit où les données de la ressource sont envoyées. Si vous avez besoin plus tard de mettre en cache des images, de transformer du CSS ou de journaliser l’utilisation des ressources, vous pouvez remplacer le `MemoryStream` par n’importe quelle implémentation de flux personnalisée. + +## Étape 2 : Configurer `HTMLLoadOptions` pour utiliser le gestionnaire + +`HTMLLoadOptions` vous permet d’insérer le gestionnaire dans le pipeline de chargement. En définissant la propriété `ResourceHandler`, vous indiquez au visualiseur d’appeler `MyHandler` pour chaque actif externe. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Pourquoi c’est important :** +Sans affecter `ResourceHandler`, le visualiseur écrirait les ressources à son emplacement par défaut (souvent un dossier temporaire). En spécifiant votre propre gestionnaire, vous **créez un gestionnaire de ressources personnalisé** qui correspond à la stratégie de stockage de votre application. + +## Étape 3 : Charger le document HTML avec les options configurées + +Chargez maintenant le fichier HTML. Le visualiseur appellera `MyHandler.HandleResource` pour chaque ressource rencontrée. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +À ce stade, le contenu HTML est analysé et toutes les ressources externes ont été diffusées dans les tampons mémoire fournis par `MyHandler`. + +## Étape 4 (optionnelle) : Accéder aux ressources capturées + +Si vous devez inspecter ou persister les ressources, vous pouvez modifier `MyHandler` afin de stocker chaque `MemoryStream` dans un dictionnaire indexé par le nom de la ressource. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Après le chargement, vous pouvez parcourir `handler.Resources` et écrire chaque élément sur le disque : + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Pourquoi c’est important :** +Le stockage des ressources permet un post‑traitement tel que l’optimisation d’images, la minification de CSS ou l’archivage. Cela fournit également une vérification concrète que la logique de **créer un gestionnaire de ressources personnalisé** fonctionne comme prévu. + +## Étape 5 : Nettoyage + +Tant `HTMLDocument` que les flux doivent être libérés pour libérer les ressources non gérées. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Exemple complet exécutable + +Voici un programme autonome qui montre toutes les étapes, de la définition de la classe à l’extraction des ressources. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Sortie attendue** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +La console répertorie chaque ressource que le visualiseur a diffusée via votre gestionnaire personnalisé, confirmant que le flux de travail **créer un gestionnaire de ressources personnalisé** a réussi. + +## Questions fréquentes et cas particuliers + +| Question | Réponse | +|----------|---------| +| *Et si une ressource est volumineuse (par ex., image haute résolution) ?* | Remplacez le `MemoryStream` par un `FileStream` pointant vers un dossier temporaire. Cela évite une consommation excessive de mémoire. | +| *Puis‑je filtrer les ressources par type ?* | Dans `HandleResource`, examinez `info.MimeType` ou `info.Extension` et retournez `null` pour les types indésirables. Retourner `null` indique au visualiseur d’ignorer la ressource. | +| *La sécurité des threads est‑elle requise ?* | Si la même instance de gestionnaire est utilisée pour plusieurs chargements concurrents, protégez le dictionnaire `Resources` avec un verrou ou utilisez une collection concurrente. | +| *Comment gérer les URL relatives ?* | `ResourceInfo` contient l’URL d’origine ; vous pouvez la combiner avec le chemin de base du fichier HTML pour résoudre les références relatives avant de les stocker. | + +## Conclusion + +Vous savez maintenant comment **créer un gestionnaire de ressources personnalisé** en C# pour le chargement HTML, configurer `HTMLLoadOptions`, capturer les actifs diffusés et nettoyer correctement. Ce modèle vous donne un contrôle total sur la gestion des ressources, ouvrant des scénarios tels que le traitement d’images à la volée, la réécriture de CSS ou le stockage sécurisé. + +Ensuite, explorez des sujets connexes comme le **chargement de HTMLDocument** avec différentes options de rendu, ou étendez le gestionnaire à des implémentations **C# resource handler** qui écrivent directement vers le stockage cloud. Expérimentez avec la méthode `HandleResource` du gestionnaire pour l’adapter au flux de travail de ressources propre à votre projet. + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications 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. + +- [Créer du HTML à partir d’une chaîne en C# – Guide du gestionnaire de ressources personnalisé](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Gestionnaire de ressources personnalisé en C# – Tutoriel de conversion HTML en ZIP](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [Comment enregistrer du HTML en C# – Guide complet avec un gestionnaire de ressources personnalisé](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/german/net/advanced-features/_index.md b/html/german/net/advanced-features/_index.md index 176ec8f9db..6d8f839de3 100644 --- a/html/german/net/advanced-features/_index.md +++ b/html/german/net/advanced-features/_index.md @@ -48,6 +48,8 @@ Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in PDF, XPS und Bilder konv Erfahren Sie, wie Sie mit Aspose.HTML für .NET dynamisch HTML-Dokumente aus JSON-Daten generieren. Nutzen Sie die Leistungsfähigkeit der HTML-Manipulation in Ihren .NET-Anwendungen. ### [Wie man Schriftarten programmgesteuert in C# kombiniert – Schritt‑für‑Schritt‑Anleitung](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Erfahren Sie, wie Sie mit Aspose.HTML Schriftarten in C# kombinieren, um benutzerdefinierte Fonts zu erstellen – detaillierte Schritt‑für‑Schritt‑Anleitung. +### [Erstellen Sie fette und kursive Schrift in C# – Schritt‑für‑Schritt‑Anleitung](./create-bold-italic-font-in-c-step-by-step-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML fette und kursive Schriftarten in C# programmieren – kompakte Anleitung mit Beispielen. ## Abschluss diff --git a/html/german/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/german/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..d577cd2da2 --- /dev/null +++ b/html/german/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-08-15 +description: Erstelle schnell eine fette kursive Schriftart in C#. Erfahre, wie du + in C# eine Schrift mit fetten und kursiven Stilen mithilfe der integrierten Font‑Klasse + erstellst. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: de +lastmod: 2026-08-15 +og_description: Erstelle eine fette kursive Schriftart in C# mit einem klaren Beispiel. + Dieses Tutorial zeigt, wie man in C# eine Schriftart mit FontStyle‑Flags erstellt + und erklärt häufige Fallstricke. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Fett‑kursiven Font in C# erstellen – vollständiger Programmierleitfaden +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Fett‑kursiven Font in C# erstellen – Schritt‑für‑Schritt‑Anleitung +url: /de/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Fetter kursiver Font in C# erstellen – Schritt‑für‑Schritt‑Anleitung + +If you need to **create bold italic font** in C#, this guide shows you exactly how to do it. You’ll see a complete, runnable example that also demonstrates how to **create font in C#** using the standard .NET `Font` class. + +Working with custom fonts is a routine part of building Windows desktop apps, generating PDFs, or rendering HTML on the server. By the end of this tutorial you will be able to instantiate a font that is both bold and italic, understand why the bitwise `|` operator is used, and handle common edge cases such as missing font families. + +## Was Sie lernen werden + +* How to import the required namespaces for font handling. +* The syntax for combining `FontStyle.Bold` and `FontStyle.Italic`. +* How to verify that the font was created successfully. +* Tips for fallback handling when the requested family isn’t installed. + +No external libraries are required—everything uses the .NET Framework / .NET Core base class library. + +## Voraussetzungen + +* .NET 6.0 SDK or later (the code also works on .NET Framework 4.6+). +* A code editor or IDE (Visual Studio, VS Code, Rider, etc.). +* Basic familiarity with C# syntax. + +If you meet these prerequisites, you can follow the steps without any additional setup. + +## Schritt 1: Die erforderlichen using‑Direktiven hinzufügen + +The `Font` class lives in the `System.Drawing` namespace, which is part of the `System.Drawing.Common` NuGet package for .NET Core/.NET 5+. Add the namespace at the top of your file: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Warum dieser Schritt wichtig ist** – Ohne die Zeile `using System.Drawing;` kann der Compiler `Font` oder `FontStyle` nicht finden, was zu einem Fehler „type or namespace name could not be found“ führt. + +## Schritt 2: Fette und kursive Stile mit dem bitweisen ODER‑Operator kombinieren + +In .NET, `FontStyle` is an enum marked with the `[Flags]` attribute. This means you can combine multiple values using the `|` (bitwise OR) operator: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Erklärung + +* `"Arial"` – der Schriftfamilien‑Name. Wenn das System Arial nicht installiert hat, fällt der Konstruktor auf die Standardschrift zurück. +* `12` – Punktgröße. +* `FontStyle.Bold | FontStyle.Italic` – kombiniert die beiden Stil‑Flags. Der `|`‑Operator verbindet die binäre Darstellung jedes Flags und erzeugt einen einzelnen Wert, der „bold + italic“ repräsentiert. + +> **Pro‑Tipp:** Verwenden Sie immer die Enum‑Namen (`FontStyle.Bold`) anstelle von Magic Numbers; das verbessert die Lesbarkeit und verhindert Fehler, wenn sich die Enum‑Werte ändern. + +## Schritt 3: Die erstellte Schriftart überprüfen (optional, aber empfohlen) + +Printing the font’s properties helps you confirm that the style combination succeeded, especially when debugging on a new machine. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Erwartete Ausgabe** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +If the output lists both `Bold` and `Italic`, the font was created correctly. + +## Schritt 4: Einen Beispiel‑String rendern (visuelle Bestätigung) + +When you run a console app you can’t see the actual glyph styling, but you can generate an image to prove the result. The following snippet draws “Hello, World!” using the bold‑italic font and saves it as *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +After the program runs, open *sample.png* to see the text rendered with the bold italic style. + +![Sample text rendered with bold italic font](sample.png) + +*Image alt text: Screenshot von Text, der mit einer fetten kursiven Arial‑Schrift in einem C#‑Konsolenfenster gerendert wurde* – this alt text satisfies the SEO requirement for image alt text. + +## Schritt 5: Eleganter Fallback, wenn die Schriftfamilie nicht verfügbar ist + +If the requested family (e.g., “Arial”) isn’t installed, the `Font` constructor throws an `ArgumentException`. Wrap the creation in a `try/catch` block and fall back to a known safe font such as “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Warum das behandeln?** In containerisierten oder headless Umgebungen kann das Standardsatz an Schriftarten von einem typischen Desktop abweichen. Ein Fallback verhindert Laufzeit‑Abstürze und sorgt für konsistente Darstellung. + +## Vollständiges, ausführbares Beispiel + +Putting everything together, here is a complete program you can copy, paste, and run: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### So führen Sie das Programm aus + +1. Save the code to a file named `Program.cs`. +2. Open a terminal in the file’s directory. +3. Execute `dotnet new console -n FontDemo` (if you need a project scaffold). +4. Replace the generated `Program.cs` with the code above. +5. Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). +6. Build and run with `dotnet run`. + +You’ll see the console output confirming the font properties, and `sample.png` will appear in the project folder. + +## Häufige Fallstricke und wie man sie vermeidet + +| Fallstrick | Warum es passiert | Lösung | +|------------|-------------------|--------| +| **Missing `System.Drawing.Common` package** | .NET Core does not include `System.Drawing` by default. | Run `dotnet add package System.Drawing.Common`. | +| **Font family not installed** | Headless Docker images often lack Windows fonts. | Use a fallback font or install the required fonts in the container. | +| **Incorrect use of `|`** | Using `+` instead of `|` results in an invalid combination. | Always combine `FontStyle` values with the bitwise OR operator (`|`). | +| **Disposing the `Font` object** | Not calling `Dispose` can leak GDI resources. | Wrap `Font` in a `using` block or call `font.Dispose()` after you’re done. | + +## Fazit + +You now know how to **create bold italic font** in C# and how to **create font in C#** safely and efficiently. The tutorial covered importing the right namespace, combining `FontStyle` flags, verifying the result, rendering a visual sample, and handling missing font families. + +Next, you might explore: + +* **Creating underlined or strike‑through fonts** – add `FontStyle.Underline` or `FontStyle.Strikeout`. +* **Using custom TrueType fonts** – load a `.ttf` file with `PrivateFontCollection`. +* **Applying fonts in WinForms, WPF, or PDF generation** – the same `Font` object can be passed to UI controls or third‑party libraries. + +Feel free to experiment with different families, sizes, and style combinations. If you run into issues, revisit the “Common pitfalls” table or check the official [.NET documentation for System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Happy coding! + +## Was sollten Sie als Nächstes lernen? + +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. + +- [Wie man Schriftarten programmgesteuert in C# kombiniert – Schritt‑für‑Schritt‑Anleitung](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [HTML‑Dokument mit formatiertem Text erstellen und als PDF exportieren – Vollständige Anleitung](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [docx in png konvertieren – ZIP‑Archiv erstellen C#‑Tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/german/net/working-with-html-documents/_index.md b/html/german/net/working-with-html-documents/_index.md index 20ea4c9d75..e5739b6f6e 100644 --- a/html/german/net/working-with-html-documents/_index.md +++ b/html/german/net/working-with-html-documents/_index.md @@ -39,6 +39,11 @@ Lassen Sie uns nun Ihre Fähigkeiten auf die nächste Ebene bringen. Das Bearbei ### [HTML in C# speichern – Vollständige Anleitung mit benutzerdefiniertem Ressourcen-Handler](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) Erfahren Sie, wie Sie HTML in C# mit einem benutzerdefinierten Ressourcen-Handler speichern können. + +### [Erstellen eines benutzerdefinierten Ressourcen-Handlers in C# für das Laden von HTML](./create-custom-resource-handler-in-c-for-html-loading/) + +Lernen Sie, wie Sie in C# einen eigenen Ressourcen-Handler implementieren, um HTML zu laden. + ### [Überschrift mit CSS & C# fett formatieren – Komplett‑Schritt‑für‑Schritt‑Anleitung](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/german/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/german/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..6527de4d6d --- /dev/null +++ b/html/german/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-08-15 +description: Erstelle einen benutzerdefinierten Ressourcen‑Handler in C#, um HTML‑Ressourcen + wie Bilder und CSS zu verwalten. Lerne HTMLLoadOptions, MemoryStreams und das Laden + von HTMLDocument kennen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: de +lastmod: 2026-08-15 +og_description: Erstellen Sie einen benutzerdefinierten Ressourcen‑Handler in C#, + um zu steuern, wie HTML‑Ressourcen gestreamt werden. Dieses Tutorial zeigt die Einrichtung + von HTMLLoadOptions, die Handhabung von MemoryStreams und das Laden von HTMLDocument + mit benutzerdefinierter Logik. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Erstelle einen benutzerdefinierten Ressourcen‑Handler in C# – vollständige + Anleitung zur HTML‑Ressourcenverwaltung +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Benutzerdefinierten Ressourcen‑Handler in C# für HTML‑Laden erstellen +url: /de/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Erstellen eines benutzerdefinierten Resource Handlers in C# für das Laden von HTML + +Wenn Sie **einen benutzerdefinierten Resource Handler** für HTML‑Dateien erstellen müssen, zeigt Ihnen diese Anleitung genau, wie das geht. Sie lernen, wie Sie Bilder, CSS und andere Assets beim Laden eines HTML‑Dokuments abfangen, indem Sie `HTMLLoadOptions` und einen speicherbasierten Stream verwenden. + +Das Tutorial deckt alles ab, was nötig ist, um einen wiederverwendbaren Handler zu implementieren, Ladeoptionen zu konfigurieren und zu überprüfen, dass Ressourcen korrekt erfasst werden. Keine externe Dokumentation ist nötig – nur der untenstehende Code und die Erklärungen. + +## Voraussetzungen + +- .NET 6.0 oder höher +- Grundkenntnisse in C# +- Eine Referenz zur HTML‑Verarbeitungsbibliothek, die `HTMLDocument`, `HtmlLoadOptions` und `ResourceHandler` bereitstellt (z. B. GroupDocs.Viewer für .NET) + +## Überblick über die Lösung + +Wir werden: + +1. **Einen benutzerdefinierten Resource Handler** erstellen, indem wir `ResourceHandler` ableiten. +2. `HTMLLoadOptions` so konfigurieren, dass der Handler verwendet wird. +3. Eine HTML‑Datei mit `HTMLDocument` laden, wobei der Handler für jede Ressource einen Stream bereitstellt. +4. (Optional) Empfangene Ressourcen zur Überprüfung auf die Festplatte speichern. + +Jeder Schritt enthält vollständigen Quellcode und die dahinterstehende Logik. + +## Schritt 1: Definieren der benutzerdefinierten Resource‑Handler‑Klasse + +Ein benutzerdefinierter Handler bedeutet, dass Sie `HandleResource` überschreiben, damit die Bibliothek die Ressourcendaten in einen von Ihnen gesteuerten Stream schreibt. Die Verwendung eines `MemoryStream` hält die Daten im Speicher, was ideal für Tests oder weitere Verarbeitung ist. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Warum das wichtig ist:** +Durch das Überschreiben von `HandleResource` erhalten Sie die vollständige Kontrolle darüber, wohin die Ressourcendaten geschrieben werden. Wenn Sie später Bilder zwischenspeichern, CSS transformieren oder die Ressourcennutzung protokollieren möchten, können Sie den `MemoryStream` durch jede beliebige benutzerdefinierte Stream‑Implementierung ersetzen. + +## Schritt 2: `HTMLLoadOptions` so konfigurieren, dass der Handler verwendet wird + +`HTMLLoadOptions` ermöglicht es Ihnen, den Handler in die Ladepipeline einzuklinken. Durch das Setzen der Eigenschaft `ResourceHandler` wird dem Viewer mitgeteilt, dass er `MyHandler` für jedes externe Asset aufrufen soll. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Warum das wichtig ist:** +Ohne Zuweisung von `ResourceHandler` würde der Viewer Ressourcen an den Standardspeicherort schreiben (oft ein temporärer Ordner). Durch die Angabe Ihres eigenen Handlers **erstellen Sie benutzerdefiniertes Resource‑Handler‑Verhalten**, das zu Ihrer Speicherstrategie passt. + +## Schritt 3: Laden des HTML‑Dokuments mit den konfigurierten Optionen + +Jetzt laden Sie die HTML‑Datei. Der Viewer ruft `MyHandler.HandleResource` für jede gefundene Ressource auf. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +An diesem Punkt ist der HTML‑Inhalt geparst, und alle externen Ressourcen wurden in die von `MyHandler` bereitgestellten Speicherpuffer gestreamt. + +## Schritt 4 (optional): Zugriff auf die erfassten Ressourcen + +Falls Sie die Ressourcen inspizieren oder persistieren möchten, können Sie `MyHandler` so anpassen, dass jeder `MemoryStream` in einem Dictionary gespeichert wird, das mit dem Ressourcennamen als Schlüssel arbeitet. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Nach dem Laden können Sie über `handler.Resources` iterieren und jede Ressource auf die Festplatte schreiben: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Warum das wichtig ist:** +Das Speichern von Ressourcen ermöglicht Nachbearbeitungen wie Bildoptimierung, CSS‑Minifizierung oder Archivierung. Es liefert zudem einen greifbaren Nachweis, dass die **create custom resource handler**‑Logik wie beabsichtigt funktioniert. + +## Schritt 5: Aufräumen + +Sowohl `HTMLDocument` als auch alle Streams sollten disposed werden, um nicht verwaltete Ressourcen freizugeben. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Vollständiges ausführbares Beispiel + +Im Folgenden finden Sie ein eigenständiges Programm, das alle Schritte von der Klassendefinition bis zur Ressourcenausgabe demonstriert. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Erwartete Ausgabe** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Die Konsole listet jede Ressource auf, die der Viewer über Ihren benutzerdefinierten Handler gestreamt hat, und bestätigt damit, dass der **create custom resource handler**‑Workflow erfolgreich war. + +## Häufige Fragen und Sonderfälle + +| Frage | Antwort | +|----------|--------| +| *Was, wenn eine Ressource groß ist (z. B. ein hochauflösendes Bild)?* | Ersetzen Sie `MemoryStream` durch einen `FileStream`, der auf einen temporären Ordner zeigt. Das verhindert übermäßigen Speicherverbrauch. | +| *Kann ich Ressourcen nach Typ filtern?* | Untersuchen Sie in `HandleResource` `info.MimeType` oder `info.Extension` und geben Sie `null` für unerwünschte Typen zurück. `null` signalisiert dem Viewer, die Ressource zu überspringen. | +| *Ist Thread‑Safety erforderlich?* | Wenn dieselbe Handler‑Instanz über mehrere gleichzeitige Ladevorgänge hinweg verwendet wird, schützen Sie das `Resources`‑Dictionary mit einem Lock oder verwenden Sie eine Concurrent‑Collection. | +| *Wie unterstütze ich relative URLs?* | `ResourceInfo` enthält die ursprüngliche URL; Sie können sie mit dem Basis‑Pfad der HTML‑Datei kombinieren, um relative Verweise vor dem Speichern aufzulösen. | + +## Fazit + +Sie wissen jetzt, wie Sie **einen benutzerdefinierten Resource Handler** in C# für das Laden von HTML erstellen, `HTMLLoadOptions` konfigurieren, gestreamte Assets erfassen und verantwortungsbewusst aufräumen. Dieses Muster gibt Ihnen die volle Kontrolle über das Ressourcenmanagement und ermöglicht Szenarien wie die Echtzeit‑Bildverarbeitung, CSS‑Umwandlung oder sichere Speicherung. + +Als Nächstes können Sie verwandte Themen erkunden, etwa **HTMLDocument‑Laden** mit verschiedenen Rendering‑Optionen, oder den Handler zu **C# resource handler**‑Implementierungen erweitern, die direkt in Cloud‑Speicher schreiben. Experimentieren Sie mit der `HandleResource`‑Methode, um den Workflow an die spezifischen Anforderungen Ihres Projekts anzupassen. + + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, damit Sie weitere API‑Funktionen meistern und alternative Implementierungsansätze in Ihren eigenen Projekten erkunden können. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/greek/net/advanced-features/_index.md b/html/greek/net/advanced-features/_index.md index f086ac2861..bd85fb43be 100644 --- a/html/greek/net/advanced-features/_index.md +++ b/html/greek/net/advanced-features/_index.md @@ -46,6 +46,8 @@ url: /el/net/advanced-features/ Μάθετε πώς να χρησιμοποιείτε το Aspose.HTML για .NET για τη δυναμική δημιουργία εγγράφων HTML από δεδομένα JSON. Αξιοποιήστε τη δύναμη του χειρισμού HTML στις εφαρμογές σας .NET. ### [Πώς να συνδυάσετε γραμματοσειρές προγραμματιστικά σε C# – Οδηγός βήμα‑βήμα](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +### [Δημιουργία έντονης πλάγιας γραμματοσειράς σε C# – οδηγός βήμα‑βήμα](./create-bold-italic-font-in-c-step-by-step-guide/) + ## Σύναψη Το Aspose.HTML για .NET ανοίγει την πόρτα σε έναν κόσμο δυνατοτήτων όσον αφορά την εργασία με έγγραφα HTML στις εφαρμογές σας .NET. Αυτά τα προηγμένα σεμινάρια λειτουργιών θα σας εξοπλίσουν με τις γνώσεις και τις δεξιότητες που απαιτούνται για να αξιοποιήσετε πλήρως τις δυνατότητες του Aspose.HTML. Αυξήστε τα αναπτυξιακά σας έργα, εξοικονομήστε χρόνο και δημιουργήστε αξιόλογες λύσεις με το Aspose.HTML για .NET. Ξεκινήστε με τα σεμινάρια μας σήμερα και μεταφέρετε την ανάπτυξη ιστού σας στο επόμενο επίπεδο. diff --git a/html/greek/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/greek/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..a20a8bce1e --- /dev/null +++ b/html/greek/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-08-15 +description: Δημιουργήστε έντονη πλάγια γραμματοσειρά σε C# γρήγορα. Μάθετε πώς να + δημιουργήσετε γραμματοσειρά σε C# με έντονο και πλάγιο στυλ χρησιμοποιώντας την + ενσωματωμένη κλάση Font. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: el +lastmod: 2026-08-15 +og_description: Δημιουργήστε έντονη πλάγια γραμματοσειρά σε C# με σαφές παράδειγμα. + Αυτό το σεμινάριο δείχνει πώς να δημιουργήσετε γραμματοσειρά σε C# χρησιμοποιώντας + τις σημαίες FontStyle και εξηγεί κοινά λάθη. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Δημιουργήστε έντονη πλάγια γραμματοσειρά σε C# – πλήρης οδηγός προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Δημιουργία έντονης πλάγιας γραμματοσειράς σε C# – βήμα‑βήμα οδηγός +url: /el/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία έντονης πλάγιας γραμματοσειράς σε C# – βήμα‑βήμα οδηγός + +Αν χρειάζεστε **να δημιουργήσετε έντονη πλάγια γραμματοσειρά** σε C#, αυτός ο οδηγός σας δείχνει ακριβώς πώς να το κάνετε. Θα δείτε ένα πλήρες, εκτελέσιμο παράδειγμα που επίσης δείχνει πώς να **δημιουργήσετε γραμματοσειρά σε C#** χρησιμοποιώντας την τυπική κλάση .NET `Font`. + +Η εργασία με προσαρμοσμένες γραμματοσειρές είναι καθημερινό μέρος της δημιουργίας εφαρμογών Windows desktop, της παραγωγής PDF ή της απόδοσης HTML στον διακομιστή. Στο τέλος αυτού του σεμιναρίου θα μπορείτε να δημιουργήσετε μια γραμματοσειρά που είναι ταυτόχρονα έντονη και πλάγια, να καταλάβετε γιατί χρησιμοποιείται ο τελεστής bitwise `|` και να αντιμετωπίσετε κοινές περιπτώσεις όπως η απουσία οικογενειών γραμματοσειρών. + +## Τι θα μάθετε + +* Πώς να εισάγετε τα απαιτούμενα namespaces για διαχείριση γραμματοσειρών. +* Η σύνταξη για συνδυασμό `FontStyle.Bold` και `FontStyle.Italic`. +* Πώς να επαληθεύσετε ότι η γραμματοσειρά δημιουργήθηκε επιτυχώς. +* Συμβουλές για διαχείριση εναλλακτικών λύσεων όταν η ζητούμενη οικογένεια δεν είναι εγκατεστημένη. + +Δεν απαιτούνται εξωτερικές βιβλιοθήκες — όλα χρησιμοποιούν τη βασική βιβλιοθήκη κλάσεων του .NET Framework / .NET Core. + +## Προαπαιτούμενα + +* .NET 6.0 SDK ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.6+). +* Ένας επεξεργαστής κώδικα ή IDE (Visual Studio, VS Code, Rider κ.λπ.). +* Βασική εξοικείωση με τη σύνταξη της C#. + +Αν πληροίτε αυτά τα προαπαιτούμενα, μπορείτε να ακολουθήσετε τα βήματα χωρίς πρόσθετη ρύθμιση. + +## Βήμα 1: Προσθήκη των απαραίτητων using directives + +Η κλάση `Font` βρίσκεται στο namespace `System.Drawing`, το οποίο είναι μέρος του πακέτου NuGet `System.Drawing.Common` για .NET Core/.NET 5+. Προσθέστε το namespace στην κορυφή του αρχείου σας: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Γιατί είναι σημαντικό αυτό το βήμα** – Χωρίς τη γραμμή `using System.Drawing;` ο μεταγλωττιστής δεν μπορεί να εντοπίσει το `Font` ή το `FontStyle`, με αποτέλεσμα σφάλμα “type or namespace name could not be found”. + +## Βήμα 2: Συνδυασμός έντονης και πλάγιας μορφής με τον τελεστή bitwise OR + +Στο .NET, το `FontStyle` είναι ένα enum με το χαρακτηριστικό `[Flags]`. Αυτό σημαίνει ότι μπορείτε να συνδυάσετε πολλαπλές τιμές χρησιμοποιώντας τον τελεστή `|` (bitwise OR): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Εξήγηση + +* `"Arial"` – το όνομα της οικογένειας γραμματοσειράς. Αν το σύστημα δεν έχει εγκατεστημένο το Arial, ο κατασκευαστής επιστρέφει την προεπιλεγμένη γραμματοσειρά. +* `12` – μέγεθος σε points. +* `FontStyle.Bold | FontStyle.Italic` – συνδυάζει τις δύο σημαίες στυλ. Ο τελεστής `|` συγχωνεύει την δυαδική αναπαράσταση κάθε σημαίας, παράγοντας μια μοναδική τιμή που αντιπροσωπεύει “έντονη + πλάγια”. + +> **Pro tip:** Χρησιμοποιείτε πάντα τα ονόματα του enum (`FontStyle.Bold`) αντί για μαγικούς αριθμούς· αυτό βελτιώνει την αναγνωσιμότητα και αποτρέπει σφάλματα όταν αλλάζουν οι τιμές του enum. + +## Βήμα 3: Επαλήθευση της δημιουργημένης γραμματοσειράς (προαιρετικό αλλά συνιστάται) + +Η εκτύπωση των ιδιοτήτων της γραμματοσειράς σας βοηθά να επιβεβαιώσετε ότι ο συνδυασμός στυλ πέτυχε, ειδικά όταν κάνετε αποσφαλμάτωση σε νέο μηχάνημα. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Αναμενόμενη έξοδος** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Αν η έξοδος εμφανίζει και τα `Bold` και `Italic`, η γραμματοσειρά δημιουργήθηκε σωστά. + +## Βήμα 4: Απόδοση δείγματος κειμένου (οπτική επιβεβαίωση) + +Όταν εκτελείτε μια εφαρμογή κονσόλας δεν μπορείτε να δείτε το πραγματικό στυλ των χαρακτήρων, αλλά μπορείτε να δημιουργήσετε μια εικόνα για να αποδείξετε το αποτέλεσμα. Το παρακάτω απόσπασμα σχεδιάζει το “Hello, World!” χρησιμοποιώντας τη γραμματοσειρά bold‑italic και το αποθηκεύει ως *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Μετά την εκτέλεση του προγράμματος, ανοίξτε το *sample.png* για να δείτε το κείμενο αποδομένο με το στυλ έντονης πλάγιας γραμματοσειράς. + +![Δείγμα κειμένου αποδομένο με έντονη πλάγια γραμματοσειρά](sample.png) + +*Κείμενο alt: Στιγμιότυπο οθόνης κειμένου αποδομένου με έντονη πλάγια γραμματοσειρά Arial σε παράθυρο κονσόλας C#* – αυτό το alt text ικανοποιεί την απαίτηση SEO για κείμενο alt εικόνας. + +## Βήμα 5: Χειροκίνητη εναλλακτική λύση όταν η οικογένεια γραμματοσειράς δεν είναι διαθέσιμη + +Αν η ζητούμενη οικογένεια (π.χ. “Arial”) δεν είναι εγκατεστημένη, ο κατασκευαστής `Font` ρίχνει `ArgumentException`. Τυλίξτε τη δημιουργία σε μπλοκ `try/catch` και επιστρέψτε σε μια ασφαλή γραμματοσειρά όπως “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Γιατί να το διαχειριστείτε;** Σε περιβάλλοντα με κοντέινερ ή headless, το σύνολο προεπιλεγμένων γραμματοσειρών μπορεί να διαφέρει από ένα τυπικό desktop. Η εναλλακτική λύση αποτρέπει σφάλματα χρόνου εκτέλεσης και εξασφαλίζει συνεπές στυλ. + +## Πλήρες, εκτελέσιμο παράδειγμα + +Συνδυάζοντας όλα τα παραπάνω, εδώ είναι ένα πλήρες πρόγραμμα που μπορείτε να αντιγράψετε, να επικολλήσετε και να τρέξετε: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Πώς να τρέξετε + +1. Αποθηκεύστε τον κώδικα σε αρχείο με όνομα `Program.cs`. +2. Ανοίξτε ένα τερματικό στον φάκελο του αρχείου. +3. Εκτελέστε `dotnet new console -n FontDemo` (αν χρειάζεστε σκελετό έργου). +4. Αντικαταστήστε το παραγόμενο `Program.cs` με τον κώδικα παραπάνω. +5. Εκτελέστε `dotnet add package System.Drawing.Common` (απαιτείται για .NET Core/5+). +6. Κατασκευάστε και τρέξτε με `dotnet run`. + +Θα δείτε την έξοδο της κονσόλας που επιβεβαιώνει τις ιδιότητες της γραμματοσειράς, και το `sample.png` θα εμφανιστεί στον φάκελο του έργου. + +## Συνηθισμένα προβλήματα και πώς να τα αποφύγετε + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| **Λείπει το πακέτο `System.Drawing.Common`** | Το .NET Core δεν περιλαμβάνει το `System.Drawing` από προεπιλογή. | Εκτελέστε `dotnet add package System.Drawing.Common`. | +| **Η οικογένεια γραμματοσειράς δεν είναι εγκατεστημένη** | Τα headless Docker images συχνά δεν έχουν γραμματοσειρές Windows. | Χρησιμοποιήστε εναλλακτική γραμματοσειρά ή εγκαταστήστε τις απαιτούμενες γραμματοσειρές στο κοντέινερ. | +| **Λανθασμένη χρήση του `|`** | Η χρήση του `+` αντί του `|` δημιουργεί άκυρο συνδυασμό. | Συνδυάστε πάντα τις τιμές του `FontStyle` με τον τελεστή bitwise OR (`|`). | +| **Μη διαγραφή του αντικειμένου `Font`** | Η μη κλήση του `Dispose` μπορεί να διαρρεύσει πόρους GDI. | Τυλίξτε το `Font` σε `using` block ή καλέστε `font.Dispose()` μετά τη χρήση. | + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **δημιουργήσετε έντονη πλάγια γραμματοσειρά** σε C# και πώς να **δημιουργήσετε γραμματοσειρά σε C#** με ασφαλή και αποδοτικό τρόπο. Ο οδηγός κάλυψε την εισαγωγή του σωστού namespace, τον συνδυασμό σημαίων `FontStyle`, την επαλήθευση του αποτελέσματος, την απόδοση οπτικού δείγματος και τη διαχείριση ελλιπών οικογενειών γραμματοσειρών. + +Στη συνέχεια, μπορείτε να εξερευνήσετε: + +* **Δημιουργία υπογραμμισμένων ή διακριτών γραμματοσειρών** – προσθέστε `FontStyle.Underline` ή `FontStyle.Strikeout`. +* **Χρήση προσαρμοσμένων γραμματοσειρών TrueType** – φορτώστε αρχείο `.ttf` με `PrivateFontCollection`. +* **Εφαρμογή γραμματοσειρών σε WinForms, WPF ή δημιουργία PDF** – το ίδιο αντικείμενο `Font` μπορεί να περαστεί σε UI controls ή βιβλιοθήκες τρίτων. + +Πειραματιστείτε με διαφορετικές οικογένειες, μεγέθη και συνδυασμούς στυλ. Αν αντιμετωπίσετε προβλήματα, επιστρέψτε στον πίνακα “Συνηθισμένα προβλήματα” ή ελέγξτε την επίσημη [.NET τεκμηρίωση για System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Καλή προγραμματιστική! + +## Τι θα πρέπει να μάθετε στη συνέχεια; + +Οι παρακάτω σεμινάρια καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας έργα. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/greek/net/working-with-html-documents/_index.md b/html/greek/net/working-with-html-documents/_index.md index 1990362d06..d372625666 100644 --- a/html/greek/net/working-with-html-documents/_index.md +++ b/html/greek/net/working-with-html-documents/_index.md @@ -41,6 +41,8 @@ url: /el/net/working-with-html-documents/ Μάθετε πώς να αποθηκεύετε HTML σε C# χρησιμοποιώντας έναν προσαρμοσμένο διαχειριστή πόρων, βήμα-βήμα οδηγός. ### [Πώς να κάνετε έντονο τίτλο με CSS & C# – Πλήρης οδηγός βήμα‑βήμα](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Δημιουργία προσαρμοσμένου διαχειριστή πόρων σε C# για φόρτωση HTML](./create-custom-resource-handler-in-c-for-html-loading/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/greek/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/greek/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..8c3b0cd281 --- /dev/null +++ b/html/greek/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-08-15 +description: Δημιουργήστε προσαρμοσμένο διαχειριστή πόρων σε C# για τη διαχείριση + πόρων HTML όπως εικόνες και CSS. Μάθετε τις HTMLLoadOptions, τις ροές μνήμης και + τη φόρτωση του HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: el +lastmod: 2026-08-15 +og_description: Δημιουργήστε προσαρμοσμένο διαχειριστή πόρων σε C# για να ελέγχετε + πώς μεταδίδονται οι πόροι HTML. Αυτό το σεμινάριο δείχνει τη ρύθμιση του HTMLLoadOptions, + τη διαχείριση της μνήμης ροής και τη φόρτωση του HTMLDocument με προσαρμοσμένη λογική. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Δημιουργία προσαρμοσμένου διαχειριστή πόρων σε C# – πλήρης οδηγός διαχείρισης + πόρων HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Δημιουργία προσαρμοσμένου διαχειριστή πόρων σε C# για τη φόρτωση HTML +url: /el/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία προσαρμοσμένου διαχειριστή πόρων σε C# για φόρτωση HTML + +Αν χρειάζεστε **create custom resource handler** για αρχεία HTML, αυτός ο οδηγός σας δείχνει ακριβώς πώς. Θα μάθετε πώς να παρεμβάλλετε εικόνες, CSS και άλλα στοιχεία κατά τη φόρτωση ενός εγγράφου HTML, χρησιμοποιώντας `HTMLLoadOptions` και μια ροή βασισμένη στη μνήμη. + +Το tutorial καλύπτει όλα όσα απαιτούνται για την υλοποίηση ενός επαναχρησιμοποιήσιμου διαχειριστή, τη διαμόρφωση των επιλογών φόρτωσης και την επαλήθευση ότι οι πόροι καταγράφονται σωστά. Δεν χρειάζεται εξωτερική τεκμηρίωση — μόνο ο κώδικας παρακάτω και οι εξηγήσεις. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο +- Βασική εξοικείωση με C# +- Αναφορά στη βιβλιοθήκη επεξεργασίας HTML που παρέχει `HTMLDocument`, `HtmlLoadOptions` και `ResourceHandler` (π.χ., GroupDocs.Viewer for .NET) + +## Επισκόπηση της λύσης + +Θα: + +1. **Create a custom resource handler** κληρονομώντας την κλάση `ResourceHandler`. +2. Διαμορφώσουμε το `HTMLLoadOptions` ώστε να χρησιμοποιεί τον διαχειριστή. +3. Φορτώσουμε ένα αρχείο HTML με το `HTMLDocument` ενώ ο διαχειριστής παρέχει ροή για κάθε πόρο. +4. (Προαιρετικά) Αποθηκεύσουμε τους ληφθέντες πόρους στο δίσκο για επαλήθευση. + +Κάθε βήμα περιλαμβάνει πλήρη πηγαίο κώδικα και τη λογική που τον υποστηρίζει. + +## Βήμα 1: Ορισμός της κλάσης προσαρμοσμένου διαχειριστή πόρων + +Η δημιουργία προσαρμοσμένου διαχειριστή σημαίνει την υπερφόρτωση του `HandleResource` ώστε η βιβλιοθήκη να γράφει τα bytes του πόρου σε ροή που ελέγχετε. Η χρήση `MemoryStream` διατηρεί τα δεδομένα στη μνήμη, κάτι ιδανικό για δοκιμές ή περαιτέρω επεξεργασία. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Γιατί είναι σημαντικό:** +Η υπερφόρτωση του `HandleResource` σας δίνει πλήρη έλεγχο στο πού πηγαίνουν τα δεδομένα του πόρου. Αν αργότερα χρειαστείτε να κάνετε cache εικόνων, να μετασχηματίσετε CSS ή να καταγράψετε τη χρήση πόρων, μπορείτε να αντικαταστήσετε το `MemoryStream` με οποιαδήποτε προσαρμοσμένη υλοποίηση ροής. + +## Βήμα 2: Διαμόρφωση του `HTMLLoadOptions` για χρήση του διαχειριστή + +Το `HTMLLoadOptions` σας επιτρέπει να ενσωματώσετε τον διαχειριστή στην αλυσίδα φόρτωσης. Ορίζοντας την ιδιότητα `ResourceHandler` λέτε στον προβολέα να καλέσει το `MyHandler` για κάθε εξωτερικό στοιχείο. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Γιατί είναι σημαντικό:** +Χωρίς την ανάθεση του `ResourceHandler`, ο προβολέας θα έγραφε τους πόρους στην προεπιλεγμένη τοποθεσία του (συχνά σε προσωρινό φάκελο). Καθορίζοντας τον δικό σας διαχειριστή, **create custom resource handler** συμπεριφορά που ευθυγραμμίζεται με τη στρατηγική αποθήκευσης της εφαρμογής σας. + +## Βήμα 3: Φόρτωση του εγγράφου HTML με τις διαμορφωμένες επιλογές + +Τώρα φορτώνουμε το αρχείο HTML. Ο προβολέας θα καλέσει το `MyHandler.HandleResource` για κάθε πόρο που εντοπίζει. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Σε αυτό το σημείο το περιεχόμενο HTML έχει αναλυθεί και όλοι οι εξωτερικοί πόροι έχουν ρέει στα buffers μνήμης που παρέχονται από το `MyHandler`. + +## Βήμα 4 (προαιρετικό): Πρόσβαση στους καταγεγραμμένους πόρους + +Αν χρειάζεται να ελέγξετε ή να αποθηκεύσετε τους πόρους, μπορείτε να τροποποιήσετε το `MyHandler` ώστε να αποθηκεύει κάθε `MemoryStream` σε λεξικό με κλειδί το όνομα του πόρου. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Μετά τη φόρτωση, μπορείτε να διατρέξετε το `handler.Resources` και να γράψετε το καθένα στο δίσκο: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Γιατί είναι σημαντικό:** +Η αποθήκευση των πόρων επιτρέπει επεξεργασία όπως βελτιστοποίηση εικόνων, ελαχιστοποίηση CSS ή αρχειοθέτηση. Παρέχει επίσης μια απτή επαλήθευση ότι η λογική **create custom resource handler** λειτουργεί όπως προβλέπεται. + +## Βήμα 5: Καθαρισμός + +Τanto το `HTMLDocument` όσο και οι ροές πρέπει να απελευθερώνονται για να ελευθερωθούν οι μη διαχειριζόμενοι πόροι. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Πλήρες εκτελέσιμο παράδειγμα + +Παρακάτω υπάρχει ένα αυτόνομο πρόγραμμα που δείχνει όλα τα βήματα, από τον ορισμό της κλάσης μέχρι την εξαγωγή πόρων. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Αναμενόμενη έξοδος** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Η κονσόλα εμφανίζει κάθε πόρο που ο προβολέας έστειλε μέσω του προσαρμοσμένου διαχειριστή, επιβεβαιώνοντας ότι η ροή **create custom resource handler** ολοκληρώθηκε με επιτυχία. + +## Συχνές ερωτήσεις και ειδικές περιπτώσεις + +| Ερώτηση | Απάντηση | +|----------|--------| +| *Τι γίνεται αν ένας πόρος είναι μεγάλος (π.χ., εικόνα υψηλής ανάλυσης);* | Αντικαταστήστε το `MemoryStream` με ένα `FileStream` που δείχνει σε έναν προσωρινό φάκελο. Αυτό αποτρέπει υπερβολική κατανάλωση μνήμης. | +| *Μπορώ να φιλτράρω πόρους ανά τύπο;* | Μέσα στο `HandleResource`, εξετάστε το `info.MimeType` ή `info.Extension` και επιστρέψτε `null` για ανεπιθύμητους τύπους. Η επιστροφή `null` λέει στον προβολέα να παραλείψει τον πόρο. | +| *Απαιτείται ασφάλεια νήματος;* | Αν η ίδια παρουσία διαχειριστή χρησιμοποιείται σε πολλαπλές ταυτόχρονες φορτώσεις, προστατέψτε το λεξικό `Resources` με κλείδωμα ή χρησιμοποιήστε μια σύγχρονη συλλογή. | +| *Πώς υποστηρίζω σχετικές διευθύνσεις URL;* | Το `ResourceInfo` περιέχει το αρχικό URL· μπορείτε να το συνδυάσετε με τη βάση του αρχείου HTML για να επιλύσετε σχετικές αναφορές πριν την αποθήκευση. | + +## Συμπέρασμα + +Τώρα γνωρίζετε πώς να **create custom resource handler** σε C# για φόρτωση HTML, να διαμορφώσετε το `HTMLLoadOptions`, να καταγράψετε τα ροές πόρων και να καθαρίσετε υπεύθυνα. Αυτό το πρότυπο σας δίνει πλήρη έλεγχο στη διαχείριση πόρων, επιτρέποντας σενάρια όπως επεξεργασία εικόνων σε πραγματικό χρόνο, επαναγραφή CSS ή ασφαλή αποθήκευση. + +Στη συνέχεια, εξερευνήστε συναφή θέματα όπως **HTMLDocument loading** με διαφορετικές επιλογές απόδοσης, ή επεκτείνετε τον διαχειριστή σε υλοποιήσεις **C# resource handler** που γράφουν απευθείας σε αποθήκευση cloud. Πειραματιστείτε με τη μέθοδο `HandleResource` του διαχειριστή για να ταιριάξει στη συγκεκριμένη ροή πόρων του έργου σας. + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσετε επιπλέον δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στην υλοποίηση σας. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/hindi/net/advanced-features/_index.md b/html/hindi/net/advanced-features/_index.md index 70aa91b60e..2848eaaf58 100644 --- a/html/hindi/net/advanced-features/_index.md +++ b/html/hindi/net/advanced-features/_index.md @@ -44,7 +44,8 @@ Aspose.HTML के साथ .NET में HTML दस्तावेज़ो JSON डेटा से HTML दस्तावेज़ों को गतिशील रूप से जेनरेट करने के लिए .NET के लिए Aspose.HTML का उपयोग करना सीखें। अपने .NET अनुप्रयोगों में HTML हेरफेर की शक्ति का उपयोग करें। ### [मेमोरी स्ट्रीम बनाएं c# – कस्टम स्ट्रीम निर्माण गाइड](./create-memory-stream-c-custom-stream-creation-guide/) JSON डेटा से HTML दस्तावेज़ों को गतिशील रूप से जेनरेट करने के लिए .NET के लिए Aspose.HTML का उपयोग करना सीखें। अपने .NET अनुप्रयोगों में HTML हेरफेर की शक्ति का उपयोग करें। - +### [C# में बोल्ड इटैलिक फ़ॉन्ट बनाएं – चरण‑दर‑चरण मार्गदर्शिका](./create-bold-italic-font-in-c-step-by-step-guide/) +C# में बोल्ड इटैलिक फ़ॉन्ट बनाने के लिए चरण‑दर‑चरण निर्देश। ## निष्कर्ष diff --git a/html/hindi/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/hindi/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..f683937245 --- /dev/null +++ b/html/hindi/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-08-15 +description: C# में जल्दी से बोल्ड इटैलिक फ़ॉन्ट बनाएं। बिल्ट‑इन Font क्लास का उपयोग + करके C# में बोल्ड और इटैलिक स्टाइल के साथ फ़ॉन्ट बनाना सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: hi +lastmod: 2026-08-15 +og_description: C# में बोल्ड इटैलिक फ़ॉन्ट बनाएं, एक स्पष्ट उदाहरण के साथ। यह ट्यूटोरियल + दिखाता है कि FontStyle फ़्लैग्स का उपयोग करके C# में फ़ॉन्ट कैसे बनाएं और सामान्य + गलतियों की व्याख्या करता है। +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: C# में बोल्ड इटैलिक फ़ॉन्ट बनाएं – पूर्ण कोडिंग गाइड +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: C# में बोल्ड इटैलिक फ़ॉन्ट बनाएं – चरण‑दर‑चरण मार्गदर्शिका +url: /hi/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में बोल्ड इटैलिक फ़ॉन्ट बनाएं – चरण‑दर‑चरण गाइड + +यदि आपको C# में **बोल्ड इटैलिक फ़ॉन्ट बनाना** है, तो यह गाइड आपको ठीक‑ठीक बताता है कि कैसे करें। आप एक पूर्ण, चलाने योग्य उदाहरण देखेंगे जो यह भी दर्शाता है कि **C# में फ़ॉन्ट कैसे बनाएं** मानक .NET `Font` क्लास का उपयोग करके। + +कस्टम फ़ॉन्ट्स के साथ काम करना Windows डेस्कटॉप ऐप्स बनाते समय, PDFs जेनरेट करते समय, या सर्वर पर HTML रेंडर करते समय एक सामान्य कार्य है। इस ट्यूटोरियल के अंत तक आप एक ऐसा फ़ॉन्ट इंस्टैंशिएट कर पाएंगे जो दोनों ही बोल्ड और इटैलिक हो, समझेंगे कि बिटवाइज़ `|` ऑपरेटर क्यों उपयोग किया जाता है, और सामान्य किनारे के मामलों जैसे कि गायब फ़ॉन्ट फ़ैमिली को कैसे संभालें। + +## आप क्या सीखेंगे + +* फ़ॉन्ट हैंडलिंग के लिए आवश्यक नेमस्पेसेज़ को इम्पोर्ट करने का तरीका। +* `FontStyle.Bold` और `FontStyle.Italic` को मिलाने की सिंटैक्स। +* यह सत्यापित करने का तरीका कि फ़ॉन्ट सफलतापूर्वक बनाया गया है या नहीं। +* जब अनुरोधित फ़ैमिली इंस्टॉल नहीं हो तो फ़ॉलबैक हैंडलिंग के टिप्स। + +कोई बाहरी लाइब्रेरी आवश्यक नहीं है—सब कुछ .NET Framework / .NET Core बेस क्लास लाइब्रेरी का उपयोग करता है। + +## पूर्वापेक्षाएँ + +* .NET 6.0 SDK या बाद का संस्करण (कोड .NET Framework 4.6+ पर भी काम करता है)। +* एक कोड एडिटर या IDE (Visual Studio, VS Code, Rider, आदि)। +* C# सिंटैक्स की बुनियादी समझ। + +यदि आप इन पूर्वापेक्षाओं को पूरा करते हैं, तो आप बिना किसी अतिरिक्त सेटअप के चरणों का पालन कर सकते हैं। + +## चरण 1: आवश्यक using निर्देश जोड़ें + +`Font` क्लास `System.Drawing` नेमस्पेस में स्थित है, जो .NET Core/.NET 5+ के लिए `System.Drawing.Common` NuGet पैकेज का हिस्सा है। फ़ाइल के शीर्ष पर नेमस्पेस जोड़ें: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **यह चरण क्यों महत्वपूर्ण है** – बिना `using System.Drawing;` लाइन के कंपाइलर `Font` या `FontStyle` को नहीं ढूँढ़ पाता, जिससे “type or namespace name could not be found” त्रुटि आती है। + +## चरण 2: बिटवाइज़ OR ऑपरेटर से बोल्ड और इटैलिक स्टाइल को मिलाएँ + +.NET में, `FontStyle` एक enum है जिसमें `[Flags]` एट्रिब्यूट लगा है। इसका मतलब है कि आप कई मानों को `|` (बिटवाइज़ OR) ऑपरेटर से जोड़ सकते हैं: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### व्याख्या + +* `"Arial"` – फ़ॉन्ट फ़ैमिली का नाम। यदि सिस्टम में Arial इंस्टॉल नहीं है, तो कंस्ट्रक्टर डिफ़ॉल्ट फ़ॉन्ट पर फ़ॉलबैक करता है। +* `12` – पॉइंट साइज। +* `FontStyle.Bold | FontStyle.Italic` – दो स्टाइल फ़्लैग्स को मिलाता है। `|` ऑपरेटर प्रत्येक फ़्लैग के बाइनरी प्रतिनिधित्व को जोड़ता है, जिससे एकल मान बनता है जो “bold + italic” को दर्शाता है। + +> **प्रो टिप:** हमेशा enum नाम (`FontStyle.Bold`) का उपयोग करें, न कि मैजिक नंबर; इससे पठनीयता बढ़ती है और जब enum मान बदलते हैं तो बग्स से बचा जा सकता है। + +## चरण 3: बनाए गए फ़ॉन्ट को सत्यापित करें (वैकल्पिक लेकिन अनुशंसित) + +फ़ॉन्ट की प्रॉपर्टीज़ को प्रिंट करने से आपको यह पुष्टि करने में मदद मिलती है कि स्टाइल संयोजन सफल रहा, विशेषकर नई मशीन पर डिबगिंग करते समय। + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**अपेक्षित आउटपुट** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +यदि आउटपुट में दोनों `Bold` और `Italic` दिखते हैं, तो फ़ॉन्ट सही ढंग से बनाया गया है। + +## चरण 4: एक सैंपल स्ट्रिंग रेंडर करें (विज़ुअल पुष्टि) + +जब आप एक कंसोल ऐप चलाते हैं तो आप वास्तविक ग्लिफ़ स्टाइल नहीं देख सकते, लेकिन आप एक इमेज जेनरेट करके परिणाम प्रमाणित कर सकते हैं। नीचे दिया गया स्निपेट “Hello, World!” को बोल्ड‑इटैलिक फ़ॉन्ट में ड्रॉ करता है और इसे *sample.png* के रूप में सहेजता है: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +प्रोग्राम चलने के बाद, *sample.png* खोलें और देखें कि टेक्स्ट बोल्ड इटैलिक स्टाइल में रेंडर हुआ है। + +![Sample text rendered with bold italic font](sample.png) + +*Image alt text: C# कंसोल विंडो में बोल्ड इटैलिक Arial फ़ॉन्ट के साथ रेंडर किया गया टेक्स्ट का स्क्रीनशॉट* – यह alt टेक्स्ट इमेज के SEO आवश्यकताओं को पूरा करता है। + +## चरण 5: फ़ॉन्ट फ़ैमिली अनुपलब्ध होने पर सुगम फ़ॉलबैक + +यदि अनुरोधित फ़ैमिली (जैसे “Arial”) इंस्टॉल नहीं है, तो `Font` कंस्ट्रक्टर `ArgumentException` फेंकता है। निर्माण को `try/catch` ब्लॉक में रैप करें और “Segoe UI” जैसी सुरक्षित फ़ॉन्ट पर फ़ॉलबैक करें। + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**यह क्यों संभालें?** कंटेनराइज़्ड या हेडलेस वातावरण में डिफ़ॉल्ट फ़ॉन्ट सेट सामान्य डेस्कटॉप से अलग हो सकता है। फ़ॉलबैक प्रदान करने से रनटाइम क्रैश से बचाव होता है और स्टाइलिंग सुसंगत रहती है। + +## पूर्ण, चलाने योग्य उदाहरण + +सब कुछ मिलाकर, यहाँ एक पूरा प्रोग्राम है जिसे आप कॉपी, पेस्ट और चलाकर देख सकते हैं: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### चलाने का तरीका + +1. कोड को `Program.cs` नामक फ़ाइल में सहेजें। +2. फ़ाइल की डायरेक्टरी में टर्मिनल खोलें। +3. `dotnet new console -n FontDemo` चलाएँ (यदि आपको प्रोजेक्ट स्कैफ़ोल्ड चाहिए)। +4. जेनरेट किए गए `Program.cs` को ऊपर के कोड से बदल दें। +5. `dotnet add package System.Drawing.Common` चलाएँ (.NET Core/5+ के लिए आवश्यक)। +6. `dotnet run` के साथ बिल्ड और रन करें। + +आपको कंसोल आउटपुट में फ़ॉन्ट प्रॉपर्टीज़ की पुष्टि दिखेगी, और `sample.png` प्रोजेक्ट फ़ोल्डर में बन जाएगा। + +## सामान्य समस्याएँ और उनका समाधान + +| समस्या | क्यों होती है | समाधान | +|---------|----------------|-----| +| **`System.Drawing.Common` पैकेज गायब** | .NET Core में `System.Drawing` डिफ़ॉल्ट रूप से शामिल नहीं होता। | `dotnet add package System.Drawing.Common` चलाएँ। | +| **फ़ॉन्ट फ़ैमिली इंस्टॉल नहीं** | हेडलेस Docker इमेजेज़ में अक्सर Windows फ़ॉन्ट नहीं होते। | फ़ॉलबैक फ़ॉन्ट उपयोग करें या कंटेनर में आवश्यक फ़ॉन्ट इंस्टॉल करें। | +| **`|` का गलत उपयोग** | `+` का उपयोग करने से अमान्य संयोजन बनता है। | हमेशा `FontStyle` मानों को बिटवाइज़ OR ऑपरेटर (`|`) से मिलाएँ। | +| **`Font` ऑब्जेक्ट को डिस्पोज़ न करना** | `Dispose` न करने से GDI रिसोर्स लीक हो सकते हैं। | `Font` को `using` ब्लॉक में रखें या उपयोग के बाद `font.Dispose()` कॉल करें। | + +## निष्कर्ष + +अब आप जानते हैं कि **C# में बोल्ड इटैलिक फ़ॉन्ट कैसे बनाएं** और इसे **C# में फ़ॉन्ट सुरक्षित और कुशलता से कैसे बनाएं**। ट्यूटोरियल ने सही नेमस्पेस इम्पोर्ट, `FontStyle` फ़्लैग्स को मिलाना, परिणाम सत्यापित करना, विज़ुअल सैंपल रेंडर करना, और फ़ॉन्ट फ़ैमिली न मिलने पर फ़ॉलबैक संभालना कवर किया। + +आगे आप खोज सकते हैं: + +* **अंडरलाइन या स्ट्राइक‑थ्रू फ़ॉन्ट बनाना** – `FontStyle.Underline` या `FontStyle.Strikeout` जोड़ें। +* **कस्टम TrueType फ़ॉन्ट्स का उपयोग** – `.ttf` फ़ाइल को `PrivateFontCollection` से लोड करें। +* **WinForms, WPF, या PDF जेनरेशन में फ़ॉन्ट लागू करना** – वही `Font` ऑब्जेक्ट UI कंट्रोल्स या थर्ड‑पार्टी लाइब्रेरीज़ को पास किया जा सकता है। + +विभिन्न फ़ैमिली, साइज और स्टाइल संयोजनों के साथ प्रयोग करने में संकोच न करें। यदि कोई समस्या आती है, तो “सामान्य समस्याएँ” तालिका को फिर से देखें या आधिकारिक [.NET दस्तावेज़ System.Drawing.Font के लिए](https://learn.microsoft.com/dotnet/api/system.drawing.font) देखें। कोडिंग का आनंद लें! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में निपुण हो सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का अन्वेषण कर सकें। + +- [C# में प्रोग्रामेटिकली फ़ॉन्ट कैसे मिलाएँ – चरण‑दर‑चरण गाइड](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [HTML दस्तावेज़ को स्टाइल्ड टेक्स्ट के साथ बनाएं और PDF में एक्सपोर्ट करें – पूर्ण गाइड](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [docx को png में बदलें – zip आर्काइव बनाएं c# ट्यूटोरियल](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/hindi/net/working-with-html-documents/_index.md b/html/hindi/net/working-with-html-documents/_index.md index 4c5be51ef6..0018a62d22 100644 --- a/html/hindi/net/working-with-html-documents/_index.md +++ b/html/hindi/net/working-with-html-documents/_index.md @@ -37,6 +37,7 @@ HTML दस्तावेज़ वेब की रीढ़ हैं, और अब, आइए अपने कौशल को अगले स्तर पर ले जाएं। HTML दस्तावेज़ों को संपादित करना वेब डेवलपर्स के लिए एक सामान्य कार्य है, और Aspose.HTML इस प्रक्रिया को काफी सरल बनाता है। इस अनुभाग में, हम दस्तावेज़ निर्माण, हेरफेर और स्टाइलिंग को कवर करेंगे। आप जानेंगे कि अपनी वेब सामग्री की उपस्थिति और कार्यक्षमता को कैसे बढ़ाया जाए, जिससे यह आकर्षक और उपयोगकर्ता के अनुकूल बन सके। ### [C# में HTML को सहेजना – कस्टम रिसोर्स हैंडलर का उपयोग करके पूर्ण गाइड](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +### [HTML लोडिंग के लिए C# में कस्टम रिसोर्स हैंडलर बनाएं](./create-custom-resource-handler-in-c-for-html-loading/) ### [CSS और C# के साथ हेडिंग को बोल्ड कैसे बनाएं – पूर्ण चरण-दर-चरण गाइड](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/hindi/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/hindi/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..1ba1cb143b --- /dev/null +++ b/html/hindi/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-08-15 +description: C# में कस्टम रिसोर्स हैंडलर बनाकर इमेज और CSS जैसी HTML रिसोर्सेज़ को + मैनेज करें। HTMLLoadOptions, मेमोरी स्ट्रीम्स और HTMLDocument लोडिंग सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: hi +lastmod: 2026-08-15 +og_description: C# में कस्टम रिसोर्स हैंडलर बनाकर HTML संसाधनों के स्ट्रीमिंग को नियंत्रित + करें। यह ट्यूटोरियल HTMLLoadOptions सेटअप, मेमोरी स्ट्रीम हैंडलिंग, और कस्टम लॉजिक + के साथ HTMLDocument लोड करने को दर्शाता है। +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: C# में कस्टम रिसोर्स हैंडलर बनाएं – HTML रिसोर्स प्रबंधन के लिए पूर्ण गाइड +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: HTML लोडिंग के लिए C# में कस्टम रिसोर्स हैंडलर बनाएं +url: /hi/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML लोडिंग के लिए C# में कस्टम रिसोर्स हैंडलर बनाएं + +यदि आपको **कस्टम रिसोर्स हैंडलर** HTML फ़ाइलों के लिए बनाना है, तो यह गाइड आपको ठीक‑ठीक दिखाएगा। आप सीखेंगे कि कैसे HTML दस्तावेज़ लोड करते समय इमेज, CSS और अन्य एसेट्स को इंटरसेप्ट किया जाए, `HTMLLoadOptions` और मेमोरी‑आधारित स्ट्रीम का उपयोग करके। + +यह ट्यूटोरियल पुन: उपयोग योग्य हैंडलर को लागू करने, लोड विकल्पों को कॉन्फ़िगर करने और यह सत्यापित करने के लिए आवश्यक सभी चीज़ें कवर करता है कि रिसोर्स सही ढंग से कैप्चर हो रहे हैं। बाहरी दस्तावेज़ की आवश्यकता नहीं—केवल नीचे दिया गया कोड और व्याख्याएँ। + +## Prerequisites + +- .NET 6.0 या बाद का संस्करण +- C# की बुनियादी समझ +- वह HTML प्रोसेसिंग लाइब्रेरी जिसका रेफ़रेंस `HTMLDocument`, `HtmlLoadOptions`, और `ResourceHandler` प्रदान करता है (उदाहरण के लिए, GroupDocs.Viewer for .NET) + +## समाधान का Overview + +हम करेंगे: + +1. **कस्टम रिसोर्स हैंडलर** को `ResourceHandler` को सबक्लास करके बनाना। +2. `HTMLLoadOptions` को हैंडलर उपयोग करने के लिए कॉन्फ़िगर करना। +3. `HTMLDocument` के साथ HTML फ़ाइल लोड करना, जबकि हैंडलर प्रत्येक रिसोर्स के लिए स्ट्रीम प्रदान करता है। +4. (वैकल्पिक) प्राप्त रिसोर्स को डिस्क पर स्टोर करके सत्यापन करना। + +प्रत्येक चरण में पूरा स्रोत कोड और उसके पीछे की तर्कशक्ति दी गई है। + +## Step 1: Define the custom resource handler class + +कस्टम हैंडलर बनाने का मतलब है `HandleResource` को ओवरराइड करना ताकि लाइब्रेरी रिसोर्स बाइट्स को आपके नियंत्रित स्ट्रीम में लिख सके। `MemoryStream` का उपयोग डेटा को मेमोरी में रखता है, जो टेस्टिंग या आगे की प्रोसेसिंग के लिए आदर्श है। + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Why this matters:** +`HandleResource` को ओवरराइड करने से आपको रिसोर्स डेटा कहां जाएगा, इस पर पूरी नियंत्रण मिलती है। यदि बाद में आपको इमेज को कैश करना, CSS ट्रांसफ़ॉर्म करना या रिसोर्स उपयोग को लॉग करना हो, तो आप `MemoryStream` को किसी भी कस्टम स्ट्रीम इम्प्लीमेंटेशन से बदल सकते हैं। + +## Step 2: Configure `HTMLLoadOptions` to use the handler + +`HTMLLoadOptions` आपको हैंडलर को लोडिंग पाइपलाइन में प्लग करने की सुविधा देता है। `ResourceHandler` प्रॉपर्टी सेट करने से व्यूअर हर बाहरी एसेट के लिए `MyHandler` को कॉल करेगा। + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Why this matters:** +`ResourceHandler` को असाइन नहीं किया गया तो व्यूअर रिसोर्स को अपनी डिफ़ॉल्ट लोकेशन (अक्सर एक टेम्प फ़ोल्डर) में लिखेगा। अपना हैंडलर निर्दिष्ट करके आप **कस्टम रिसोर्स हैंडलर** व्यवहार बनाते हैं जो आपके एप्लिकेशन की स्टोरेज स्ट्रैटेजी के अनुरूप हो। + +## Step 3: Load the HTML document with the configured options + +अब HTML फ़ाइल लोड करें। व्यूअर प्रत्येक रिसोर्स के लिए `MyHandler.HandleResource` को कॉल करेगा। + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +इस बिंदु पर HTML कंटेंट पार्स हो चुका है, और सभी बाहरी रिसोर्स `MyHandler` द्वारा प्रदान किए गए मेमोरी बफ़र्स में स्ट्रीम हो गए हैं। + +## Step 4 (optional): Access the captured resources + +यदि आपको रिसोर्स को जांचना या स्थायी रूप से सहेजना है, तो आप `MyHandler` को इस तरह बदल सकते हैं कि प्रत्येक `MemoryStream` को रिसोर्स नाम के आधार पर एक डिक्शनरी में स्टोर किया जाए। + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +लोडिंग के बाद, आप `handler.Resources` पर इटरेट करके प्रत्येक को डिस्क पर लिख सकते हैं: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Why this matters:** +रिसोर्स को स्टोर करने से इमेज ऑप्टिमाइज़ेशन, CSS मिनिफिकेशन या आर्काइविंग जैसी पोस्ट‑प्रोसेसिंग संभव होती है। यह यह भी स्पष्ट करता है कि **create custom resource handler** लॉजिक इच्छित रूप से काम कर रहा है। + +## Step 5: Clean up + +`HTMLDocument` और सभी स्ट्रीम को डिस्पोज़ करना न भूलें ताकि अनमैनेज्ड रिसोर्स मुक्त हो सकें। + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Full runnable example + +नीचे एक स्व-समाहित प्रोग्राम है जो क्लास डिफ़िनिशन से लेकर रिसोर्स एक्सट्रैक्शन तक सभी चरणों को दर्शाता है। + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Expected output** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +कंसोल प्रत्येक रिसोर्स को सूचीबद्ध करेगा जो व्यूअर आपके कस्टम हैंडलर के माध्यम से स्ट्रीम किया, यह पुष्टि करते हुए कि **create custom resource handler** वर्कफ़्लो सफल रहा। + +## Common questions and edge cases + +| Question | Answer | +|----------|--------| +| *यदि कोई रिसोर्स बड़ा है (जैसे हाई‑रेज़ोल्यूशन इमेज)?* | `MemoryStream` के बजाय एक `FileStream` उपयोग करें जो टेम्प फ़ोल्डर की ओर इशारा करता हो। इससे मेमोरी की अत्यधिक खपत रोकी जा सकती है। | +| *क्या मैं रिसोर्स को प्रकार के आधार पर फ़िल्टर कर सकता हूँ?* | `HandleResource` के अंदर `info.MimeType` या `info.Extension` जांचें और अनचाहे प्रकारों के लिए `null` रिटर्न करें। `null` रिटर्न करने से व्यूअर उस रिसोर्स को स्किप कर देगा। | +| *क्या थ्रेड‑सेफ़्टी आवश्यक है?* | यदि एक ही हैंडलर इंस्टेंस को कई समवर्ती लोड्स में उपयोग किया जाता है, तो `Resources` डिक्शनरी को लॉक से सुरक्षित करें या एक concurrent collection उपयोग करें। | +| *मैं रिलेटिव URLs को कैसे सपोर्ट करूँ?* | `ResourceInfo` में मूल URL मौजूद होता है; आप इसे HTML फ़ाइल के बेस पाथ के साथ मिलाकर रिलेटिव रेफ़रेंसेज़ को रिज़ॉल्व कर सकते हैं और फिर स्टोर कर सकते हैं। | + +## Conclusion + +अब आप जानते हैं कि **create custom resource handler** को C# में HTML लोडिंग के लिए कैसे बनाया जाए, `HTMLLoadOptions` को कैसे कॉन्फ़िगर किया जाए, स्ट्रीम किए गए एसेट्स को कैसे कैप्चर किया जाए, और जिम्मेदारी से क्लीन‑अप कैसे किया जाए। यह पैटर्न आपको रिसोर्स मैनेजमेंट पर पूर्ण नियंत्रण देता है, जिससे ऑन‑द‑फ़्लाई इमेज प्रोसेसिंग, CSS री‑राइटिंग या सुरक्षित स्टोरेज जैसे परिदृश्य संभव होते हैं। + +अगला कदम, **HTMLDocument लोडिंग** को विभिन्न रेंडरिंग विकल्पों के साथ एक्सप्लोर करें, या हैंडलर को **C# resource handler** इम्प्लीमेंटेशन में विस्तारित करें जो सीधे क्लाउड स्टोरेज में लिखता हो। अपने प्रोजेक्ट की विशिष्ट रिसोर्स वर्कफ़्लो के अनुसार `HandleResource` मेथड को प्रयोग करके अनुकूलित करें। + +## What Should You Learn Next? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोच को एक्सप्लोर कर सकें। + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/hongkong/net/advanced-features/_index.md b/html/hongkong/net/advanced-features/_index.md index 15dbfae199..dffe88229b 100644 --- a/html/hongkong/net/advanced-features/_index.md +++ b/html/hongkong/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Aspose.HTML for .NET 是一個功能強大的工具,可讓開發人員以程 了解如何使用 Aspose.HTML for .NET 從 JSON 資料動態產生 HTML 文件。在 .NET 應用程式中利用 HTML 操作的強大功能。 ### [如何在 C# 中以程式方式合併字型 – 步驟指南](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) 本指南逐步說明如何在 C# 中使用程式碼合併多個字型檔案,打造自訂字型資源。 +### [在 C# 中建立粗斜體字型 – 步驟指南](./create-bold-italic-font-in-c-step-by-step-guide/) +本指南逐步說明如何在 C# 中建立粗斜體字型,以提升字型樣式的呈現。 ## 結論 diff --git a/html/hongkong/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/hongkong/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..cbf4336a78 --- /dev/null +++ b/html/hongkong/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-08-15 +description: 快速在 C# 中建立粗斜體字型。學習如何使用內建的 Font 類別在 C# 中建立帶有粗體與斜體樣式的字型。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: zh-hant +lastmod: 2026-08-15 +og_description: 在 C# 中建立粗斜體字型,並提供清晰範例。本教學說明如何使用 FontStyle 標誌在 C# 中建立字型,並解說常見的陷阱。 +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: 在 C# 中建立粗斜體字型 – 完整程式設計指南 +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: 在 C# 中建立粗斜體字型 – 步驟指南 +url: /zh-hant/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立粗斜體字型 – 步驟指南 + +如果你需要在 C# 中**建立粗斜體字型**,本指南會精確說明如何操作。你將看到一個完整、可執行的範例,同時示範如何使用標準 .NET `Font` 類別**在 C# 中建立字型**。 + +在 Windows 桌面應用程式、產生 PDF,或在伺服器上渲染 HTML 時,使用自訂字型是常見的工作。完成本教學後,你將能夠建立同時具備粗體與斜體的字型,了解為何使用位元運算子 `|`,以及處理字型系列缺失等常見例外情況。 + +## 你將學會 + +* 如何匯入處理字型所需的命名空間。 +* 結合 `FontStyle.Bold` 與 `FontStyle.Italic` 的語法。 +* 如何驗證字型是否成功建立。 +* 當請求的字型系列未安裝時的備援處理技巧。 + +不需要任何外部函式庫——全部使用 .NET Framework / .NET Core 基礎類別庫。 + +## 前置條件 + +* .NET 6.0 SDK 或更新版本(此程式碼亦可於 .NET Framework 4.6+ 執行)。 +* 程式碼編輯器或 IDE(Visual Studio、VS Code、Rider 等)。 +* 基本的 C# 語法概念。 + +符合上述前置條件後,即可直接依照步驟操作,無需額外設定。 + +## 步驟 1:加入必要的 using 指示詞 + +`Font` 類別位於 `System.Drawing` 命名空間,該命名空間屬於 .NET Core/.NET 5+ 的 `System.Drawing.Common` NuGet 套件。請在檔案頂部加入此命名空間: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **為何此步驟重要** – 若缺少 `using System.Drawing;`,編譯器將找不到 `Font` 或 `FontStyle`,導致出現「找不到類型或命名空間名稱」的錯誤。 + +## 步驟 2:使用位元 OR 運算子結合粗體與斜體樣式 + +在 .NET 中,`FontStyle` 是一個標記了 `[Flags]` 屬性的列舉。這表示可以使用 `|`(位元 OR)運算子合併多個值: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### 說明 + +* `"Arial"` – 字型系列名稱。若系統未安裝 Arial,建構子會回退至預設字型。 +* `12` – 點數大小。 +* `FontStyle.Bold | FontStyle.Italic` – 結合兩個樣式旗標。`|` 運算子會合併每個旗標的二進位表示,產生同時代表「粗體 + 斜體」的單一值。 + +> **小技巧**:始終使用列舉名稱(`FontStyle.Bold`)而非魔法數字;這可提升可讀性,並避免列舉值變更時產生錯誤。 + +## 步驟 3:驗證已建立的字型(可選但建議執行) + +列印字型屬性可協助確認樣式組合是否成功,特別是在新機器上除錯時。 + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**預期輸出** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +若輸出同時列出 `Bold` 與 `Italic`,表示字型已正確建立。 + +## 步驟 4:繪製樣本字串(視覺確認) + +在 console 應用程式中無法直接看到字形樣式,但可產生圖片以證明結果。以下程式碼會使用粗斜體字型繪製「Hello, World!」並存為 *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +程式執行完畢後,開啟 *sample.png* 即可看到以粗斜體樣式呈現的文字。 + +![使用粗斜體字型渲染的範例文字](sample.png) + +*圖片說明文字:在 C# 主控台視窗中以粗斜體 Arial 字型渲染的文字截圖* – 此說明文字符合 SEO 對圖片 alt 文字的要求。 + +## 步驟 5:當字型系列不可用時的優雅備援 + +若請求的系列(例如「Arial」)未安裝,`Font` 建構子會拋出 `ArgumentException`。將建立程式碼包在 `try/catch` 區塊中,並回退至已知安全的字型(如「Segoe UI」)。 + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**為何需要這樣處理?** 在容器化或無頭環境中,預設字型集合可能與一般桌面不同。提供備援可避免執行時崩潰,確保樣式一致。 + +## 完整、可執行的範例 + +將上述所有步驟整合,即可得到以下完整程式碼,直接複製、貼上並執行: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### 如何執行 + +1. 將程式碼儲存為 `Program.cs`。 +2. 在該檔案所在目錄開啟終端機。 +3. 執行 `dotnet new console -n FontDemo`(若需要建立專案骨架)。 +4. 用上述程式碼取代產生的 `Program.cs`。 +5. 執行 `dotnet add package System.Drawing.Common`(.NET Core/5+ 必須)。 +6. 使用 `dotnet run` 進行建置與執行。 + +你將在主控台看到字型屬性的確認訊息,且 `sample.png` 會出現在專案資料夾中。 + +## 常見陷阱與避免方式 + +| 陷阱 | 為何會發生 | 解決方法 | +|------|------------|----------| +| **缺少 `System.Drawing.Common` 套件** | .NET Core 預設不包含 `System.Drawing`。 | 執行 `dotnet add package System.Drawing.Common`。 | +| **字型系列未安裝** | 無頭 Docker 映像常缺少 Windows 字型。 | 使用備援字型或在容器中安裝所需字型。 | +| **錯誤使用 `|`** | 使用 `+` 取代 `|` 會產生無效的組合。 | 必須以位元 OR 運算子 (`|`) 結合 `FontStyle` 值。 | +| **未釋放 `Font` 物件** | 未呼叫 `Dispose` 會導致 GDI 資源泄漏。 | 將 `Font` 包在 `using` 區塊,或在使用完畢後呼叫 `font.Dispose()`。 | + +## 結論 + +你現在已掌握如何在 C# 中**建立粗斜體字型**,以及如何安全且有效率地**在 C# 中建立字型**。本教學涵蓋了匯入正確命名空間、結合 `FontStyle` 旗標、驗證結果、繪製視覺樣本,以及處理字型系列缺失的情況。 + +接下來,你可以探索: + +* **建立底線或刪除線字型** – 加入 `FontStyle.Underline` 或 `FontStyle.Strikeout`。 +* **使用自訂 TrueType 字型** – 以 `PrivateFontCollection` 載入 `.ttf` 檔案。 +* **在 WinForms、WPF 或 PDF 產生中套用字型** – 同一個 `Font` 物件可傳遞給 UI 控制項或第三方函式庫。 + +歡迎自行嘗試不同的字型系列、大小與樣式組合。若遇到問題,請再次檢視「常見陷阱」表格或參考官方 [.NET 文件:System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font)。祝程式開發愉快! + +## 下一步該學什麼? + +以下教學與本指南的技術緊密相關,能在此基礎上延伸更多 API 功能,並提供完整的程式碼範例與逐步說明,協助你在專案中探索不同的實作方式。 + +- [在 C# 中以程式方式合併字型 – 步驟指南](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [建立具樣式文字的 HTML 文件並匯出為 PDF – 完整指南](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [將 docx 轉換為 png – 建立 zip 壓縮檔的 C# 教學](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/hongkong/net/working-with-html-documents/_index.md b/html/hongkong/net/working-with-html-documents/_index.md index d2685fbe51..02f76be3b7 100644 --- a/html/hongkong/net/working-with-html-documents/_index.md +++ b/html/hongkong/net/working-with-html-documents/_index.md @@ -41,6 +41,8 @@ HTML 文件是網路的支柱,能夠有效地創建和操作它們對於任何 本教學說明如何在 C# 中使用自訂資源處理程式將 HTML 內容保存至檔案或串流,涵蓋完整步驟與範例。 ### [如何使用 CSS 與 C# 加粗標題 – 完整步驟指南](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [在 C# 中建立自訂資源處理程式以載入 HTML](./create-custom-resource-handler-in-c-for-html-loading/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/hongkong/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/hongkong/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..c9e9a494ac --- /dev/null +++ b/html/hongkong/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-08-15 +description: 在 C# 中建立自訂資源處理程式,以管理 HTML 資源(如圖片與 CSS)。學習 HTMLLoadOptions、記憶體串流與 HTMLDocument + 載入。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: zh-hant +lastmod: 2026-08-15 +og_description: 在 C# 中建立自訂資源處理程式,以控制 HTML 資源的串流方式。本教學示範 HTMLLoadOptions 的設定、記憶體串流處理,以及使用自訂邏輯載入 + HTMLDocument。 +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: 在 C# 中建立自訂資源處理程式 – HTML 資源管理完整指南 +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: 在 C# 中建立自訂資源處理程式以載入 HTML +url: /zh-hant/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立自訂資源處理程式以載入 HTML + +如果你需要 **create custom resource handler** 來處理 HTML 檔案,本指南將會一步一步說明。你將學會在載入 HTML 文件時攔截圖片、CSS 以及其他資產,使用 `HTMLLoadOptions` 與基於記憶體的串流。 + +本教學涵蓋實作可重複使用的處理程式、設定載入選項,以及驗證資源是否正確被擷取的全部步驟。無需額外文件——只要以下程式碼與說明即可。 + +## 前置條件 + +- .NET 6.0 或更新版本 +- 基本的 C# 使用經驗 +- 參考提供 `HTMLDocument`、`HtmlLoadOptions` 與 `ResourceHandler` 的 HTML 處理函式庫(例如 GroupDocs.Viewer for .NET) + +## 解決方案概觀 + +我們將會: + +1. **建立自訂資源處理程式**,繼承 `ResourceHandler`。 +2. 設定 `HTMLLoadOptions` 以使用此處理程式。 +3. 使用 `HTMLDocument` 載入 HTML 檔案,讓處理程式為每個資源提供串流。 +4. (可選)將取得的資源寫入磁碟以作驗證。 + +每個步驟皆附完整原始碼與背後的原理說明。 + +## 步驟 1:定義自訂資源處理程式類別 + +建立自訂處理程式即是覆寫 `HandleResource`,讓函式庫能將資源位元組寫入你自行控制的串流。使用 `MemoryStream` 可將資料保留在記憶體中,適合測試或後續處理。 + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**為什麼重要:** +覆寫 `HandleResource` 讓你完全掌控資源資料的去向。日後若需快取圖片、轉換 CSS,或記錄資源使用情況,只要把 `MemoryStream` 換成任何自訂的串流實作即可。 + +## 步驟 2:設定 `HTMLLoadOptions` 以使用處理程式 + +`HTMLLoadOptions` 允許你將處理程式插入載入流程。設定 `ResourceHandler` 屬性即可讓檢視器在遇到每個外部資產時呼叫 `MyHandler`。 + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**為什麼重要:** +若未指定 `ResourceHandler`,檢視器會將資源寫入預設位置(通常是暫存資料夾)。透過自訂處理程式,你 **create custom resource handler** 的行為即可符合應用程式的儲存策略。 + +## 步驟 3:使用已設定的選項載入 HTML 文件 + +現在載入 HTML 檔案。檢視器會對每個遇到的資源呼叫 `MyHandler.HandleResource`。 + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +此時 HTML 內容已完成解析,所有外部資源皆已透過 `MyHandler` 提供的記憶體緩衝區串流。 + +## 步驟 4(可選):存取擷取到的資源 + +若需要檢查或永久保存資源,可修改 `MyHandler`,將每個 `MemoryStream` 依資源名稱存入字典。 + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +載入完成後,你可以遍歷 `handler.Resources`,將每個資源寫入磁碟: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**為什麼重要:** +保存資源可進行後續處理,例如影像優化、CSS 壓縮或歸檔。也能實際驗證 **create custom resource handler** 的邏輯是否如預期運作。 + +## 步驟 5:清理資源 + +`HTMLDocument` 與任何串流都應在使用完畢後釋放,以免佔用非受控資源。 + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## 完整可執行範例 + +以下是一個獨立程式,示範從類別定義到資源抽取的全部步驟。 + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**預期輸出** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +主控台會列出每個由檢視器透過自訂處理程式串流的資源,證明 **create custom resource handler** 工作流程已成功。 + +## 常見問題與邊緣案例 + +| 問題 | 答案 | +|----------|--------| +| *如果資源很大(例如高解析度影像)怎麼辦?* | 改用指向暫存資料夾的 `FileStream` 取代 `MemoryStream`,可避免記憶體過度佔用。 | +| *我可以依類型過濾資源嗎?* | 在 `HandleResource` 內檢查 `info.MimeType` 或 `info.Extension`,對不需要的類型回傳 `null`。回傳 `null` 會讓檢視器跳過該資源。 | +| *需要考慮執行緒安全嗎?* | 若同一個處理程式實例會被多個併發載入共用,請使用 lock 保護 `Resources` 字典,或改用並行集合。 | +| *如何支援相對 URL?* | `ResourceInfo` 包含原始 URL,你可以在儲存前將其與 HTML 檔案的基礎路徑結合,以解析相對參照。 | + +## 結論 + +現在你已掌握如何在 C# 中 **create custom resource handler** 以載入 HTML,設定 `HTMLLoadOptions`、擷取串流資產,並負責任地釋放資源。此模式讓你全面掌控資源管理,適用於即時影像處理、CSS 重寫或安全儲存等情境。 + +接下來,可探索相關主題,例如使用不同渲染選項的 **HTMLDocument loading**,或將處理程式擴充為直接寫入雲端儲存的 **C# resource handler** 實作。多加實驗 `HandleResource` 方法,讓它符合專案的特定資源工作流程。 + +## 接下來該學什麼? + +以下教學與本指南技術緊密相關,能幫助你進一步掌握 API 功能並探索其他實作方式: + +- [在 C# 中從字串建立 HTML – 自訂資源處理程式指南](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [C# 自訂資源處理程式 – 將 HTML 轉成 ZIP 教程](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [如何在 C# 中保存 HTML – 使用自訂資源處理程式的完整指南](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/hungarian/net/advanced-features/_index.md b/html/hungarian/net/advanced-features/_index.md index 6ce1f5d073..447fe5322c 100644 --- a/html/hungarian/net/advanced-features/_index.md +++ b/html/hungarian/net/advanced-features/_index.md @@ -44,7 +44,8 @@ Ismerje meg, hogyan konvertálhat HTML-t PDF-be, XPS-be és képekké az Aspose. Ismerje meg, hogyan használhatja az Aspose.HTML for .NET-et HTML-dokumentumok dinamikus generálására JSON-adatokból. Használja ki a HTML-kezelés erejét .NET-alkalmazásaiban. ### [Memóriafolyam létrehozása C# – Egyéni stream létrehozási útmutató](./create-memory-stream-c-custom-stream-creation-guide/) Tanulja meg, hogyan hozhat létre egyedi memóriafolyamot C#-ban az Aspose.HTML használatával. - +### [Félkövér dőlt betű létrehozása C#‑ban – lépésről‑lépésre útmutató](./create-bold-italic-font-in-c-step-by-step-guide/) +Tanulja meg, hogyan hozhat létre félkövér és dőlt betűstílusú szöveget C#‑ban az Aspose.HTML segítségével, részletes lépésekkel. ## Következtetés diff --git a/html/hungarian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/hungarian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..e20d2748ce --- /dev/null +++ b/html/hungarian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-08-15 +description: Készíts gyorsan félkövér dőlt betűt C#‑ban. Tanuld meg, hogyan hozhatsz + létre betűtípust C#‑ban félkövér és dőlt stílussal a beépített Font osztály segítségével. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: hu +lastmod: 2026-08-15 +og_description: Készíts félkövér dőlt betűt C#-ban egy világos példával. Ez az útmutató + bemutatja, hogyan hozhatunk létre betűtípust C#-ban a FontStyle zászlók használatával, + és ismerteti a gyakori buktatókat. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Félkövér dőlt betű létrehozása C#-ban – teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Félkövér dőlt betűtípus létrehozása C#‑ban – lépésről‑lépésre útmutató +url: /hu/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Félkövér dőlt betűkészlet létrehozása C#‑ban – lépésről‑lépésre útmutató + +Ha **félkövér dőlt betűt** kell létrehoznod C#‑ban, ez az útmutató pontosan megmutatja, hogyan teheted meg. Egy teljes, futtatható példát is láthatsz, amely bemutatja, hogyan **hozz létre betűtípust C#‑ban** a szabványos .NET `Font` osztály használatával. + +Az egyedi betűtípusokkal való munka mindennapos része a Windows asztali alkalmazások építésének, PDF‑ek generálásának vagy a HTML szerveren történő renderelésének. A tutorial végére képes leszel egy olyan betűtípust példányosítani, amely egyszerre félkövér és dőlt, megérted, miért használjuk a bitwise `|` operátort, és kezelni tudod a gyakori szélhelyzeteket, például a hiányzó betűcsaládokat. + +## Mit fogsz megtanulni + +* Hogyan importáld a betűkezeléshez szükséges névtereket. +* A `FontStyle.Bold` és `FontStyle.Italic` kombinálásának szintaxisa. +* Hogyan ellenőrizd, hogy a betűtípus sikeresen létrejött-e. +* Tippek a visszaesés (fallback) kezelésére, ha a kért család nincs telepítve. + +Nem szükséges külső könyvtár—minden a .NET Framework / .NET Core alaposztálykönyvtárát használja. + +## Előfeltételek + +* .NET 6.0 SDK vagy újabb (a kód .NET Framework 4.6+‑on is működik). +* Kódszerkesztő vagy IDE (Visual Studio, VS Code, Rider, stb.). +* Alapvető ismeretek a C# szintaxisról. + +Ha megfelelsz ezeknek az előfeltételeknek, a lépéseket további beállítások nélkül követheted. + +## 1. lépés: Add meg a szükséges using direktívákat + +A `Font` osztály a `System.Drawing` névtérben található, amely a `System.Drawing.Common` NuGet csomag része a .NET Core/.NET 5+ számára. Add hozzá a névteret a fájlod tetején: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Miért fontos ez a lépés** – A `using System.Drawing;` sor nélkül a fordító nem tudja megtalálni a `Font` vagy `FontStyle` típusokat, ami “type or namespace name could not be found” hibához vezet. + +## 2. lépés: Kombináld a félkövér és dőlt stílusokat a bitwise OR operátorral + +A .NET‑ben a `FontStyle` egy `[Flags]` attribútummal ellátott enum. Ez azt jelenti, hogy több értéket kombinálhatsz a `|` (bitwise OR) operátorral: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Magyarázat + +* `"Arial"` – a betűcsalád neve. Ha a rendszer nem rendelkezik Arial‑ral, a konstruktor az alapértelmezett betűtípusra tér vissza. +* `12` – pontméret. +* `FontStyle.Bold | FontStyle.Italic` – kombinálja a két stílusjelzőt. A `|` operátor egyesíti minden jelző bináris ábrázolását, egyetlen értéket hozva létre, amely a “félkövér + dőlt” kombinációt jelenti. + +> **Pro tipp:** Mindig az enum neveket (`FontStyle.Bold`) használd a varázsszámok helyett; ez javítja az olvashatóságot és megakadályozza a hibákat, ha az enum értékei megváltoznak. + +## 3. lépés: Ellenőrizd a létrehozott betűtípust (opcionális, de ajánlott) + +A betűtípus tulajdonságainak kiírása segít megerősíteni, hogy a stíluskombináció sikeres volt, különösen új gépen történő hibakereséskor. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Várható kimenet** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Ha a kimenet mind `Bold`, mind `Italic` értékeket listáz, a betűtípus helyesen lett létrehozva. + +## 4. lépés: Minta szöveg renderelése (vizuális megerősítés) + +Amikor egy konzolos alkalmazást futtatsz, nem láthatod a tényleges glif stílusát, de generálhatsz egy képet a végeredmény bizonyításához. Az alábbi kódrészlet a “Hello, World!” szöveget rajzolja a félkövér‑dőlt betűtípussal, és elmenti *sample.png* néven: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +A program futása után nyisd meg a *sample.png* fájlt, hogy lásd a szöveget a félkövér dőlt stílussal renderelve. + +![Minta szöveg renderelve félkövér dőlt betűtípussal](sample.png) + +*Kép alt szöveg: Képernyőkép a félkövér dőlt Arial betűtípussal renderelt szövegről egy C# konzolablakban* – ez az alt szöveg megfelel a SEO követelménynek a képek alt szövegére vonatkozóan. + +## 5. lépés: Elegáns visszaesés, ha a betűcsalád nem érhető el + +Ha a kért család (pl. “Arial”) nincs telepítve, a `Font` konstruktor `ArgumentException`‑t dob. A létrehozást tedd egy `try/catch` blokkba, és térj vissza egy ismert, biztonságos betűtípusra, például a “Segoe UI”‑ra. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Miért kezeljük ezt?** +Konténerizált vagy fej nélküli környezetekben az alapértelmezett betűkészlet eltérhet egy tipikus asztali géptől. Visszaesés biztosítása megakadályozza a futási időbeli összeomlásokat és konzisztens stílust garantál. + +## Teljes, futtatható példa + +Mindent összevonva, itt egy teljes program, amelyet másolhatsz, beilleszthetsz és futtathatsz: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Hogyan futtassuk + +1. Mentsd a kódot `Program.cs` néven. +2. Nyiss egy terminált a fájl könyvtárában. +3. Futtasd a `dotnet new console -n FontDemo` parancsot (ha projektszerkezetre van szükséged). +4. Cseréld le a generált `Program.cs`‑t a fenti kóddal. +5. Add hozzá a `dotnet add package System.Drawing.Common` csomagot (szükséges .NET Core/5+ esetén). +6. Építsd és futtasd a `dotnet run` paranccsal. + +A konzol kimenetben láthatod a betűtípus tulajdonságait, és a `sample.png` megjelenik a projekt mappájában. + +## Gyakori buktatók és hogyan kerüld el őket + +| Buktató | Miért fordul elő | Megoldás | +|---------|------------------|----------| +| **Hiányzó `System.Drawing.Common` csomag** | .NET Core alapértelmezés szerint nem tartalmazza a `System.Drawing`‑t. | Futtasd a `dotnet add package System.Drawing.Common` parancsot. | +| **Betűcsalád nincs telepítve** | Fej nélküli Docker képek gyakran hiányolják a Windows betűtípusokat. | Használj visszaeső betűtípust, vagy telepítsd a szükséges betűtípusokat a konténerben. | +| **Helytelen `|` használat** | `+` használata a `|` helyett érvénytelen kombinációt eredményez. | Mindig a `FontStyle` értékeket kombináld a bitwise OR operátorral (`|`). | +| **A `Font` objektum eldobása** | A `Dispose` hívás hiánya GDI erőforrás szivárgáshoz vezethet. | Tedd a `Font`‑ot egy `using` blokkba, vagy hívd meg a `font.Dispose()`‑t a használat után. | + +## Következtetés + +Most már tudod, hogyan **hozz létre félkövér dőlt betűtípust** C#‑ban, és hogyan **hozz létre betűtípust C#‑ban** biztonságosan és hatékonyan. A tutorial bemutatta a megfelelő névtér importálását, a `FontStyle` jelzők kombinálását, az eredmény ellenőrzését, egy vizuális minta renderelését, valamint a hiányzó betűcsaládok kezelését. + +A következő lépésként érdemes lehet: + +* **Aláhúzott vagy áthúzott betűtípusok létrehozása** – add `FontStyle.Underline` vagy `FontStyle.Strikeout`. +* **Egyedi TrueType betűtípusok használata** – tölts be egy `.ttf` fájlt a `PrivateFontCollection`‑al. +* **Betűtípusok alkalmazása WinForms‑ben, WPF‑ben vagy PDF generálásnál** – ugyanaz a `Font` objektum átadható UI vezérlőknek vagy harmadik fél könyvtáraknak. + +Nyugodtan kísérletezz különböző családokkal, méretekkel és stíluskombinációkkal. Ha problémába ütközöl, nézd át újra a “Gyakori buktatók” táblázatot, vagy tekintsd meg a hivatalos [.NET dokumentációt a System.Drawing.Font‑ról](https://learn.microsoft.com/dotnet/api/system.drawing.font). Boldog kódolást! + +## Mit érdemes legközelebb megtanulni? + +A következő tutorialok 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ódpéldákat 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 kombinálj betűtípusokat programozott módon C#‑ban – Lépésről‑lépésre útmutató](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [HTML dokumentum létrehozása formázott szöveggel és exportálás PDF‑be – Teljes útmutató](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [docx konvertálása png‑re – zip archívum létrehozása C# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/hungarian/net/working-with-html-documents/_index.md b/html/hungarian/net/working-with-html-documents/_index.md index 81c4e72f31..f733b5dd8c 100644 --- a/html/hungarian/net/working-with-html-documents/_index.md +++ b/html/hungarian/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ Miután megértette az alapokat, mélyebbre ásunk az alkotás folyamatában. Eb Most emeljük tudását a következő szintre. A HTML-dokumentumok szerkesztése gyakori feladat a webfejlesztők számára, és az Aspose.HTML jelentősen leegyszerűsíti ezt a folyamatot. Ebben a részben a dokumentumok létrehozásával, manipulálásával és stílusával foglalkozunk. Felfedezi, hogyan javíthatja webtartalma megjelenését és funkcionalitását, hogy vonzóvá és felhasználóbaráttá tegye azt. ### [HTML mentése C#-ban – Teljes útmutató egy egyéni erőforráskezelő használatával](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [Egyéni erőforráskezelő létrehozása C#-ban a HTML betöltéséhez](./create-custom-resource-handler-in-c-for-html-loading/) + ### [Hogyan tegyünk félkövér címet CSS‑el és C#‑val – Teljes lépésről‑lépésre útmutató](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) Ismerje meg, hogyan formázhatja félkövérre a HTML‑címeket CSS‑sel és C#‑kóddal, részletes példákkal. diff --git a/html/hungarian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/hungarian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..a832db1fba --- /dev/null +++ b/html/hungarian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-08-15 +description: Készíts egy egyéni erőforráskezelőt C#-ban, amely kezeli a HTML erőforrásokat, + például képeket és CSS-t. Ismerkedj meg a HTMLLoadOptions, memóriaáramok és HTMLDocument + betöltésével. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: hu +lastmod: 2026-08-15 +og_description: Egyedi erőforráskezelő létrehozása C#-ban az HTML-erőforrások streamelésének + szabályozásához. Ez az útmutató bemutatja az HTMLLoadOptions beállítását, a memóriafolyam + kezelését, valamint az HTMLDocument betöltését egyedi logikával. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Egyedi erőforráskezelő létrehozása C#-ban – teljes útmutató HTML erőforrás-kezeléshez +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Egyedi erőforráskezelő létrehozása C#-ban HTML betöltéshez +url: /hu/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Egyedi erőforráskezelő létrehozása C#‑ban HTML betöltéshez + +Ha **egyedi erőforráskezelőt** kell létrehoznod HTML fájlokhoz, ez az útmutató pontosan megmutatja, hogyan. Megtanulod, hogyan lehet elfogni a képeket, a CSS‑t és egyéb erőforrásokat egy HTML dokumentum betöltése közben, a `HTMLLoadOptions` és egy memória‑alapú stream használatával. + +Az útmutató mindent lefed, ami egy újrahasználható kezelő megvalósításához, a betöltési beállítások konfigurálásához és az erőforrások helyes rögzítésének ellenőrzéséhez szükséges. Nem kell külső dokumentáció – csak az alábbi kód és a magyarázatok. + +## Előfeltételek + +- .NET 6.0 vagy újabb +- Alapvető C# ismeretek +- Hivatkozás a HTML feldolgozó könyvtárra, amely biztosítja a `HTMLDocument`, `HtmlLoadOptions` és `ResourceHandler` osztályokat (pl. GroupDocs.Viewer for .NET) + +## A megoldás áttekintése + +A következőket fogjuk tenni: + +1. **Egyedi erőforráskezelő létrehozása** a `ResourceHandler` leszármaztatásával. +2. `HTMLLoadOptions` konfigurálása a kezelő használatához. +3. HTML fájl betöltése a `HTMLDocument`‑tel, miközben a kezelő minden erőforráshoz streamet biztosít. +4. (Opcionális) A kapott erőforrások lemezre mentése ellenőrzés céljából. + +Minden lépéshez teljes forráskód és a mögöttes gondolatmenet tartozik. + +## 1. lépés: Az egyedi erőforráskezelő osztály definiálása + +Egyedi kezelő létrehozása azt jelenti, hogy felülírjuk a `HandleResource` metódust, hogy a könyvtár a erőforrás bájtjait egy általunk irányított stream‑be írja. A `MemoryStream` használata az adatot memóriában tartja, ami ideális teszteléshez vagy további feldolgozáshoz. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Miért fontos:** +A `HandleResource` felülírása teljes irányítást ad arra, hogy hová kerülnek az erőforrás adatok. Ha később képeket szeretnél gyorsítótárazni, CSS‑t átalakítani vagy erőforrás‑használatot naplózni, a `MemoryStream`‑et bármilyen egyedi stream megvalósítással helyettesítheted. + +## 2. lépés: `HTMLLoadOptions` konfigurálása a kezelő használatához + +A `HTMLLoadOptions` lehetővé teszi, hogy a kezelőt beilleszd a betöltési csővezetékbe. A `ResourceHandler` tulajdonság beállítása azt mondja a megjelenítőnek, hogy minden külső eszközhöz hívja meg a `MyHandler`‑t. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Miért fontos:** +A `ResourceHandler` megadása nélkül a megjelenítő az erőforrásokat az alapértelmezett helyre (gyakran egy ideiglenes mappába) írná. A saját kezelő megadása **egyedi erőforráskezelő** viselkedést hoz létre, amely illeszkedik az alkalmazásod tárolási stratégiájához. + +## 3. lépés: A HTML dokumentum betöltése a konfigurált beállításokkal + +Most töltsd be a HTML fájlt. A megjelenítő minden megtalált erőforráshoz meghívja a `MyHandler.HandleResource`‑t. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Ekkor a HTML tartalom feldolgozásra kerül, és minden külső erőforrás a `MyHandler` által biztosított memória‑bufferbe kerül. + +## 4. lépés (opcionális): A rögzített erőforrások elérése + +Ha meg szeretnéd vizsgálni vagy megőrizni az erőforrásokat, módosíthatod a `MyHandler`‑t úgy, hogy minden `MemoryStream`‑et egy szótárba mentse, amelynek kulcsa az erőforrás neve. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Betöltés után iterálhatsz a `handler.Resources`‑en, és mindegyiket lemezre írhatod: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Miért fontos:** +Az erőforrások tárolása lehetővé teszi a későbbi feldolgozást, például képek optimalizálását, CSS minifikálását vagy archiválását. Emellett kézzelfogható ellenőrzést nyújt arról, hogy a **create custom resource handler** logika a várt módon működik. + +## 5. lépés: Tisztítás + +A `HTMLDocument`‑et és minden stream‑et el kell engedni, hogy felszabaduljanak a nem kezelt erőforrások. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Teljes, futtatható példa + +Az alábbi önálló program bemutatja az összes lépést az osztálydefiníciótól az erőforrás‑kivonásig. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Várt kimenet** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +A konzol felsorolja minden olyan erőforrást, amelyet a megjelenítő a saját egyedi kezelődön keresztül streamelt, ezzel megerősítve, hogy a **create custom resource handler** munkafolyamat sikeres volt. + +## Gyakori kérdések és széljegyek + +| Kérdés | Válasz | +|----------|--------| +| *Mi a teendő, ha egy erőforrás nagy (pl. nagy felbontású kép)?* | Cseréld le a `MemoryStream`‑et egy `FileStream`‑re, amely egy ideiglenes mappára mutat. Ez megakadályozza a túlzott memóriahasználatot. | +| *Szűrhetek-e erőforrásokat típus szerint?* | A `HandleResource`‑ben ellenőrizheted az `info.MimeType` vagy `info.Extension` értékét, és `null`‑t visszaadva kihagyhatod a nem kívánt típusokat. A `null` visszaadása azt jelzi a megjelenítőnek, hogy hagyja ki az erőforrást. | +| *Szükséges a szálbiztonság?* | Ha ugyanazt a kezelőpéldányt több párhuzamos betöltéshez használod, védd a `Resources` szótárat lock‑kal, vagy használj párhuzamos gyűjteményt. | +| *Hogyan kezelem a relatív URL‑eket?* | A `ResourceInfo` tartalmazza az eredeti URL‑t; kombinálhatod a HTML fájl alapútvonalával a relatív hivatkozások feloldásához, mielőtt tárolnád őket. | + +## Összegzés + +Most már tudod, hogyan **create custom resource handler** C#‑ban HTML betöltéshez, hogyan konfiguráld a `HTMLLoadOptions`‑t, hogyan rögzítsd a stream‑elt eszközöket, és hogyan tisztítsd meg a forrásokat felelősségteljesen. Ez a minta teljes irányítást ad az erőforrás‑kezelés felett, lehetővé téve olyan forgatókönyveket, mint a valós‑időben történő kép‑feldolgozás, CSS‑átírás vagy biztonságos tárolás. + +Ezután nézd meg a kapcsolódó témákat, például a **HTMLDocument betöltését** különböző megjelenítési beállításokkal, vagy bővítsd a kezelőt **C# resource handler** megvalósításokra, amelyek közvetlenül a felhő tárolóba írnak. Kísérletezz a `HandleResource` metódussal, hogy a projekted specifikus erőforrás‑folyamataira szabjad. + +## Mit tanulj meg legközelebb? + +Az alábbi oktatóanyagok szorosan kapcsolódnak, és a jelen útmutatóban bemutatott technikákra építenek. Minden forrás teljes, működő kódpéldákat tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek további API‑funkciók elsajátításában és alternatív megvalósítási megközelítések felfedezésében saját projektjeidben. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/indonesian/net/advanced-features/_index.md b/html/indonesian/net/advanced-features/_index.md index 963c612bbf..a64c144eda 100644 --- a/html/indonesian/net/advanced-features/_index.md +++ b/html/indonesian/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Pelajari cara mengonversi HTML ke PDF, XPS, dan gambar dengan Aspose.HTML untuk Pelajari cara menggunakan Aspose.HTML untuk .NET guna membuat dokumen HTML secara dinamis dari data JSON. Manfaatkan kekuatan manipulasi HTML dalam aplikasi .NET Anda. ### [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah‑demi‑Langkah](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Pelajari cara menggabungkan beberapa font menjadi satu file menggunakan C# dengan Aspose.HTML, lengkap dengan contoh kode langkah demi langkah. +### [Buat Font Tebal Miring di C# – Panduan Langkah‑demi‑Langkah](./create-bold-italic-font-in-c-step-by-step-guide/) +Pelajari cara membuat font tebal miring di C# dengan panduan langkah demi langkah menggunakan Aspose.HTML. ## Kesimpulan diff --git a/html/indonesian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/indonesian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..d410869baa --- /dev/null +++ b/html/indonesian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-08-15 +description: Buat font tebal miring di C# dengan cepat. Pelajari cara membuat font + di C# dengan gaya tebal dan miring menggunakan kelas Font bawaan. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: id +lastmod: 2026-08-15 +og_description: Buat font tebal miring di C# dengan contoh yang jelas. Tutorial ini + menunjukkan cara membuat font di C# menggunakan flag FontStyle dan menjelaskan jebakan + umum. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Buat font tebal miring di C# – panduan pemrograman lengkap +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Buat font tebal miring di C# – panduan langkah demi langkah +url: /id/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat font tebal miring di C# – panduan langkah demi langkah + +Jika Anda perlu **membuat font tebal miring** di C#, panduan ini menunjukkan secara tepat cara melakukannya. Anda akan melihat contoh lengkap yang dapat dijalankan yang juga memperlihatkan cara **membuat font di C#** menggunakan kelas standar .NET `Font`. + +Bekerja dengan font khusus merupakan bagian rutin dalam membangun aplikasi desktop Windows, menghasilkan PDF, atau merender HTML di server. Pada akhir tutorial ini Anda akan dapat menginstansiasi font yang sekaligus tebal dan miring, memahami mengapa operator bitwise `|` digunakan, dan menangani kasus tepi umum seperti keluarga font yang tidak ada. + +## Apa yang akan Anda pelajari + +* Cara mengimpor namespace yang diperlukan untuk penanganan font. +* Sintaks untuk menggabungkan `FontStyle.Bold` dan `FontStyle.Italic`. +* Cara memverifikasi bahwa font berhasil dibuat. +* Tips penanganan fallback ketika keluarga font yang diminta tidak terpasang. + +Tidak ada pustaka eksternal yang diperlukan—semua menggunakan .NET Framework / .NET Core base class library. + +## Prasyarat + +* .NET 6.0 SDK atau lebih baru (kode juga berfungsi pada .NET Framework 4.6+). +* Editor kode atau IDE (Visual Studio, VS Code, Rider, dll.). +* Familiaritas dasar dengan sintaks C#. + +Jika Anda memenuhi prasyarat ini, Anda dapat mengikuti langkah‑langkah tanpa pengaturan tambahan. + +## Langkah 1: Tambahkan direktif using yang diperlukan + +Kelas `Font` berada di namespace `System.Drawing`, yang merupakan bagian dari paket NuGet `System.Drawing.Common` untuk .NET Core/.NET 5+. Tambahkan namespace di bagian atas file Anda: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Mengapa langkah ini penting** – Tanpa baris `using System.Drawing;` kompiler tidak dapat menemukan `Font` atau `FontStyle`, sehingga menghasilkan error “type or namespace name could not be found”. + +## Langkah 2: Gabungkan gaya tebal dan miring dengan operator OR bitwise + +Di .NET, `FontStyle` adalah enum yang ditandai dengan atribut `[Flags]`. Ini berarti Anda dapat menggabungkan beberapa nilai menggunakan operator `|` (OR bitwise): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Penjelasan + +* `"Arial"` – nama keluarga font. Jika sistem tidak memiliki Arial terpasang, konstruktor akan kembali ke font default. +* `12` – ukuran poin. +* `FontStyle.Bold | FontStyle.Italic` – menggabungkan dua flag gaya. Operator `|` menggabungkan representasi biner masing‑masing flag, menghasilkan satu nilai yang mewakili “tebal + miring”. + +> **Pro tip:** Selalu gunakan nama enum (`FontStyle.Bold`) daripada angka ajaib; ini meningkatkan keterbacaan dan mencegah bug ketika nilai enum berubah. + +## Langkah 3: Verifikasi font yang dibuat (opsional namun disarankan) + +Mencetak properti font membantu Anda memastikan bahwa kombinasi gaya berhasil, terutama saat debugging pada mesin baru. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Output yang diharapkan** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Jika output menampilkan kedua `Bold` dan `Italic`, font telah dibuat dengan benar. + +## Langkah 4: Render string contoh (konfirmasi visual) + +Saat Anda menjalankan aplikasi konsol Anda tidak dapat melihat gaya glyph secara langsung, tetapi Anda dapat menghasilkan gambar untuk membuktikan hasilnya. Potongan kode berikut menggambar “Hello, World!” menggunakan font tebal‑miring dan menyimpannya sebagai *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Setelah program selesai, buka *sample.png* untuk melihat teks yang dirender dengan gaya tebal miring. + +![Sample text rendered with bold italic font](sample.png) + +*Teks alt gambar: Tangkapan layar teks yang dirender dengan font Arial tebal miring di jendela konsol C#* – teks alt ini memenuhi persyaratan SEO untuk alt gambar. + +## Langkah 5: Fallback yang elegan ketika keluarga font tidak tersedia + +Jika keluarga yang diminta (misalnya “Arial”) tidak terpasang, konstruktor `Font` akan melempar `ArgumentException`. Bungkus pembuatan dalam blok `try/catch` dan gunakan font cadangan yang aman seperti “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Mengapa menangani ini?** Pada lingkungan yang terkontainer atau tanpa tampilan (headless) set font default dapat berbeda dari desktop biasa. Menyediakan fallback mencegah crash pada runtime dan memastikan gaya tetap konsisten. + +## Contoh lengkap yang dapat dijalankan + +Menggabungkan semuanya, berikut program lengkap yang dapat Anda salin, tempel, dan jalankan: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Cara menjalankan + +1. Simpan kode ke file bernama `Program.cs`. +2. Buka terminal di direktori file tersebut. +3. Jalankan `dotnet new console -n FontDemo` (jika Anda memerlukan scaffold proyek). +4. Ganti `Program.cs` yang dihasilkan dengan kode di atas. +5. Jalankan `dotnet add package System.Drawing.Common` (diperlukan untuk .NET Core/5+). +6. Build dan jalankan dengan `dotnet run`. + +Anda akan melihat output konsol yang mengonfirmasi properti font, dan `sample.png` akan muncul di folder proyek. + +## Jebakan umum dan cara menghindarinya + +| Jebakan | Mengapa terjadi | Solusi | +|---------|----------------|--------| +| **Missing `System.Drawing.Common` package** | .NET Core tidak menyertakan `System.Drawing` secara default. | Jalankan `dotnet add package System.Drawing.Common`. | +| **Font family not installed** | Image Docker tanpa kepala biasanya tidak memiliki font Windows. | Gunakan font fallback atau instal font yang diperlukan di dalam container. | +| **Incorrect use of `|`** | Menggunakan `+` alih‑alih `|` menghasilkan kombinasi yang tidak valid. | Selalu gabungkan nilai `FontStyle` dengan operator OR bitwise (`|`). | +| **Disposing the `Font` object** | Tidak memanggil `Dispose` dapat menyebabkan kebocoran sumber daya GDI. | Bungkus `Font` dalam blok `using` atau panggil `font.Dispose()` setelah selesai. | + +## Kesimpulan + +Anda kini tahu cara **membuat font tebal miring** di C# dan cara **membuat font di C#** secara aman dan efisien. Tutorial ini mencakup impor namespace yang tepat, menggabungkan flag `FontStyle`, memverifikasi hasil, merender contoh visual, serta menangani keluarga font yang tidak ada. + +Selanjutnya, Anda dapat menjelajahi: + +* **Membuat font bergaris bawah atau coret** – tambahkan `FontStyle.Underline` atau `FontStyle.Strikeout`. +* **Menggunakan font TrueType khusus** – muat file `.ttf` dengan `PrivateFontCollection`. +* **Menerapkan font di WinForms, WPF, atau pembuatan PDF** – objek `Font` yang sama dapat diteruskan ke kontrol UI atau pustaka pihak ketiga. + +Silakan bereksperimen dengan berbagai keluarga, ukuran, dan kombinasi gaya. Jika Anda menemui masalah, tinjau kembali tabel “Jebakan umum” atau periksa dokumentasi resmi [.NET untuk System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Buat Dokumen HTML dengan Teks Bergaya dan Ekspor ke PDF – Panduan Lengkap](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [konversi docx ke png – buat arsip zip tutorial c#](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/indonesian/net/working-with-html-documents/_index.md b/html/indonesian/net/working-with-html-documents/_index.md index b7ad357be1..21cdea0989 100644 --- a/html/indonesian/net/working-with-html-documents/_index.md +++ b/html/indonesian/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ Setelah Anda memahami dasar-dasarnya, kita akan mempelajari lebih dalam proses p Sekarang, mari tingkatkan keterampilan Anda ke tingkat berikutnya. Mengedit dokumen HTML merupakan tugas umum bagi pengembang web, dan Aspose.HTML menyederhanakan proses ini secara signifikan. Di bagian ini, kami akan membahas pembuatan, manipulasi, dan penataan dokumen. Anda akan menemukan cara meningkatkan tampilan dan fungsionalitas konten web Anda, membuatnya menarik dan mudah digunakan. ### [Cara Menyimpan HTML di C# – Panduan Lengkap Menggunakan Penangan Sumber Daya Kustom](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [Cara Membuat Penangan Sumber Daya Kustom di C# untuk Memuat HTML](./create-custom-resource-handler-in-c-for-html-loading/) + ### [Cara Membuat Heading Tebal dengan CSS & C# – Panduan Lengkap Langkah demi Langkah](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/indonesian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/indonesian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..357f5c096f --- /dev/null +++ b/html/indonesian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-08-15 +description: Buat penangan sumber daya khusus di C# untuk mengelola sumber daya HTML + seperti gambar dan CSS. Pelajari HTMLLoadOptions, aliran memori, dan pemuatan HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: id +lastmod: 2026-08-15 +og_description: Buat penangan sumber daya khusus di C# untuk mengontrol cara aliran + sumber daya HTML. Tutorial ini menunjukkan pengaturan HTMLLoadOptions, penanganan + memory stream, dan pemuatan HTMLDocument dengan logika khusus. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Buat penangan sumber daya khusus di C# – panduan lengkap untuk manajemen + sumber daya HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Buat penangan sumber daya khusus di C# untuk memuat HTML +url: /id/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat custom resource handler di C# untuk pemuatan HTML + +Jika Anda perlu **create custom resource handler** untuk file HTML, panduan ini menunjukkan secara tepat caranya. Anda akan belajar cara menyela gambar, CSS, dan aset lainnya saat memuat dokumen HTML, menggunakan `HTMLLoadOptions` dan aliran berbasis memori. + +Tutorial ini mencakup semua yang diperlukan untuk mengimplementasikan handler yang dapat digunakan kembali, mengonfigurasi opsi pemuatan, dan memverifikasi bahwa sumber daya ditangkap dengan benar. Tidak diperlukan dokumentasi eksternal—hanya kode di bawah ini dan penjelasannya. + +## Prasyarat + +- .NET 6.0 atau yang lebih baru +- Familiaritas dasar dengan C# +- Referensi ke pustaka pemrosesan HTML yang menyediakan `HTMLDocument`, `HtmlLoadOptions`, dan `ResourceHandler` (misalnya GroupDocs.Viewer untuk .NET) + +## Gambaran solusi + +Kita akan: + +1. **Create a custom resource handler** dengan membuat subclass `ResourceHandler`. +2. Mengonfigurasi `HTMLLoadOptions` untuk menggunakan handler. +3. Memuat file HTML dengan `HTMLDocument` sementara handler menyediakan aliran untuk setiap sumber daya. +4. (Opsional) Menyimpan sumber daya yang diterima ke disk untuk verifikasi. + +Setiap langkah menyertakan kode sumber lengkap dan penjelasan di baliknya. + +## Langkah 1: Definisikan kelas custom resource handler + +Membuat handler khusus berarti menimpa `HandleResource` sehingga pustaka dapat menulis byte sumber daya ke aliran yang Anda kontrol. Menggunakan `MemoryStream` menjaga data tetap di memori, yang ideal untuk pengujian atau pemrosesan lebih lanjut. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Mengapa ini penting:** +Menimpa `HandleResource` memberi Anda kontrol penuh atas tempat data sumber daya disimpan. Jika nanti Anda perlu menyimpan cache gambar, mengubah CSS, atau mencatat penggunaan sumber daya, Anda dapat mengganti `MemoryStream` dengan implementasi aliran khusus apa pun. + +## Langkah 2: Konfigurasikan `HTMLLoadOptions` untuk menggunakan handler + +`HTMLLoadOptions` memungkinkan Anda menyambungkan handler ke pipeline pemuatan. Menetapkan properti `ResourceHandler` memberi tahu viewer untuk memanggil `MyHandler` untuk setiap aset eksternal. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Mengapa ini penting:** +Tanpa menetapkan `ResourceHandler`, viewer akan menulis sumber daya ke lokasi defaultnya (seringkali folder sementara). Dengan menentukan handler Anda sendiri, Anda **create custom resource handler** yang selaras dengan strategi penyimpanan aplikasi Anda. + +## Langkah 3: Muat dokumen HTML dengan opsi yang telah dikonfigurasi + +Sekarang muat file HTML. Viewer akan memanggil `MyHandler.HandleResource` untuk setiap sumber daya yang ditemukannya. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Pada titik ini konten HTML telah diparse, dan semua sumber daya eksternal telah dialirkan ke buffer memori yang disediakan oleh `MyHandler`. + +## Langkah 4 (opsional): Akses sumber daya yang ditangkap + +Jika Anda perlu memeriksa atau menyimpan sumber daya, Anda dapat memodifikasi `MyHandler` untuk menyimpan setiap `MemoryStream` dalam kamus yang diindeks dengan nama sumber daya. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Setelah pemuatan, Anda dapat mengiterasi `handler.Resources` dan menulis masing‑masing ke disk: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Mengapa ini penting:** +Menyimpan sumber daya memungkinkan pemrosesan lanjutan seperti optimasi gambar, minifikasi CSS, atau pengarsipan. Ini juga memberikan verifikasi nyata bahwa logika **create custom resource handler** berfungsi sebagaimana mestinya. + +## Langkah 5: Bersihkan + +Baik `HTMLDocument` maupun aliran apa pun harus dibuang untuk membebaskan sumber daya yang tidak dikelola. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Contoh lengkap yang dapat dijalankan + +Berikut adalah program mandiri yang mendemonstrasikan semua langkah mulai dari definisi kelas hingga ekstraksi sumber daya. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Output yang diharapkan** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Konsol akan menampilkan setiap sumber daya yang dialirkan viewer melalui handler khusus Anda, mengonfirmasi bahwa alur kerja **create custom resource handler** berhasil. + +## Pertanyaan umum dan kasus tepi + +| Pertanyaan | Jawaban | +|------------|---------| +| *Bagaimana jika sebuah sumber daya berukuran besar (misalnya gambar resolusi tinggi)?* | Ganti `MemoryStream` dengan `FileStream` yang mengarah ke folder sementara. Ini mencegah konsumsi memori yang berlebihan. | +| *Bisakah saya memfilter sumber daya berdasarkan tipe?* | Di dalam `HandleResource`, periksa `info.MimeType` atau `info.Extension` dan kembalikan `null` untuk tipe yang tidak diinginkan. Mengembalikan `null` memberi tahu viewer untuk melewatkan sumber daya tersebut. | +| *Apakah diperlukan keamanan thread?* | Jika instance handler yang sama digunakan pada beberapa pemuatan bersamaan, lindungi kamus `Resources` dengan lock atau gunakan koleksi bersamaan. | +| *Bagaimana cara mendukung URL relatif?* | `ResourceInfo` berisi URL asli; Anda dapat menggabungkannya dengan jalur dasar file HTML untuk menyelesaikan referensi relatif sebelum menyimpan. | + +## Kesimpulan + +Anda kini tahu cara **create custom resource handler** di C# untuk pemuatan HTML, mengonfigurasi `HTMLLoadOptions`, menangkap aset yang dialirkan, dan membersihkan secara bertanggung jawab. Pola ini memberi Anda kontrol penuh atas manajemen sumber daya, memungkinkan skenario seperti pemrosesan gambar secara langsung, penulisan ulang CSS, atau penyimpanan aman. + +Selanjutnya, jelajahi topik terkait seperti **HTMLDocument loading** dengan opsi rendering yang berbeda, atau perpanjang handler menjadi implementasi **C# resource handler** yang menulis langsung ke penyimpanan cloud. Bereksperimenlah dengan metode `HandleResource` handler untuk menyesuaikannya dengan alur kerja sumber daya spesifik proyek Anda. + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait dan membangun di atas teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/italian/net/advanced-features/_index.md b/html/italian/net/advanced-features/_index.md index 083f791b3e..ac51e29ba7 100644 --- a/html/italian/net/advanced-features/_index.md +++ b/html/italian/net/advanced-features/_index.md @@ -44,7 +44,8 @@ Scopri come convertire HTML in PDF, XPS e immagini con Aspose.HTML per .NET. Ese Scopri come usare Aspose.HTML per .NET per generare dinamicamente documenti HTML da dati JSON. Sfrutta la potenza della manipolazione HTML nelle tue applicazioni .NET. ### [Crea stream di memoria in C# – Guida alla creazione di stream personalizzati](./create-memory-stream-c-custom-stream-creation-guide/) Scopri come creare uno stream di memoria personalizzato in C# usando Aspose.HTML per .NET. Esempi passo passo e consigli pratici. - +### [Crea font grassetto corsivo in C# – guida passo‑a‑passo](./create-bold-italic-font-in-c-step-by-step-guide/) +Impara a creare font grassetto e corsivo in C# con Aspose.HTML, passo dopo passo, con esempi pratici. ## Conclusione diff --git a/html/italian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/italian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..c94edd4ed2 --- /dev/null +++ b/html/italian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-08-15 +description: Crea rapidamente un font grassetto e corsivo in C#. Scopri come creare + un font in C# con stili grassetto e corsivo usando la classe Font integrata. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: it +lastmod: 2026-08-15 +og_description: Crea un font grassetto e corsivo in C# con un esempio chiaro. Questo + tutorial mostra come creare un font in C# usando i flag FontStyle e spiega le insidie + più comuni. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Crea un font grassetto e corsivo in C# – guida completa di programmazione +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Crea un font grassetto e corsivo in C# – guida passo passo +url: /it/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea un font grassetto corsivo in C# – guida passo‑passo + +Se hai bisogno di **creare un font grassetto corsivo** in C#, questa guida ti mostra esattamente come farlo. Vedrai un esempio completo e eseguibile che dimostra anche come **creare un font in C#** usando la classe standard .NET `Font`. + +Lavorare con font personalizzati è una parte routine della creazione di app desktop Windows, della generazione di PDF o del rendering di HTML sul server. Alla fine di questo tutorial sarai in grado di istanziare un font sia grassetto che corsivo, capire perché viene usato l'operatore bitwise `|` e gestire casi limite comuni come famiglie di font mancanti. + +Non sono richieste librerie esterne—tutto utilizza la libreria di classi di base .NET Framework / .NET Core. + +## Cosa imparerai + +* Come importare gli spazi dei nomi necessari per la gestione dei font. +* La sintassi per combinare `FontStyle.Bold` e `FontStyle.Italic`. +* Come verificare che il font sia stato creato correttamente. +* Suggerimenti per la gestione dei fallback quando la famiglia richiesta non è installata. + +Non sono richieste librerie esterne—tutto utilizza la libreria di classi di base .NET Framework / .NET Core. + +## Prerequisiti + +* .NET 6.0 SDK o successivo (il codice funziona anche su .NET Framework 4.6+). +* Un editor di codice o IDE (Visual Studio, VS Code, Rider, ecc.). +* Familiarità di base con la sintassi C#. + +Se soddisfi questi prerequisiti, puoi seguire i passaggi senza alcuna configurazione aggiuntiva. + +## Passo 1: Aggiungi le direttive using necessarie + +La classe `Font` si trova nello spazio dei nomi `System.Drawing`, che fa parte del pacchetto NuGet `System.Drawing.Common` per .NET Core/.NET 5+. Aggiungi lo spazio dei nomi all'inizio del tuo file: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Perché questo passaggio è importante** – Senza la riga `using System.Drawing;` il compilatore non può individuare `Font` o `FontStyle`, generando un errore “type or namespace name could not be found”. + +## Passo 2: Combina gli stili grassetto e corsivo con l'operatore OR bitwise + +In .NET, `FontStyle` è un enum contrassegnato con l'attributo `[Flags]`. Questo significa che puoi combinare più valori usando l'operatore `|` (OR bitwise): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Spiegazione + +* `"Arial"` – il nome della famiglia di font. Se il sistema non ha Arial installato, il costruttore ricade sul font predefinito. +* `12` – dimensione in punti. +* `FontStyle.Bold | FontStyle.Italic` – combina le due bandiere di stile. L'operatore `|` unisce la rappresentazione binaria di ciascuna bandiera, producendo un unico valore che rappresenta “grassetto + corsivo”. + +> **Consiglio pro:** Usa sempre i nomi dell'enum (`FontStyle.Bold`) invece di numeri magici; questo migliora la leggibilità e previene bug quando i valori dell'enum cambiano. + +## Passo 3: Verifica il font creato (opzionale ma consigliato) + +Stampare le proprietà del font ti aiuta a confermare che la combinazione di stili sia riuscita, specialmente durante il debug su una nuova macchina. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Output previsto** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Se l'output elenca sia `Bold` che `Italic`, il font è stato creato correttamente. + +## Passo 4: Renderizza una stringa di esempio (conferma visiva) + +Quando esegui un'app console non puoi vedere lo stile effettivo dei glifi, ma puoi generare un'immagine per dimostrare il risultato. Il frammento seguente disegna “Hello, World!” usando il font grassetto‑corsivo e lo salva come *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Dopo che il programma è terminato, apri *sample.png* per vedere il testo renderizzato con lo stile grassetto corsivo. + +![Testo di esempio renderizzato con font grassetto corsivo](sample.png) + +*Testo alternativo dell'immagine: Screenshot del testo renderizzato con un font Arial grassetto corsivo in una finestra console C#* – questo testo alternativo soddisfa il requisito SEO per il testo alternativo delle immagini. + +## Passo 5: Fallback elegante quando la famiglia di font non è disponibile + +Se la famiglia richiesta (ad es., “Arial”) non è installata, il costruttore `Font` lancia un `ArgumentException`. Avvolgi la creazione in un blocco `try/catch` e ricorri a un font sicuro noto, come “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Perché gestirlo?** In ambienti containerizzati o headless il set predefinito di font può differire da un tipico desktop. Fornire un fallback previene crash a runtime e garantisce uno stile coerente. + +## Esempio completo, eseguibile + +Mettendo tutto insieme, ecco un programma completo che puoi copiare, incollare ed eseguire: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Come eseguire + +1. Salva il codice in un file chiamato `Program.cs`. +2. Apri un terminale nella directory del file. +3. Esegui `dotnet new console -n FontDemo` (se ti serve uno scheletro di progetto). +4. Sostituisci il `Program.cs` generato con il codice sopra. +5. Esegui `dotnet add package System.Drawing.Common` (necessario per .NET Core/5+). +6. Compila ed esegui con `dotnet run`. + +Vedrai l'output della console che conferma le proprietà del font, e `sample.png` apparirà nella cartella del progetto. + +## Problemi comuni e come evitarli + +| Problema | Perché succede | Soluzione | +|----------|----------------|-----------| +| **Manca il pacchetto `System.Drawing.Common`** | .NET Core non include `System.Drawing` per impostazione predefinita. | Esegui `dotnet add package System.Drawing.Common`. | +| **Famiglia di font non installata** | Le immagini Docker headless spesso non hanno i font Windows. | Usa un font di fallback o installa i font richiesti nel container. | +| **Uso errato di `|`** | Usare `+` invece di `|` produce una combinazione non valida. | Combina sempre i valori di `FontStyle` con l'operatore OR bitwise (`|`). | +| **Non rilasciare l'oggetto `Font`** | Non chiamare `Dispose` può provocare perdite di risorse GDI. | Avvolgi `Font` in un blocco `using` o chiama `font.Dispose()` dopo aver finito. | + +## Conclusione + +Ora sai come **creare un font grassetto corsivo** in C# e come **creare un font in C#** in modo sicuro ed efficiente. Il tutorial ha coperto l'importazione dello spazio dei nomi corretto, la combinazione delle bandiere `FontStyle`, la verifica del risultato, il rendering di un esempio visivo e la gestione delle famiglie di font mancanti. + +Successivamente, potresti esplorare: + +* **Creare font sottolineati o barrati** – aggiungi `FontStyle.Underline` o `FontStyle.Strikeout`. +* **Usare font TrueType personalizzati** – carica un file `.ttf` con `PrivateFontCollection`. +* **Applicare i font in WinForms, WPF o nella generazione di PDF** – lo stesso oggetto `Font` può essere passato a controlli UI o a librerie di terze parti. + +Sentiti libero di sperimentare con diverse famiglie, dimensioni e combinazioni di stile. Se incontri problemi, rivedi la tabella “Problemi comuni” o consulta la documentazione ufficiale [.NET per System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Buon coding! + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come combinare i font programmaticamente in C# – Guida passo‑passo](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Crea documento HTML con testo formattato ed esporta in PDF – Guida completa](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [converti docx in png – crea archivio zip tutorial C#](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/italian/net/working-with-html-documents/_index.md b/html/italian/net/working-with-html-documents/_index.md index 0d466ec954..e9d7f6e1e3 100644 --- a/html/italian/net/working-with-html-documents/_index.md +++ b/html/italian/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ Ora, portiamo le tue competenze al livello successivo. La modifica di documenti ### [Come salvare HTML in C# – Guida completa con un gestore di risorse personalizzato](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [Come rendere grassetto un'intestazione con CSS e C# – Guida completa passo‑passo](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Creare un gestore di risorse personalizzato in C# per il caricamento di HTML](./create-custom-resource-handler-in-c-for-html-loading/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/italian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/italian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..0e9329bed5 --- /dev/null +++ b/html/italian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-08-15 +description: Crea un gestore di risorse personalizzato in C# per gestire le risorse + HTML come immagini e CSS. Impara HTMLLoadOptions, stream di memoria e caricamento + di HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: it +lastmod: 2026-08-15 +og_description: Crea un gestore di risorse personalizzato in C# per controllare come + le risorse HTML vengono trasmesse. Questo tutorial mostra la configurazione di HTMLLoadOptions, + la gestione dello stream di memoria e il caricamento di HTMLDocument con logica + personalizzata. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Crea gestore di risorse personalizzato in C# – guida completa per la gestione + delle risorse HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Crea gestore di risorse personalizzato in C# per il caricamento HTML +url: /it/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea gestore di risorse personalizzato in C# per il caricamento HTML + +Se hai bisogno di **create custom resource handler** per file HTML, questa guida ti mostra esattamente come fare. Imparerai a intercettare immagini, CSS e altre risorse durante il caricamento di un documento HTML, usando `HTMLLoadOptions` e uno stream basato su memoria. + +Il tutorial copre tutto il necessario per implementare un gestore riutilizzabile, configurare le opzioni di caricamento e verificare che le risorse siano catturate correttamente. Non è necessaria alcuna documentazione esterna—basta il codice qui sotto e le spiegazioni. + +## Prerequisiti + +- .NET 6.0 o versioni successive +- Familiarità di base con C# +- Un riferimento alla libreria di elaborazione HTML che fornisce `HTMLDocument`, `HtmlLoadOptions` e `ResourceHandler` (ad esempio, GroupDocs.Viewer per .NET) + +## Panoramica della soluzione + +Procederemo: + +1. **Create a custom resource handler** creando una sottoclasse di `ResourceHandler`. +2. Configurare `HTMLLoadOptions` per utilizzare il gestore. +3. Caricare un file HTML con `HTMLDocument` mentre il gestore fornisce uno stream per ogni risorsa. +4. (Opzionale) Salvare le risorse ricevute su disco per la verifica. + +Ogni passaggio include il codice sorgente completo e la motivazione dietro di esso. + +## Passo 1: Definisci la classe del gestore di risorse personalizzato + +Creare un gestore personalizzato significa sovrascrivere `HandleResource` in modo che la libreria possa scrivere i byte della risorsa su uno stream controllato da te. L'uso di un `MemoryStream` mantiene i dati in memoria, ideale per test o ulteriori elaborazioni. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Perché è importante:** +Sovrascrivere `HandleResource` ti dà il controllo completo su dove vanno i dati della risorsa. Se in seguito dovessi memorizzare nella cache le immagini, trasformare il CSS o registrare l'uso delle risorse, puoi sostituire il `MemoryStream` con qualsiasi implementazione di stream personalizzata. + +## Passo 2: Configura `HTMLLoadOptions` per utilizzare il gestore + +`HTMLLoadOptions` ti consente di inserire il gestore nella pipeline di caricamento. Impostare la proprietà `ResourceHandler` indica al visualizzatore di invocare `MyHandler` per ogni risorsa esterna. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Perché è importante:** +Senza assegnare `ResourceHandler`, il visualizzatore scriverebbe le risorse nella sua posizione predefinita (spesso una cartella temporanea). Specificando il tuo gestore, crei un comportamento di **create custom resource handler** che si allinea alla strategia di archiviazione della tua applicazione. + +## Passo 3: Carica il documento HTML con le opzioni configurate + +Ora carica il file HTML. Il visualizzatore chiamerà `MyHandler.HandleResource` per ogni risorsa che incontra. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +A questo punto il contenuto HTML è stato analizzato e tutte le risorse esterne sono state inviate nei buffer di memoria forniti da `MyHandler`. + +## Passo 4 (opzionale): Accedi alle risorse catturate + +Se hai bisogno di ispezionare o conservare le risorse, puoi modificare `MyHandler` per memorizzare ogni `MemoryStream` in un dizionario indicizzato dal nome della risorsa. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Dopo il caricamento, puoi iterare su `handler.Resources` e scrivere ciascuna su disco: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Perché è importante:** +Memorizzare le risorse consente post‑processing come l'ottimizzazione delle immagini, la minificazione del CSS o l'archiviazione. Fornisce anche una verifica tangibile che la logica di **create custom resource handler** funzioni come previsto. + +## Passo 5: Pulizia + +Sia `HTMLDocument` che eventuali stream devono essere eliminati per liberare risorse non gestite. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Esempio completo eseguibile + +Di seguito è riportato un programma autonomo che dimostra tutti i passaggi, dalla definizione della classe all'estrazione delle risorse. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Output previsto** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +La console elenca ogni risorsa che il visualizzatore ha inviato attraverso il tuo gestore personalizzato, confermando che il flusso di lavoro **create custom resource handler** è riuscito. + +## Domande comuni e casi limite + +| Domanda | Risposta | +|----------|--------| +| *Che succede se una risorsa è grande (ad esempio, immagine ad alta risoluzione)?* | Sostituire `MemoryStream` con un `FileStream` che punta a una cartella temporanea. Questo evita un consumo eccessivo di memoria. | +| *Posso filtrare le risorse per tipo?* | All'interno di `HandleResource`, ispeziona `info.MimeType` o `info.Extension` e restituisci `null` per i tipi indesiderati. Restituire `null` indica al visualizzatore di saltare la risorsa. | +| *È necessaria la sicurezza dei thread?* | Se la stessa istanza del gestore viene utilizzata in più caricamenti concorrenti, proteggi il dizionario `Resources` con un lock o usa una collezione concorrente. | +| *Come gestire URL relativi?* | `ResourceInfo` contiene l'URL originale; puoi combinarlo con il percorso base del file HTML per risolvere i riferimenti relativi prima di memorizzarli. | + +## Conclusione + +Ora sai come **create custom resource handler** in C# per il caricamento HTML, configurare `HTMLLoadOptions`, catturare le risorse trasmesse e pulire in modo responsabile. Questo modello ti offre il controllo completo sulla gestione delle risorse, consentendo scenari come l'elaborazione di immagini al volo, la riscrittura del CSS o l'archiviazione sicura. + +Successivamente, esplora argomenti correlati come il **HTMLDocument loading** con diverse opzioni di rendering, o estendi il gestore a implementazioni di **C# resource handler** che scrivono direttamente su storage cloud. Sperimenta con il metodo `HandleResource` del gestore per adattarlo al flusso di lavoro delle risorse specifico del tuo progetto. + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Crea HTML da stringa in C# – Guida al gestore di risorse personalizzato](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Gestore di risorse personalizzato in C# – Tutorial per convertire HTML in ZIP](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [Come salvare HTML in C# – Guida completa usando un gestore di risorse personalizzato](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/japanese/net/advanced-features/_index.md b/html/japanese/net/advanced-features/_index.md index 124414d1ba..4ce3b32cae 100644 --- a/html/japanese/net/advanced-features/_index.md +++ b/html/japanese/net/advanced-features/_index.md @@ -44,7 +44,7 @@ Aspose.HTML for .NET を使用して HTML を PDF、XPS、画像に変換する Aspose.HTML for .NET を使用して JSON データから HTML ドキュメントを動的に生成する方法を学びます。.NET アプリケーションで HTML 操作のパワーを活用します。 ### [C# のメモリ ストリーム作成 – カスタム ストリーム作成ガイド](./create-memory-stream-c-custom-stream-creation-guide/) C# でカスタム メモリ ストリームを作成し、Aspose.HTML での HTML 操作に活用する方法をステップバイステップで学びます。 - +### [C# で太字斜体フォントを作成する – ステップバイステップ ガイド](./create-bold-italic-font-in-c-step-by-step-guide/) ## 結論 diff --git a/html/japanese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/japanese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..68077b7621 --- /dev/null +++ b/html/japanese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-08-15 +description: C#で太字イタリック体のフォントをすばやく作成する。組み込みの Font クラスを使用して、太字とイタリックのスタイルでフォントを作成する方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: ja +lastmod: 2026-08-15 +og_description: C#で太字イタリック体フォントを作成する方法を、明確な例とともに紹介します。このチュートリアルでは、FontStyle フラグを使用して + C# でフォントを作成する手順と、よくある落とし穴を解説します。 +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: C#で太字イタリック体フォントを作成する – 完全コーディングガイド +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: C#で太字イタリックフォントを作成する – ステップバイステップガイド +url: /ja/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で太字斜体フォントを作成する – ステップバイステップガイド + +C# で **太字斜体フォントを作成** したい場合、このガイドではその手順を正確に示します。標準の .NET `Font` クラスを使用して **C# でフォントを作成** する方法も、実行可能な完全なサンプルで確認できます。 + +カスタムフォントの取り扱いは、Windows デスクトップアプリの構築、PDF の生成、サーバー側での HTML レンダリングなどで日常的に行われます。このチュートリアルを終える頃には、太字かつ斜体のフォントをインスタンス化でき、ビット単位の `|` 演算子が使用される理由を理解し、フォントファミリーが見つからないときの一般的な対策も把握できるようになります。 + +## 学べること + +* フォント処理に必要な名前空間のインポート方法。 +* `FontStyle.Bold` と `FontStyle.Italic` を組み合わせる構文。 +* フォントが正常に作成されたかを確認する方法。 +* 要求したフォントファミリーがインストールされていない場合のフォールバック処理のコツ。 + +外部ライブラリは不要です。すべて .NET Framework / .NET Core の基本クラスライブラリだけで完結します。 + +## 前提条件 + +* .NET 6.0 SDK 以降(コードは .NET Framework 4.6+ でも動作します)。 +* コードエディタまたは IDE(Visual Studio、VS Code、Rider など)。 +* C# の基本構文に慣れていること。 + +上記の前提条件を満たしていれば、追加のセットアップなしで手順を進められます。 + +## 手順 1: 必要な using ディレクティブを追加 + +`Font` クラスは `System.Drawing` 名前空間にあり、.NET Core/.NET 5+ では `System.Drawing.Common` NuGet パッケージの一部です。ファイルの先頭に次の名前空間を追加してください。 + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **この手順が重要な理由** – `using System.Drawing;` 行が無いと、コンパイラは `Font` や `FontStyle` を見つけられず、 “type or namespace name could not be found” エラーが発生します。 + +## 手順 2: ビット単位 OR 演算子で太字と斜体スタイルを組み合わせる + +.NET では `FontStyle` は `[Flags]` 属性が付与された enum です。そのため、`|`(ビット単位 OR)演算子で複数の値を組み合わせられます。 + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### 解説 + +* `"Arial"` – フォントファミリー名。システムに Arial がインストールされていない場合、コンストラクタはデフォルトフォントにフォールバックします。 +* `12` – ポイントサイズ。 +* `FontStyle.Bold | FontStyle.Italic` – 2 つのスタイルフラグを組み合わせます。`|` 演算子は各フラグのビット表現をマージし、 “bold + italic” を表す単一の値を生成します。 + +> **プロのコツ:** マジックナンバーではなく enum 名(`FontStyle.Bold`)を常に使用してください。可読性が向上し、enum の値が変更されたときのバグを防げます。 + +## 手順 3: 作成したフォントを検証する(任意だが推奨) + +フォントのプロパティを出力すれば、スタイルの組み合わせが正しく行われたかを確認できます。特に新しいマシンでデバッグする際に有用です。 + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**期待される出力** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +出力に `Bold` と `Italic` の両方が含まれていれば、フォントは正しく作成されています。 + +## 手順 4: サンプル文字列を描画する(視覚的確認) + +コンソールアプリだけでは実際の字形スタイルは見えませんが、画像を生成すれば結果を確認できます。以下のスニペットは “Hello, World!” を太字斜体フォントで描画し、*sample.png* として保存します。 + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +プログラム実行後、*sample.png* を開くと太字斜体スタイルでテキストが描画されていることが確認できます。 + +![太字斜体フォントでレンダリングされたサンプルテキスト](sample.png) + +*Image alt text: C# コンソールウィンドウで太字斜体の Arial フォントで描画されたテキストのスクリーンショット* – この alt テキストは画像の SEO 要件を満たします。 + +## 手順 5: フォントファミリーが利用できない場合の優雅なフォールバック + +要求したファミリー(例: “Arial”)がインストールされていないと、`Font` コンストラクタは `ArgumentException` をスローします。`try/catch` ブロックで作成を囲み、 “Segoe UI” など安全なフォントにフォールバックしましょう。 + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**なぜ対処が必要か** – コンテナ化やヘッドレス環境ではデフォルトのフォントセットが一般的なデスクトップと異なることがあります。フォールバックを用意しておくことで実行時クラッシュを防ぎ、スタイルの一貫性を保てます。 + +## 完全な実行可能サンプル + +すべてをまとめたプログラムは以下です。コピーして貼り付け、実行してください。 + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### 実行方法 + +1. コードを `Program.cs` という名前のファイルに保存。 +2. ファイルがあるディレクトリでターミナルを開く。 +3. `dotnet new console -n FontDemo` を実行(プロジェクトの雛形が必要な場合)。 +4. 生成された `Program.cs` を上記コードに置き換える。 +5. `dotnet add package System.Drawing.Common` を実行(.NET Core/5+ 必須)。 +6. `dotnet run` でビルド・実行。 + +コンソールにフォントプロパティが表示され、プロジェクトフォルダーに `sample.png` が生成されます。 + +## よくある落とし穴と回避策 + +| 落とし穴 | 発生原因 | 対策 | +|---------|----------|------| +| **`System.Drawing.Common` パッケージが欠如** | .NET Core にはデフォルトで `System.Drawing` が含まれない。 | `dotnet add package System.Drawing.Common` を実行。 | +| **フォントファミリーがインストールされていない** | ヘッドレス Docker イメージは Windows フォントを持たないことが多い。 | フォールバックフォントを使用するか、コンテナに必要なフォントをインストール。 | +| **`|` の代わりに `+` を使用** | 無効な組み合わせとなりエラーになる。 | 常にビット単位 OR 演算子(`|`)で `FontStyle` を結合。 | +| **`Font` オブジェクトを破棄しない** | GDI リソースがリークする可能性がある。 | `using` ブロックで `Font` を囲むか、使用後に `font.Dispose()` を呼び出す。 | + +## 結論 + +これで **C# で太字斜体フォントを作成** する方法と、 **C# でフォントを作成** する際の安全かつ効率的な手順が身につきました。正しい名前空間のインポート、`FontStyle` フラグの組み合わせ、結果の検証、視覚的サンプルの生成、フォントファミリーが欠如したときのフォールバックまで網羅しました。 + +次に試すと良いテーマ: + +* **下線や取り消し線付きフォントの作成** – `FontStyle.Underline` または `FontStyle.Strikeout` を追加。 +* **カスタム TrueType フォントの使用** – `.ttf` ファイルを `PrivateFontCollection` で読み込む。 +* **WinForms、WPF、PDF 生成でのフォント適用** – 同じ `Font` オブジェクトを UI コントロールやサードパーティライブラリに渡せます。 + +さまざまなファミリー、サイズ、スタイルの組み合わせで実験してみてください。問題が発生したら「よくある落とし穴」表を再確認するか、公式の [.NET documentation for System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font) を参照してください。ハッピーコーディング! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには完全なコード例とステップバイステップの解説が含まれており、追加の API 機能を習得したり、別の実装アプローチを自分のプロジェクトに取り入れたりするのに役立ちます。 + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/japanese/net/working-with-html-documents/_index.md b/html/japanese/net/working-with-html-documents/_index.md index b81b2fd9c9..3c012f54b4 100644 --- a/html/japanese/net/working-with-html-documents/_index.md +++ b/html/japanese/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ HTML ドキュメントは Web のバックボーンであり、それを効果 ### [カスタムリソースハンドラを使用した C# での HTML 保存完全ガイド](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [CSS と C# で見出しを太字にする方法 – 完全ステップバイステップガイド](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [C# で HTML 読み込み用カスタムリソースハンドラを作成する](./create-custom-resource-handler-in-c-for-html-loading/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/japanese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/japanese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..ef85373da8 --- /dev/null +++ b/html/japanese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,296 @@ +--- +category: general +date: 2026-08-15 +description: C#でカスタムリソースハンドラを作成し、画像やCSSなどのHTMLリソースを管理します。HTMLLoadOptions、メモリストリーム、HTMLDocumentのロード方法を学びます。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: ja +lastmod: 2026-08-15 +og_description: C#でカスタムリソースハンドラを作成し、HTMLリソースのストリーミング方法を制御します。このチュートリアルでは、HTMLLoadOptionsの設定、メモリストリームの処理、カスタムロジックによるHTMLDocumentのロード方法を示します。 +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: C#でカスタムリソースハンドラを作成 – HTMLリソース管理の完全ガイド +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: HTML読み込みのためのC#カスタムリソースハンドラを作成する +url: /ja/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で HTML 読み込み用カスタムリソースハンドラを作成する + +HTML ファイル用に **カスタムリソースハンドラを作成** する必要がある場合、このガイドで手順をすべて示します。`HTMLLoadOptions` とメモリベースのストリームを使用して、HTML ドキュメントの読み込み中に画像、CSS、その他のアセットをインターセプトする方法を学びます。 + +このチュートリアルでは、再利用可能なハンドラの実装、ロードオプションの設定、リソースが正しく取得されているかの検証に必要なすべてを網羅しています。外部ドキュメントは不要です—以下のコードと解説だけで完了します。 + +## 前提条件 + +- .NET 6.0 以降 +- C# の基本的な知識 +- `HTMLDocument`、`HtmlLoadOptions`、`ResourceHandler` を提供する HTML 処理ライブラリへの参照(例: GroupDocs.Viewer for .NET) + +## ソリューションの概要 + +以下を行います。 + +1. `ResourceHandler` を継承して **カスタムリソースハンドラを作成** する。 +2. ハンドラを使用するように `HTMLLoadOptions` を設定する。 +3. `HTMLDocument` で HTML ファイルを読み込み、ハンドラが各リソースに対してストリームを提供するようにする。 +4. (オプション)取得したリソースをディスクに保存して検証する。 + +各ステップには完全なソースコードとその背後にある考え方を示します。 + +## 手順 1: カスタムリソースハンドラ クラスを定義する + +カスタムハンドラを作成するには `HandleResource` をオーバーライドし、ライブラリがリソースバイトを書き込むストリームを自分で制御できるようにします。`MemoryStream` を使用すればデータはメモリ内に保持され、テストや追加処理に最適です。 + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**重要ポイント:** +`HandleResource` をオーバーライドすることで、リソースデータの保存先を完全にコントロールできます。後で画像をキャッシュしたり、CSS を変換したり、リソース使用状況をログに記録したりしたい場合は、`MemoryStream` を任意のカスタムストリーム実装に置き換えるだけです。 + +## 手順 2: ハンドラを使用するように `HTMLLoadOptions` を設定する + +`HTMLLoadOptions` ではハンドラをロード パイプラインに差し込むことができます。`ResourceHandler` プロパティにハンドラを設定すると、ビューアは外部アセットごとに `MyHandler` を呼び出します。 + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**重要ポイント:** +`ResourceHandler` を設定しない場合、ビューアはデフォルトの場所(多くの場合一時フォルダ)にリソースを書き込みます。独自のハンドラを指定することで、**カスタムリソースハンドラ** の動作をアプリケーションの保存戦略に合わせて実装できます。 + +## 手順 3: 設定したオプションで HTML ドキュメントを読み込む + +ここで HTML ファイルを読み込みます。ビューアは検出した各リソースに対して `MyHandler.HandleResource` を呼び出します。 + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +この時点で HTML コンテンツは解析され、外部リソースはすべて `MyHandler` が提供したメモリ バッファにストリームされました。 + +## 手順 4(オプション): 取得したリソースにアクセスする + +リソースを確認または永続化したい場合は、`MyHandler` を変更して各 `MemoryStream` をリソース名をキーとしたディクショナリに格納します。 + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +読み込み後、`handler.Resources` を走査して各ストリームをディスクに書き出すことができます。 + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**重要ポイント:** +リソースを保存すると、画像最適化や CSS 圧縮、アーカイブなどの後処理が可能になります。また、**カスタムリソースハンドラを作成** するロジックが期待通りに動作していることを目に見えて確認できます。 + +## 手順 5: クリーンアップ + +`HTMLDocument` とすべてのストリームは、アンマネージド リソースを解放するために必ず破棄してください。 + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## 完全な実行可能サンプル + +以下はクラス定義からリソース抽出までのすべての手順を示す、自己完結型プログラムです。 + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**期待される出力** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +コンソールには、ビューアがカスタムハンドラを通してストリームした各リソースが一覧表示され、**カスタムリソースハンドラの作成** ワークフローが正常に完了したことが確認できます。 + +## よくある質問とエッジケース + +| 質問 | 回答 | +|----------|--------| +| *リソースが大きい(例: 高解像度画像)場合はどうすべきですか?* | `MemoryStream` の代わりに一時フォルダを指す `FileStream` を使用します。これによりメモリ使用量を抑えられます。 | +| *リソースを種類でフィルタリングできますか?* | `HandleResource` 内で `info.MimeType` または `info.Extension` を確認し、不要なタイプに対して `null` を返します。`null` を返すとビューアはそのリソースをスキップします。 | +| *スレッドセーフは必要ですか?* | 同一ハンドラ インスタンスを複数の同時ロードで使う場合は、`Resources` ディクショナリをロックで保護するか、`ConcurrentDictionary` などのスレッドセーフコレクションを使用してください。 | +| *相対 URL をサポートするには?* | `ResourceInfo` に元の URL が含まれるので、HTML ファイルのベースパスと組み合わせて相対参照を解決し、保存前に調整できます。 | + +## 結論 + +これで **C# で HTML 読み込み用カスタムリソースハンドラを作成** し、`HTMLLoadOptions` を設定してストリーミングされたアセットを取得し、適切にクリーンアップする方法が分かりました。このパターンを使えば、オンザフライの画像処理、CSS の書き換え、セキュアな保存など、リソース管理をフルコントロールできます。 + +次は、**HTMLDocument の読み込み** をさまざまなレンダリングオプションで試したり、ハンドラを拡張して **C# リソースハンドラ** がクラウドストレージに直接書き込む実装に挑戦したりしてください。`HandleResource` メソッドをプロジェクト固有のリソースフローに合わせてカスタマイズしてみましょう。 + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには完全な動作サンプルとステップバイステップの解説が含まれており、API の追加機能習得や代替実装アプローチの探求に役立ちます。 + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/korean/net/advanced-features/_index.md b/html/korean/net/advanced-features/_index.md index 39059e92e6..717f97b543 100644 --- a/html/korean/net/advanced-features/_index.md +++ b/html/korean/net/advanced-features/_index.md @@ -32,7 +32,7 @@ Aspose.HTML을 사용하여 .NET에서 HTML 문서를 다루는 방법을 알아 .NET용 Aspose.HTML을 사용하여 HTML 문서를 효율적으로 조작하는 방법을 알아보세요. 개발자를 위한 단계별 튜토리얼. ### [Aspose.HTML을 사용한 .NET의 메모리 스트림 공급자](./memory-stream-provider/) Aspose.HTML로 .NET에서 멋진 HTML 문서를 만드는 방법을 알아보세요. 단계별 튜토리얼을 따라 HTML 조작의 힘을 풀어보세요. -### [Aspose.HTML을 사용한 .NET에서의 웹 스크래핑](./web-scraping/) +### [Aspose.HTML을 사용한 .NET에서 웹 스크래핑](./web-scraping/) Aspose.HTML을 사용하여 .NET에서 HTML 문서를 조작하는 방법을 배우세요. 향상된 웹 개발을 위해 요소를 효과적으로 탐색, 필터링, 쿼리 및 선택합니다. ### [Aspose.HTML을 사용하여 .NET에서 확장된 콘텐츠 속성 사용](./use-extended-content-property/) Aspose.HTML for .NET을 사용하여 동적 웹 콘텐츠를 만드는 방법을 알아보세요. 튜토리얼에서는 초보자를 위한 필수 조건, 단계별 지침 및 FAQ를 다룹니다. @@ -44,7 +44,8 @@ Aspose.HTML for .NET을 사용하여 HTML을 PDF, XPS 및 이미지로 변환하 .NET용 Aspose.HTML을 사용하여 JSON 데이터에서 HTML 문서를 동적으로 생성하는 방법을 알아보세요. .NET 애플리케이션에서 HTML 조작의 힘을 활용하세요. ### [c# 메모리 스트림 만들기 – 맞춤 스트림 생성 가이드](./create-memory-stream-c-custom-stream-creation-guide/) Aspose.HTML을 사용하여 .NET에서 메모리 스트림을 직접 생성하고 활용하는 방법을 단계별로 안내합니다. - +### [C#에서 굵은 이탤릭 글꼴 만들기 – 단계별 가이드](./create-bold-italic-font-in-c-step-by-step-guide/) +C#을 사용해 굵은 이탤릭체 글꼴을 생성하는 방법을 단계별로 안내합니다. ## 결론 diff --git a/html/korean/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/korean/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..854bd8898b --- /dev/null +++ b/html/korean/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-08-15 +description: C#에서 굵은 기울임꼴 폰트를 빠르게 만들기. 내장 Font 클래스를 사용하여 굵게와 기울임꼴 스타일이 적용된 폰트를 C#에서 + 만드는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: ko +lastmod: 2026-08-15 +og_description: C#에서 굵은 이탤릭 글꼴을 명확한 예제로 만들기. 이 튜토리얼은 FontStyle 플래그를 사용하여 C#에서 글꼴을 + 만드는 방법을 보여주고 일반적인 함정을 설명합니다. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: C#에서 굵은 이탤릭 폰트 만들기 – 완전 코딩 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: C#에서 굵은 이탤릭체 폰트 만들기 – 단계별 가이드 +url: /ko/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 굵은 이탤릭체 폰트 만들기 – 단계별 가이드 + +C#에서 **굵은 이탤릭체 폰트**를 만들어야 한다면, 이 가이드는 정확한 방법을 보여줍니다. 표준 .NET `Font` 클래스를 사용하여 **C#에서 폰트 만들기**를 시연하는 완전한 실행 예제도 확인할 수 있습니다. + +커스텀 폰트를 다루는 것은 Windows 데스크톱 앱 개발, PDF 생성, 서버에서 HTML 렌더링 등에서 일상적인 작업입니다. 이 튜토리얼을 마치면 굵고 이탤릭인 폰트를 인스턴스화하는 방법, 비트 연산자 `|`를 사용하는 이유, 폰트 패밀리가 없을 때의 일반적인 예외 처리 방법을 이해하게 됩니다. + +## 배울 내용 + +* 폰트 처리를 위한 필수 네임스페이스 가져오기. +* `FontStyle.Bold`와 `FontStyle.Italic`을 결합하는 구문. +* 폰트가 정상적으로 생성됐는지 확인하는 방법. +* 요청한 패밀리가 설치되지 않았을 때의 폴백 처리 팁. + +외부 라이브러리는 필요 없습니다—모두 .NET Framework / .NET Core 기본 클래스 라이브러리를 사용합니다. + +## 사전 요구 사항 + +* .NET 6.0 SDK 이상 (코드는 .NET Framework 4.6+에서도 동작). +* 코드 편집기 또는 IDE (Visual Studio, VS Code, Rider 등). +* C# 문법에 대한 기본 지식. + +위 요구 사항을 충족한다면 추가 설정 없이 단계들을 따라 할 수 있습니다. + +## 1단계: 필요한 using 지시문 추가 + +`Font` 클래스는 `System.Drawing` 네임스페이스에 포함되어 있으며, .NET Core/.NET 5+에서는 `System.Drawing.Common` NuGet 패키지의 일부입니다. 파일 상단에 네임스페이스를 추가하세요: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **이 단계가 중요한 이유** – `using System.Drawing;` 라인이 없으면 컴파일러가 `Font`나 `FontStyle`을 찾지 못해 “type or namespace name could not be found” 오류가 발생합니다. + +## 2단계: 비트 연산자 OR(`|`)으로 굵은 및 이탤릭 스타일 결합 + +.NET에서 `FontStyle`은 `[Flags]` 특성이 지정된 열거형(enum)입니다. 따라서 `|` (비트 OR) 연산자를 사용해 여러 값을 결합할 수 있습니다: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### 설명 + +* `"Arial"` – 폰트 패밀리 이름. 시스템에 Arial이 없으면 생성자는 기본 폰트로 폴백합니다. +* `12` – 포인트 크기. +* `FontStyle.Bold | FontStyle.Italic` – 두 스타일 플래그를 결합합니다. `|` 연산자는 각 플래그의 이진 표현을 병합해 “굵게 + 이탤릭”을 나타내는 단일 값을 만듭니다. + +> **프로 팁:** 매직 넘버 대신 열거형 이름(`FontStyle.Bold`)을 사용하세요. 가독성이 높아지고 열거형 값이 변경될 때 버그를 방지할 수 있습니다. + +## 3단계: 생성된 폰트 확인 (선택 사항이지만 권장) + +폰트 속성을 출력하면 스타일 조합이 성공했는지 확인할 수 있습니다. 특히 새 머신에서 디버깅할 때 유용합니다. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**예상 출력** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +출력에 `Bold`와 `Italic`이 모두 표시되면 폰트가 올바르게 생성된 것입니다. + +## 4단계: 샘플 문자열 렌더링 (시각적 확인) + +콘솔 앱에서는 실제 글리프 스타일을 볼 수 없지만, 이미지를 생성해 결과를 증명할 수 있습니다. 아래 스니펫은 굵은‑이탤릭 폰트로 “Hello, World!”를 그려 *sample.png* 파일로 저장합니다: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +프로그램 실행 후 *sample.png*를 열어 굵은 이탤릭 스타일로 렌더링된 텍스트를 확인하세요. + +![굵은 이탤릭 폰트로 렌더링된 샘플 텍스트](sample.png) + +*이미지 대체 텍스트: C# 콘솔 창에서 굵은 이탤릭 Arial 폰트로 렌더링된 텍스트 스크린샷* – 이 대체 텍스트는 SEO 요구 사항을 충족합니다. + +## 5단계: 폰트 패밀리 사용 불가 시 우아한 폴백 처리 + +요청한 패밀리(예: “Arial”)가 설치되지 않으면 `Font` 생성자가 `ArgumentException`을 throw합니다. `try/catch` 블록으로 감싸고 “Segoe UI”와 같은 안전한 폰트로 폴백하세요. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**왜 처리해야 할까요?** 컨테이너화되거나 헤드리스 환경에서는 기본 폰트 세트가 일반 데스크톱과 다를 수 있습니다. 폴백을 제공하면 런타임 충돌을 방지하고 일관된 스타일링을 유지할 수 있습니다. + +## 전체 실행 가능한 예제 + +모든 내용을 합친 완전한 프로그램은 다음과 같습니다. 복사·붙여넣기 후 바로 실행할 수 있습니다: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### 실행 방법 + +1. 코드를 `Program.cs` 파일에 저장합니다. +2. 파일이 있는 디렉터리에서 터미널을 엽니다. +3. `dotnet new console -n FontDemo` 명령으로 프로젝트 스캐폴드를 생성합니다 (필요한 경우). +4. 생성된 `Program.cs`를 위 코드로 교체합니다. +5. `dotnet add package System.Drawing.Common`을 실행합니다 (.NET Core/5+에 필요). +6. `dotnet run`으로 빌드하고 실행합니다. + +콘솔에 폰트 속성이 출력되고, 프로젝트 폴더에 `sample.png`가 생성됩니다. + +## 흔히 겪는 문제와 해결 방법 + +| 문제점 | 발생 원인 | 해결 방법 | +|---------|----------------|-----| +| **`System.Drawing.Common` 패키지 누락** | .NET Core에는 기본적으로 `System.Drawing`이 포함되지 않음. | `dotnet add package System.Drawing.Common` 실행 | +| **폰트 패밀리 미설치** | 헤드리스 Docker 이미지에는 Windows 폰트가 없을 수 있음. | 폴백 폰트를 사용하거나 컨테이너에 필요한 폰트를 설치 | +| **`|` 대신 `+` 사용** | `+`를 사용하면 잘못된 조합이 됨. | 항상 비트 OR 연산자(`|`)로 `FontStyle` 값을 결합 | +| **`Font` 객체 해제 누락** | `Dispose`를 호출하지 않으면 GDI 리소스가 누수될 수 있음. | `using` 블록으로 `Font`를 감싸거나 사용 후 `font.Dispose()` 호출 | + +## 결론 + +이제 C#에서 **굵은 이탤릭체 폰트 만들기**와 **C#에서 폰트 만들기**를 안전하고 효율적으로 수행하는 방법을 알게 되었습니다. 올바른 네임스페이스 가져오기, `FontStyle` 플래그 결합, 결과 확인, 시각적 샘플 렌더링, 폰트 패밀리 누락 시 처리까지 다루었습니다. + +다음 단계로 살펴볼 내용: + +* **밑줄 또는 취소선 폰트 만들기** – `FontStyle.Underline` 또는 `FontStyle.Strikeout` 추가. +* **커스텀 TrueType 폰트 사용** – `PrivateFontCollection`으로 `.ttf` 파일 로드. +* **WinForms, WPF, PDF 생성에 폰트 적용** – 동일 `Font` 객체를 UI 컨트롤이나 서드파티 라이브러리에 전달 가능. + +다양한 패밀리, 크기, 스타일 조합을 실험해 보세요. 문제가 발생하면 “흔히 겪는 문제” 표를 다시 확인하거나 공식 [.NET 문서의 System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font)를 참고하세요. 즐거운 코딩 되세요! + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 배운 기술을 확장하는 관련 주제를 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공해 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하도록 돕습니다. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/korean/net/working-with-html-documents/_index.md b/html/korean/net/working-with-html-documents/_index.md index 491b68f5a8..fda917aaa3 100644 --- a/html/korean/net/working-with-html-documents/_index.md +++ b/html/korean/net/working-with-html-documents/_index.md @@ -41,6 +41,10 @@ HTML 문서는 웹의 중추이며, 효과적으로 만들고 조작할 수 있 사용자 정의 리소스 핸들러를 사용해 C#에서 HTML을 저장하는 방법을 단계별로 안내합니다. ### [CSS와 C#로 제목을 굵게 만드는 방법 – 완전 단계별 가이드](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [HTML 로딩을 위한 C# 사용자 정의 리소스 핸들러 만들기](./create-custom-resource-handler-in-c-for-html-loading/) + +HTML 로딩 시 사용자 정의 리소스 핸들러를 구현하는 방법을 단계별로 안내합니다. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/korean/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/korean/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..ab83fe4e89 --- /dev/null +++ b/html/korean/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-08-15 +description: C#에서 이미지 및 CSS와 같은 HTML 리소스를 관리하기 위한 사용자 정의 리소스 핸들러를 생성합니다. HTMLLoadOptions, + 메모리 스트림 및 HTMLDocument 로딩을 학습합니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: ko +lastmod: 2026-08-15 +og_description: C#에서 사용자 정의 리소스 핸들러를 만들어 HTML 리소스가 스트리밍되는 방식을 제어합니다. 이 튜토리얼에서는 HTMLLoadOptions + 설정, 메모리 스트림 처리 및 사용자 정의 로직으로 HTMLDocument를 로드하는 방법을 보여줍니다. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: C#에서 사용자 정의 리소스 핸들러 만들기 – HTML 리소스 관리 완전 가이드 +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: HTML 로딩을 위한 C# 사용자 정의 리소스 핸들러 만들기 +url: /ko/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML 로딩을 위한 맞춤 리소스 핸들러 만들기 + +HTML 파일에 대해 **맞춤 리소스 핸들러**를 만들어야 할 경우, 이 가이드는 정확한 방법을 보여줍니다. `HTMLLoadOptions`와 메모리 기반 스트림을 사용해 HTML 문서를 로드하면서 이미지, CSS 및 기타 자산을 가로채는 방법을 배울 수 있습니다. + +이 튜토리얼은 재사용 가능한 핸들러 구현, 로드 옵션 구성, 그리고 리소스가 올바르게 캡처되는지 확인하는 데 필요한 모든 내용을 다룹니다. 외부 문서는 필요 없으며, 아래 코드와 설명만 있으면 됩니다. + +## 사전 요구 사항 + +- .NET 6.0 이상 +- C# 기본 지식 +- `HTMLDocument`, `HtmlLoadOptions`, `ResourceHandler` 등을 제공하는 HTML 처리 라이브러리 참조(예: GroupDocs.Viewer for .NET) + +## 솔루션 개요 + +우리는 다음을 수행합니다: + +1. `ResourceHandler`를 상속하여 **맞춤 리소스 핸들러**를 생성합니다. +2. `HTMLLoadOptions`에 핸들러를 지정합니다. +3. `HTMLDocument`로 HTML 파일을 로드하면서 핸들러가 각 리소스에 대한 스트림을 제공합니다. +4. (선택) 캡처한 리소스를 디스크에 저장해 확인합니다. + +각 단계마다 전체 소스 코드와 그 이유를 설명합니다. + +## 1단계: 맞춤 리소스 핸들러 클래스 정의 + +맞춤 핸들러를 만들려면 `HandleResource`를 오버라이드하여 라이브러리가 리소스 바이트를 여러분이 제어하는 스트림에 쓸 수 있게 합니다. `MemoryStream`을 사용하면 데이터가 메모리에 유지되어 테스트나 추가 처리에 이상적입니다. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**왜 중요한가:** +`HandleResource`를 오버라이드하면 리소스 데이터가 어디로 가는지 완전히 제어할 수 있습니다. 나중에 이미지를 캐시하거나 CSS를 변환하거나 리소스 사용을 로그에 남겨야 할 경우, `MemoryStream`을 다른 커스텀 스트림 구현으로 교체하면 됩니다. + +## 2단계: `HTMLLoadOptions`에 핸들러 지정 + +`HTMLLoadOptions`를 사용하면 로드 파이프라인에 핸들러를 연결할 수 있습니다. `ResourceHandler` 속성을 설정하면 뷰어가 모든 외부 자산에 대해 `MyHandler`를 호출합니다. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**왜 중요한가:** +`ResourceHandler`를 지정하지 않으면 뷰어는 기본 위치(보통 임시 폴더)에 리소스를 기록합니다. 자체 핸들러를 지정함으로써 **맞춤 리소스 핸들러** 동작을 구현하고 애플리케이션의 저장 전략에 맞출 수 있습니다. + +## 3단계: 구성된 옵션으로 HTML 문서 로드 + +이제 HTML 파일을 로드합니다. 뷰어는 발견하는 각 리소스마다 `MyHandler.HandleResource`를 호출합니다. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +이 시점에서 HTML 내용이 파싱되고, 모든 외부 리소스가 `MyHandler`가 제공한 메모리 버퍼로 스트리밍됩니다. + +## 4단계 (선택): 캡처한 리소스 접근 + +리소스를 검사하거나 영구 저장해야 한다면 `MyHandler`를 수정해 각 `MemoryStream`을 리소스 이름을 키로 하는 사전에 저장할 수 있습니다. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +로드가 끝난 뒤, `handler.Resources`를 순회하면서 각각을 디스크에 기록할 수 있습니다: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**왜 중요한가:** +리소스를 저장하면 이미지 최적화, CSS 압축, 아카이빙 등 후처리를 수행할 수 있습니다. 또한 **맞춤 리소스 핸들러** 로직이 의도대로 동작함을 눈으로 확인할 수 있습니다. + +## 5단계: 정리 + +`HTMLDocument`와 모든 스트림은 사용이 끝난 뒤 반드시 `Dispose`하여 비관리 리소스를 해제해야 합니다. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## 전체 실행 가능한 예제 + +아래는 클래스 정의부터 리소스 추출까지 모든 단계를 포함한 독립 실행형 프로그램입니다. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**예상 출력** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +콘솔에 뷰어가 맞춤 핸들러를 통해 스트리밍한 각 리소스가 나열되며, **맞춤 리소스 핸들러** 워크플로가 성공했음을 확인할 수 있습니다. + +## 흔히 묻는 질문 및 예외 상황 + +| Question | Answer | +|----------|--------| +| *리소스가 큰 경우(예: 고해상도 이미지)는 어떻게 하나요?* | `MemoryStream` 대신 임시 폴더를 가리키는 `FileStream`을 사용하세요. 메모리 사용량을 크게 줄일 수 있습니다. | +| *리소스를 타입별로 필터링할 수 있나요?* | `HandleResource` 내부에서 `info.MimeType` 또는 `info.Extension`을 검사하고, 원하지 않는 타입에 대해서는 `null`을 반환하면 됩니다. `null`을 반환하면 뷰어가 해당 리소스를 건너뜁니다. | +| *스레드 안전성이 필요한가요?* | 동일한 핸들러 인스턴스를 여러 동시 로드에 사용한다면 `Resources` 사전을 `lock`으로 보호하거나 `ConcurrentDictionary`와 같은 동시 컬렉션을 사용하세요. | +| *상대 URL을 지원하려면?* | `ResourceInfo`에 원본 URL이 포함되어 있으므로, HTML 파일의 기본 경로와 결합해 상대 경로를 해석한 뒤 저장하면 됩니다. | + +## 결론 + +이제 C#에서 HTML 로딩을 위해 **맞춤 리소스 핸들러**를 만들고, `HTMLLoadOptions`를 구성하며, 스트리밍된 자산을 캡처하고, 적절히 정리하는 방법을 알게 되었습니다. 이 패턴을 활용하면 실시간 이미지 처리, CSS 재작성, 보안 저장 등 다양한 시나리오에 대한 완전한 리소스 관리가 가능합니다. + +다음 단계로는 **HTMLDocument 로딩**을 다양한 렌더링 옵션과 함께 살펴보거나, 핸들러를 확장해 **C# resource handler**가 클라우드 스토리지에 직접 쓰도록 구현해 보세요. `HandleResource` 메서드를 프로젝트에 맞게 조정해 보면서 여러분만의 리소스 워크플로를 완성해 보시기 바랍니다. + +## 다음에 배울 내용 + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하며, 단계별 코드 예제와 상세 설명을 제공합니다. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/polish/net/advanced-features/_index.md b/html/polish/net/advanced-features/_index.md index ea97083f1a..780e4ab0d3 100644 --- a/html/polish/net/advanced-features/_index.md +++ b/html/polish/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Dowiedz się, jak konwertować HTML na PDF, XPS i obrazy za pomocą Aspose.HTML Dowiedz się, jak używać Aspose.HTML dla .NET do dynamicznego generowania dokumentów HTML z danych JSON. Wykorzystaj moc manipulacji HTML w swoich aplikacjach .NET. ### [Jak łączyć czcionki programowo w C# – przewodnik krok po kroku](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Dowiedz się, jak programowo łączyć czcionki w C# przy użyciu Aspose.HTML, krok po kroku, z przykładami kodu. +### [Utwórz pogrubioną i kursywną czcionkę w C# – przewodnik krok po kroku](./create-bold-italic-font-in-c-step-by-step-guide/) +Dowiedz się, jak programowo tworzyć czcionki pogrubione i kursywne w C# przy użyciu Aspose.HTML. ## Wniosek diff --git a/html/polish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/polish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..b2fa93a036 --- /dev/null +++ b/html/polish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-08-15 +description: Szybko utwórz pogrubioną i pochyłą czcionkę w C#. Dowiedz się, jak stworzyć + czcionkę w C# z pogrubionym i pochyłym stylem, używając wbudowanej klasy Font. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: pl +lastmod: 2026-08-15 +og_description: Utwórz pogrubioną kursywę w C# z przejrzystym przykładem. Ten poradnik + pokazuje, jak stworzyć czcionkę w C# przy użyciu flag FontStyle i wyjaśnia typowe + pułapki. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Tworzenie pogrubionej i pochylonej czcionki w C# – kompletny przewodnik + programistyczny +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Tworzenie pogrubionej i kursywnej czcionki w C# – przewodnik krok po kroku +url: /pl/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utworzenie pogrubionej kursywnej czcionki w C# – przewodnik krok po kroku + +Jeśli potrzebujesz **utworzyć pogrubioną kursywną czcionkę** w C#, ten przewodnik pokaże Ci dokładnie, jak to zrobić. Zobaczysz kompletny, uruchamialny przykład, który dodatkowo demonstruje, jak **utworzyć czcionkę w C#** przy użyciu standardowej klasy .NET `Font`. + +Praca z własnymi czcionkami jest rutynową częścią tworzenia aplikacji desktopowych Windows, generowania PDF‑ów lub renderowania HTML na serwerze. Po zakończeniu tego samouczka będziesz w stanie zainicjować czcionkę, która jest jednocześnie pogrubiona i kursywa, zrozumiesz, dlaczego używany jest operator bitowy `|`, oraz poradzisz sobie z typowymi przypadkami brzegowymi, takimi jak brakujące rodziny czcionek. + +## Czego się nauczysz + +* Jak zaimportować wymagane przestrzenie nazw do obsługi czcionek. +* Składnię łączenia `FontStyle.Bold` i `FontStyle.Italic`. +* Jak zweryfikować, że czcionka została utworzona pomyślnie. +* Wskazówki dotyczące obsługi fallbacku, gdy żądana rodzina nie jest zainstalowana. + +Żadne zewnętrzne biblioteki nie są wymagane – wszystko korzysta z biblioteki klas bazowych .NET Framework / .NET Core. + +## Wymagania wstępne + +* .NET 6.0 SDK lub nowszy (kod działa również na .NET Framework 4.6+). +* Edytor kodu lub IDE (Visual Studio, VS Code, Rider, itp.). +* Podstawowa znajomość składni C#. + +Jeśli spełniasz te wymagania, możesz przejść do kolejnych kroków bez dodatkowej konfiguracji. + +## Krok 1: Dodaj niezbędne dyrektywy using + +Klasa `Font` znajduje się w przestrzeni nazw `System.Drawing`, która jest częścią pakietu NuGet `System.Drawing.Common` dla .NET Core/.NET 5+. Dodaj tę przestrzeń nazw na początku pliku: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Dlaczego ten krok jest ważny** – Bez linii `using System.Drawing;` kompilator nie może znaleźć `Font` ani `FontStyle`, co skutkuje błędem „type or namespace name could not be found”. + +## Krok 2: Połącz style pogrubiony i kursywa przy użyciu operatora bitowego OR + +W .NET, `FontStyle` jest wyliczeniem oznaczonym atrybutem `[Flags]`. Oznacza to, że możesz łączyć wiele wartości przy użyciu operatora `|` (bitowego OR): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Wyjaśnienie + +* `"Arial"` – nazwa rodziny czcionki. Jeśli system nie ma zainstalowanego Arial, konstruktor przechodzi do czcionki domyślnej. +* `12` – rozmiar w punktach. +* `FontStyle.Bold | FontStyle.Italic` – łączy dwa flagi stylu. Operator `|` łączy binarne reprezentacje obu flag, tworząc jedną wartość, która oznacza „pogrubiona + kursywa”. + +> **Pro tip:** Zawsze używaj nazw wyliczeń (`FontStyle.Bold`) zamiast magicznych liczb; poprawia to czytelność i zapobiega błędom, gdy wartości wyliczenia ulegną zmianie. + +## Krok 3: Zweryfikuj utworzoną czcionkę (opcjonalnie, ale zalecane) + +Wypisywanie właściwości czcionki pomaga potwierdzić, że połączenie stylów powiodło się, szczególnie przy debugowaniu na nowej maszynie. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Oczekiwany wynik** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Jeśli wynik zawiera zarówno `Bold`, jak i `Italic`, czcionka została utworzona poprawnie. + +## Krok 4: Renderuj przykładowy ciąg znaków (potwierdzenie wizualne) + +Gdy uruchomisz aplikację konsolową, nie zobaczysz rzeczywistego stylu glifów, ale możesz wygenerować obraz, aby udowodnić rezultat. Poniższy fragment rysuje „Hello, World!” przy użyciu pogrubionej‑kursywnej czcionki i zapisuje go jako *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Po zakończeniu programu otwórz *sample.png*, aby zobaczyć tekst wyrenderowany pogrubioną kursywą. + +![Sample text rendered with bold italic font](sample.png) + +*Image alt text: Zrzut ekranu tekstu wyrenderowanego pogrubioną kursywną czcionką Arial w oknie konsoli C#* – ten opis spełnia wymóg SEO dotyczący tekstu alternatywnego obrazu. + +## Krok 5: Elegancki fallback, gdy rodzina czcionki jest niedostępna + +Jeśli żądana rodzina (np. „Arial”) nie jest zainstalowana, konstruktor `Font` rzuca `ArgumentException`. Owiń tworzenie w blok `try/catch` i przejdź do znanej, bezpiecznej czcionki, takiej jak „Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Dlaczego warto to obsłużyć?** W środowiskach konteneryzowanych lub bez interfejsu graficznego domyślny zestaw czcionek może różnić się od typowego pulpitu. Zapewnienie fallbacku zapobiega awariom w czasie wykonywania i gwarantuje spójny styl. + +## Pełny, uruchamialny przykład + +Łącząc wszystkie elementy, oto kompletny program, który możesz skopiować, wkleić i uruchomić: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Jak uruchomić + +1. Zapisz kod w pliku o nazwie `Program.cs`. +2. Otwórz terminal w katalogu, w którym znajduje się plik. +3. Wykonaj `dotnet new console -n FontDemo` (jeśli potrzebujesz szkieletu projektu). +4. Zamień wygenerowany `Program.cs` kodem powyżej. +5. Uruchom `dotnet add package System.Drawing.Common` (wymagane dla .NET Core/5+). +6. Zbuduj i uruchom poleceniem `dotnet run`. + +Zobaczysz w konsoli wypisane właściwości czcionki, a plik `sample.png` pojawi się w folderze projektu. + +## Typowe pułapki i jak ich uniknąć + +| Pułapka | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| **Missing `System.Drawing.Common` package** | .NET Core nie zawiera `System.Drawing` domyślnie. | Uruchom `dotnet add package System.Drawing.Common`. | +| **Font family not installed** | Obrazy Docker bez interfejsu graficznego często nie mają czcionek Windows. | Użyj czcionki fallback lub zainstaluj wymagane czcionki w kontenerze. | +| **Incorrect use of `|`** | Użycie `+` zamiast `|` skutkuje nieprawidłowym połączeniem. | Zawsze łącz wartości `FontStyle` operatorem bitowym OR (`|`). | +| **Disposing the `Font` object** | Nie wywołanie `Dispose` może powodować wycieki zasobów GDI. | Owiń `Font` w blok `using` lub wywołaj `font.Dispose()` po zakończeniu użycia. | + +## Zakończenie + +Teraz wiesz, jak **utworzyć pogrubioną kursywną czcionkę** w C# oraz jak **utworzyć czcionkę w C#** w sposób bezpieczny i wydajny. Samouczek obejmował import właściwej przestrzeni nazw, łączenie flag `FontStyle`, weryfikację wyniku, renderowanie przykładu wizualnego oraz obsługę brakujących rodzin czcionek. + +Następnie możesz zgłębić: + +* **Tworzenie czcionek podkreślonych lub przekreślonych** – dodaj `FontStyle.Underline` lub `FontStyle.Strikeout`. +* **Używanie własnych czcionek TrueType** – załaduj plik `.ttf` przy pomocy `PrivateFontCollection`. +* **Stosowanie czcionek w WinForms, WPF lub generowaniu PDF** – ten sam obiekt `Font` może być przekazywany do kontrolek UI lub bibliotek firm trzecich. + +Śmiało eksperymentuj z różnymi rodzinami, rozmiarami i kombinacjami stylów. Jeśli napotkasz problemy, wróć do tabeli „Typowe pułapki” lub sprawdź oficjalną [dokumentację .NET dla System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Szczęśliwego kodowania! + +## Co powinieneś się nauczyć dalej? + +Poniższe samouczki 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 z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak łączyć czcionki programowo w C# – przewodnik krok po kroku](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Tworzenie dokumentu HTML ze stylowanym tekstem i eksport do PDF – pełny przewodnik](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [konwertowanie docx na png – tworzenie archiwum zip – samouczek C#](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/polish/net/working-with-html-documents/_index.md b/html/polish/net/working-with-html-documents/_index.md index ac233f79e1..3b6036c6d7 100644 --- a/html/polish/net/working-with-html-documents/_index.md +++ b/html/polish/net/working-with-html-documents/_index.md @@ -43,6 +43,8 @@ Poznaj metodę zapisu HTML w C# z własnym obsługiwaczem zasobów, umożliwiaj Dowiedz się, jak użyć CSS i C# do pogrubienia nagłówka w HTML, krok po kroku, z praktycznymi przykładami. +### [Utwórz własny obsługiwacz zasobów w C# do ładowania HTML](./create-custom-resource-handler-in-c-for-html-loading/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/polish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/polish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..833267b519 --- /dev/null +++ b/html/polish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-08-15 +description: Utwórz własny handler zasobów w C#, aby zarządzać zasobami HTML, takimi + jak obrazy i CSS. Poznaj HTMLLoadOptions, strumienie pamięci oraz ładowanie HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: pl +lastmod: 2026-08-15 +og_description: Utwórz własny obsługujący zasoby w C#, aby kontrolować sposób strumieniowania + zasobów HTML. Ten tutorial pokazuje konfigurację HTMLLoadOptions, obsługę strumienia + pamięci oraz ładowanie HTMLDocument z własną logiką. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Utwórz własny obsługiwacz zasobów w C# – pełny przewodnik po zarządzaniu + zasobami HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Utwórz własny handler zasobów w C# do ładowania HTML +url: /pl/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create custom resource handler in C# for HTML loading + +Jeśli potrzebujesz **create custom resource handler** dla plików HTML, ten przewodnik pokaże Ci dokładnie, jak to zrobić. Nauczysz się przechwytywać obrazy, CSS i inne zasoby podczas ładowania dokumentu HTML, używając `HTMLLoadOptions` oraz strumienia opartego na pamięci. + +Tutorial obejmuje wszystko, co potrzebne do wdrożenia wielokrotnego użytku handlera, skonfigurowania opcji ładowania i weryfikacji, że zasoby są prawidłowo przechwytywane. Nie potrzebna jest żadna zewnętrzna dokumentacja — wystarczy poniższy kod i wyjaśnienia. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy +- Podstawowa znajomość C# +- Odwołanie do biblioteki przetwarzania HTML, która udostępnia `HTMLDocument`, `HtmlLoadOptions` i `ResourceHandler` (np. GroupDocs.Viewer for .NET) + +## Przegląd rozwiązania + +We will: + +1. **Create a custom resource handler** poprzez dziedziczenie po `ResourceHandler`. +2. Skonfiguruj `HTMLLoadOptions`, aby używał handlera. +3. Załaduj plik HTML za pomocą `HTMLDocument`, podczas gdy handler dostarcza strumień dla każdego zasobu. +4. (Opcjonalnie) Zapisz otrzymane zasoby na dysku w celu weryfikacji. + +Każdy krok zawiera pełny kod źródłowy oraz wyjaśnienie. + +## Krok 1: Zdefiniuj klasę własnego handlera zasobów + +Utworzenie własnego handlera oznacza nadpisanie metody `HandleResource`, aby biblioteka mogła zapisywać bajty zasobu do strumienia, którym sterujesz. Użycie `MemoryStream` utrzymuje dane w pamięci, co jest idealne do testowania lub dalszego przetwarzania. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Dlaczego to ważne:** +Nadpisanie `HandleResource` daje pełną kontrolę nad tym, gdzie trafiają dane zasobu. Jeśli później będziesz musiał buforować obrazy, przekształcać CSS lub rejestrować użycie zasobów, możesz zamienić `MemoryStream` na dowolną własną implementację strumienia. + +## Krok 2: Skonfiguruj `HTMLLoadOptions`, aby używał handlera + +`HTMLLoadOptions` pozwala podłączyć handler do potoku ładowania. Ustawienie właściwości `ResourceHandler` informuje podgląd, aby wywoływał `MyHandler` dla każdego zewnętrznego zasobu. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Dlaczego to ważne:** +Bez przypisania `ResourceHandler` podgląd zapisywałby zasoby w domyślnej lokalizacji (często w folderze tymczasowym). Określając własny handler, **create custom resource handler** zachowanie, które jest zgodne ze strategią przechowywania w Twojej aplikacji. + +## Krok 3: Załaduj dokument HTML z skonfigurowanymi opcjami + +Teraz załaduj plik HTML. Podgląd wywoła `MyHandler.HandleResource` dla każdego napotkanego zasobu. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +W tym momencie zawartość HTML jest parsowana, a wszystkie zewnętrzne zasoby zostały przesłane do buforów pamięci dostarczonych przez `MyHandler`. + +## Krok 4 (opcjonalnie): Uzyskaj dostęp do przechwyconych zasobów + +Jeśli potrzebujesz przejrzeć lub zachować zasoby, możesz zmodyfikować `MyHandler`, aby przechowywał każdy `MemoryStream` w słowniku indeksowanym nazwą zasobu. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Po załadowaniu możesz iterować po `handler.Resources` i zapisywać każdy na dysk: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Dlaczego to ważne:** +Przechowywanie zasobów umożliwia przetwarzanie po‑załadowaniu, takie jak optymalizacja obrazów, minifikacja CSS czy archiwizacja. Daje to także namacalną weryfikację, że logika **create custom resource handler** działa zgodnie z zamierzeniami. + +## Krok 5: Sprzątanie + +Zarówno `HTMLDocument`, jak i wszelkie strumienie powinny być zwalniane, aby zwolnić zasoby niezarządzane. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Pełny przykład do uruchomienia + +Poniżej znajduje się samodzielny program, który demonstruje wszystkie kroki od definicji klasy po wyodrębnianie zasobów. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Oczekiwany wynik** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Konsola wypisuje każdy zasób, który podgląd przesłał przez Twój własny handler, potwierdzając, że przepływ pracy **create custom resource handler** zakończył się sukcesem. + +## Częste pytania i przypadki brzegowe + +| Question | Answer | +|----------|--------| +| *Co zrobić, gdy zasób jest duży (np. obraz wysokiej rozdzielczości)?* | Zastąp `MemoryStream` `FileStream` wskazującym na folder tymczasowy. Zapobiega to nadmiernemu zużyciu pamięci. | +| *Czy mogę filtrować zasoby według typu?* | Wewnątrz `HandleResource` sprawdź `info.MimeType` lub `info.Extension` i zwróć `null` dla niechcianych typów. Zwrócenie `null` informuje podgląd, aby pominął zasób. | +| *Czy wymagana jest bezpieczeństwo wątkowe?* | Jeśli ta sama instancja handlera jest używana w wielu równoczesnych ładowaniach, zabezpiecz słownik `Resources` przy pomocy blokady lub użyj kolekcji współbieżnej. | +| *Jak obsługiwać względne adresy URL?* | `ResourceInfo` zawiera oryginalny URL; możesz połączyć go ze ścieżką bazową pliku HTML, aby rozwiązać względne odwołania przed zapisaniem. | + +## Zakończenie + +Teraz wiesz, jak **create custom resource handler** w C# dla ładowania HTML, skonfigurować `HTMLLoadOptions`, przechwycić przesyłane zasoby i odpowiednio je zwolnić. Ten wzorzec daje pełną kontrolę nad zarządzaniem zasobami, umożliwiając scenariusze takie jak przetwarzanie obrazów w locie, przepisywanie CSS czy bezpieczne przechowywanie. + +Następnie, zapoznaj się z powiązanymi tematami, takimi jak **HTMLDocument loading** z różnymi opcjami renderowania, lub rozszerz handler do implementacji **C# resource handler**, które zapisują bezpośrednio w chmurze. Eksperymentuj z metodą `HandleResource` handlera, aby dopasować ją do konkretnego przepływu zasobów w Twoim projekcie. + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletny działający kod z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Utwórz HTML z ciągu znaków w C# – Przewodnik po Custom Resource Handler](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler w C# – Tutorial konwersji HTML do ZIP](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [Jak zapisać HTML w C# – Kompletny przewodnik z użyciem Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/portuguese/net/advanced-features/_index.md b/html/portuguese/net/advanced-features/_index.md index 9cee0ea266..556bf4bfae 100644 --- a/html/portuguese/net/advanced-features/_index.md +++ b/html/portuguese/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Aprenda a converter HTML para PDF, XPS e imagens com Aspose.HTML para .NET. Tuto Aprenda a usar Aspose.HTML para .NET para gerar dinamicamente documentos HTML a partir de dados JSON. Aproveite o poder da manipulação HTML em seus aplicativos .NET. ### [Como combinar fontes programaticamente em C# – Guia passo a passo](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Aprenda a combinar várias fontes em um documento usando C# e Aspose.HTML, com exemplos detalhados e instruções passo a passo. +### [Criar fonte negrito itálico em C# – guia passo a passo](./create-bold-italic-font-in-c-step-by-step-guide/) +Aprenda a criar fontes em negrito e itálico programaticamente em C# usando Aspose.HTML, com exemplos passo a passo. ## Conclusão diff --git a/html/portuguese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/portuguese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..39a97c9171 --- /dev/null +++ b/html/portuguese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-08-15 +description: Crie fonte em negrito e itálico em C# rapidamente. Aprenda como criar + fonte em C# com estilos negrito e itálico usando a classe Font incorporada. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: pt +lastmod: 2026-08-15 +og_description: Crie fonte negrito itálico em C# com um exemplo claro. Este tutorial + mostra como criar fontes em C# usando os flags FontStyle e explica armadilhas comuns. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Criar fonte em negrito e itálico em C# – guia completo de codificação +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Crie fonte em negrito e itálico no C# – guia passo a passo +url: /pt/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar fonte negrito itálico em C# – guia passo a passo + +Se você precisa **criar fonte negrito itálico** em C#, este guia mostra exatamente como fazer isso. Você verá um exemplo completo e executável que também demonstra como **criar fonte em C#** usando a classe padrão .NET `Font`. + +Trabalhar com fontes personalizadas é uma parte rotineira da construção de aplicativos desktop Windows, geração de PDFs ou renderização de HTML no servidor. Ao final deste tutorial você será capaz de instanciar uma fonte que seja tanto negrito quanto itálico, entender por que o operador bitwise `|` é usado e lidar com casos comuns, como famílias de fontes ausentes. + +## O que você aprenderá + +* Como importar os namespaces necessários para manipulação de fontes. +* A sintaxe para combinar `FontStyle.Bold` e `FontStyle.Italic`. +* Como verificar se a fonte foi criada com sucesso. +* Dicas para tratamento de fallback quando a família solicitada não está instalada. + +Nenhuma biblioteca externa é necessária — tudo usa a biblioteca de classes base do .NET Framework / .NET Core. + +## Pré-requisitos + +* .NET 6.0 SDK ou posterior (o código também funciona no .NET Framework 4.6+). +* Um editor de código ou IDE (Visual Studio, VS Code, Rider, etc.). +* Familiaridade básica com a sintaxe C#. + +Se você atende a esses pré-requisitos, pode seguir os passos sem nenhuma configuração adicional. + +## Etapa 1: Adicionar as diretivas using necessárias + +A classe `Font` está no namespace `System.Drawing`, que faz parte do pacote NuGet `System.Drawing.Common` para .NET Core/.NET 5+. Adicione o namespace no topo do seu arquivo: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Por que esta etapa importa** – Sem a linha `using System.Drawing;` o compilador não consegue localizar `Font` ou `FontStyle`, resultando em um erro “type or namespace name could not be found”. + +## Etapa 2: Combinar estilos negrito e itálico com o operador OR bit a bit + +No .NET, `FontStyle` é um enum marcado com o atributo `[Flags]`. Isso significa que você pode combinar múltiplos valores usando o operador `|` (OR bit a bit): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Explicação + +* `"Arial"` – o nome da família de fonte. Se o sistema não tiver Arial instalado, o construtor recorre à fonte padrão. +* `12` – tamanho em pontos. +* `FontStyle.Bold | FontStyle.Italic` – combina as duas bandeiras de estilo. O operador `|` mescla a representação binária de cada bandeira, produzindo um único valor que representa “negrito + itálico”. + +> **Dica profissional:** Sempre use os nomes do enum (`FontStyle.Bold`) ao invés de números mágicos; isso melhora a legibilidade e previne bugs quando os valores do enum mudam. + +## Etapa 3: Verificar a fonte criada (opcional, mas recomendado) + +Imprimir as propriedades da fonte ajuda a confirmar que a combinação de estilos foi bem-sucedida, especialmente ao depurar em uma máquina nova. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Saída esperada** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Se a saída listar tanto `Bold` quanto `Italic`, a fonte foi criada corretamente. + +## Etapa 4: Renderizar uma string de exemplo (confirmação visual) + +Ao executar um aplicativo de console você não vê a estilização real dos glifos, mas pode gerar uma imagem para provar o resultado. O trecho a seguir desenha “Hello, World!” usando a fonte negrito‑itálico e salva como *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Após o programa ser executado, abra *sample.png* para ver o texto renderizado com o estilo negrito itálico. + +![Texto de exemplo renderizado com fonte negrito itálico](sample.png) + +*Texto alternativo da imagem: Captura de tela do texto renderizado com uma fonte Arial negrito itálico em uma janela de console C#* – este texto alternativo satisfaz o requisito de SEO para texto alternativo de imagem. + +## Etapa 5: Fallback elegante quando a família de fonte não está disponível + +Se a família solicitada (por exemplo, “Arial”) não estiver instalada, o construtor `Font` lança uma `ArgumentException`. Envolva a criação em um bloco `try/catch` e recorra a uma fonte segura conhecida, como “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Por que tratar isso?** Em ambientes containerizados ou sem interface gráfica o conjunto padrão de fontes pode diferir de um desktop típico. Fornecer um fallback evita falhas em tempo de execução e garante consistência de estilo. + +## Exemplo completo, executável + +Juntando tudo, aqui está um programa completo que você pode copiar, colar e executar: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Como executar + +1. Salve o código em um arquivo chamado `Program.cs`. +2. Abra um terminal no diretório do arquivo. +3. Execute `dotnet new console -n FontDemo` (se precisar de uma estrutura de projeto). +4. Substitua o `Program.cs` gerado pelo código acima. +5. Execute `dotnet add package System.Drawing.Common` (necessário para .NET Core/5+). +6. Compile e execute com `dotnet run`. + +Você verá a saída no console confirmando as propriedades da fonte, e `sample.png` aparecerá na pasta do projeto. + +## Armadilhas comuns e como evitá‑las + +| Armadilha | Por que acontece | Correção | +|-----------|------------------|----------| +| **Falta o pacote `System.Drawing.Common`** | .NET Core não inclui `System.Drawing` por padrão. | Execute `dotnet add package System.Drawing.Common`. | +| **Família de fonte não instalada** | Imagens Docker sem interface gráfica frequentemente não possuem fontes Windows. | Use uma fonte de fallback ou instale as fontes necessárias no contêiner. | +| **Uso incorreto de `|`** | Usar `+` ao invés de `|` resulta em uma combinação inválida. | Sempre combine valores de `FontStyle` com o operador OR bit a bit (`|`). | +| **Descartar o objeto `Font`** | Não chamar `Dispose` pode vazar recursos GDI. | Envolva `Font` em um bloco `using` ou chame `font.Dispose()` após terminar. | + +## Conclusão + +Agora você sabe como **criar fonte negrito itálico** em C# e como **criar fonte em C#** de forma segura e eficiente. O tutorial abordou a importação do namespace correto, combinação de bandeiras `FontStyle`, verificação do resultado, renderização de um exemplo visual e tratamento de famílias de fontes ausentes. + +Em seguida, você pode explorar: + +* **Criar fontes sublinhadas ou tachadas** – adicione `FontStyle.Underline` ou `FontStyle.Strikeout`. +* **Usar fontes TrueType personalizadas** – carregue um arquivo `.ttf` com `PrivateFontCollection`. +* **Aplicar fontes em WinForms, WPF ou geração de PDF** – o mesmo objeto `Font` pode ser passado para controles de UI ou bibliotecas de terceiros. + +Fique à vontade para experimentar diferentes famílias, tamanhos e combinações de estilo. Se encontrar problemas, revise a tabela “Armadilhas comuns” ou consulte a documentação oficial do [.NET para System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Feliz codificação! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que se baseiam nas 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 de implementação em seus próprios projetos. + +- [Como combinar fontes programaticamente em C# – Guia passo a passo](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Criar documento HTML com texto formatado e exportar para PDF – Guia completo](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [converter docx para png – criar arquivo zip tutorial c#](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/portuguese/net/working-with-html-documents/_index.md b/html/portuguese/net/working-with-html-documents/_index.md index a8b4154dc2..785f563861 100644 --- a/html/portuguese/net/working-with-html-documents/_index.md +++ b/html/portuguese/net/working-with-html-documents/_index.md @@ -37,8 +37,11 @@ Depois que você tiver compreendido o básico, vamos nos aprofundar no processo Agora, vamos levar suas habilidades para o próximo nível. Editar documentos HTML é uma tarefa comum para desenvolvedores web, e o Aspose.HTML simplifica esse processo significativamente. Nesta seção, abordaremos a criação, manipulação e estilo de documentos. Você descobrirá como aprimorar a aparência e a funcionalidade do seu conteúdo web, tornando-o envolvente e amigável ao usuário. ### [Como salvar HTML em C# – Guia completo usando um manipulador de recursos personalizado](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + ### [Como deixar o título em negrito com CSS e C# – Guia completo passo a passo](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Criar manipulador de recursos personalizado em C# para carregamento de HTML](./create-custom-resource-handler-in-c-for-html-loading/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/portuguese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/portuguese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..731780b884 --- /dev/null +++ b/html/portuguese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-08-15 +description: Crie um manipulador de recursos personalizado em C# para gerenciar recursos + HTML, como imagens e CSS. Aprenda HTMLLoadOptions, fluxos de memória e o carregamento + de HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: pt +lastmod: 2026-08-15 +og_description: Criar manipulador de recursos personalizado em C# para controlar como + os recursos HTML são transmitidos. Este tutorial mostra a configuração de HTMLLoadOptions, + o tratamento de streams de memória e o carregamento de HTMLDocument com lógica personalizada. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Crie um manipulador de recursos personalizado em C# – guia completo para + gerenciamento de recursos HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Criar manipulador de recurso personalizado em C# para carregamento de HTML +url: /pt/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar manipulador de recurso personalizado em C# para carregamento de HTML + +Se você precisa **criar manipulador de recurso personalizado** para arquivos HTML, este guia mostra exatamente como fazer. Você aprenderá a interceptar imagens, CSS e outros recursos ao carregar um documento HTML, usando `HTMLLoadOptions` e um stream baseado em memória. + +O tutorial cobre tudo o que é necessário para implementar um manipulador reutilizável, configurar opções de carregamento e verificar se os recursos são capturados corretamente. Nenhuma documentação externa é necessária — apenas o código abaixo e as explicações. + +## Pré-requisitos + +- .NET 6.0 ou posterior +- Familiaridade básica com C# +- Uma referência à biblioteca de processamento HTML que fornece `HTMLDocument`, `HtmlLoadOptions` e `ResourceHandler` (por exemplo, GroupDocs.Viewer for .NET) + +## Visão geral da solução + +Vamos: + +1. **Criar um manipulador de recurso personalizado** ao estender `ResourceHandler`. +2. Configurar `HTMLLoadOptions` para usar o manipulador. +3. Carregar um arquivo HTML com `HTMLDocument` enquanto o manipulador fornece um stream para cada recurso. +4. (Opcional) Armazenar os recursos recebidos em disco para verificação. + +Cada passo inclui o código-fonte completo e o raciocínio por trás dele. + +## Passo 1: Definir a classe do manipulador de recurso personalizado + +Criar um manipulador personalizado significa sobrescrever `HandleResource` para que a biblioteca possa gravar os bytes do recurso em um stream que você controla. Usar um `MemoryStream` mantém os dados na memória, o que é ideal para testes ou processamento adicional. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Por que isso importa:** +Sobrescrever `HandleResource` lhe dá controle total sobre onde os dados do recurso são enviados. Se mais tarde precisar armazenar imagens em cache, transformar CSS ou registrar o uso de recursos, você pode substituir o `MemoryStream` por qualquer implementação de stream personalizada. + +## Passo 2: Configurar `HTMLLoadOptions` para usar o manipulador + +`HTMLLoadOptions` permite conectar o manipulador ao pipeline de carregamento. Definir a propriedade `ResourceHandler` indica ao visualizador para invocar `MyHandler` para cada recurso externo. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Por que isso importa:** +Sem atribuir `ResourceHandler`, o visualizador gravaria os recursos em seu local padrão (geralmente uma pasta temporária). Ao especificar seu próprio manipulador, você **cria manipulador de recurso personalizado** que se alinha à estratégia de armazenamento da sua aplicação. + +## Passo 3: Carregar o documento HTML com as opções configuradas + +Agora carregue o arquivo HTML. O visualizador chamará `MyHandler.HandleResource` para cada recurso que encontrar. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Neste ponto o conteúdo HTML é analisado, e todos os recursos externos foram transmitidos para os buffers de memória fornecidos por `MyHandler`. + +## Passo 4 (opcional): Acessar os recursos capturados + +Se precisar inspecionar ou persistir os recursos, você pode modificar `MyHandler` para armazenar cada `MemoryStream` em um dicionário indexado pelo nome do recurso. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Após o carregamento, você pode iterar sobre `handler.Resources` e gravar cada um em disco: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Por que isso importa:** +Armazenar recursos permite pós‑processamento como otimização de imagens, minificação de CSS ou arquivamento. Também fornece uma verificação tangível de que a lógica de **criar manipulador de recurso personalizado** funciona como esperado. + +## Passo 5: Limpar + +Tanto `HTMLDocument` quanto quaisquer streams devem ser descartados para liberar recursos não gerenciados. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Exemplo completo executável + +Abaixo está um programa autônomo que demonstra todos os passos, desde a definição da classe até a extração de recursos. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Saída esperada** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +O console lista cada recurso que o visualizador transmitiu através do seu manipulador personalizado, confirmando que o fluxo de trabalho de **criar manipulador de recurso personalizado** foi bem‑sucedido. + +## Perguntas comuns e casos de borda + +| Pergunta | Resposta | +|----------|----------| +| *E se um recurso for grande (por exemplo, imagem de alta resolução)?* | Substitua `MemoryStream` por um `FileStream` apontando para uma pasta temporária. Isso evita consumo excessivo de memória. | +| *Posso filtrar recursos por tipo?* | Dentro de `HandleResource`, inspecione `info.MimeType` ou `info.Extension` e retorne `null` para tipos indesejados. Retornar `null` indica ao visualizador que ele deve ignorar o recurso. | +| *É necessária segurança de thread?* | Se a mesma instância do manipulador for usada em múltiplos carregamentos concorrentes, proteja o dicionário `Resources` com um lock ou use uma coleção concorrente. | +| *Como posso suportar URLs relativas?* | `ResourceInfo` contém a URL original; você pode combiná‑la com o caminho base do arquivo HTML para resolver referências relativas antes de armazenar. | + +## Conclusão + +Agora você sabe como **criar manipulador de recurso personalizado** em C# para carregamento de HTML, configurar `HTMLLoadOptions`, capturar ativos transmitidos e limpar de forma responsável. Esse padrão lhe dá controle total sobre o gerenciamento de recursos, permitindo cenários como processamento de imagens em tempo real, reescrita de CSS ou armazenamento seguro. + +Em seguida, explore tópicos relacionados como **carregamento de HTMLDocument** com diferentes opções de renderização, ou estenda o manipulador para implementações de **manipulador de recurso C#** que escrevem diretamente em armazenamento na nuvem. Experimente o método `HandleResource` do manipulador para adequá‑lo ao fluxo de recursos específico do seu projeto. + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas 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 de implementação alternativas em seus próprios projetos. + +- [Criar HTML a partir de String em C# – Guia de Manipulador de Recurso Personalizado](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Manipulador de Recurso Personalizado em C# – Tutorial de Conversão de HTML para ZIP](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [Como Salvar HTML em C# – Guia Completo Usando um Manipulador de Recurso Personalizado](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/russian/net/advanced-features/_index.md b/html/russian/net/advanced-features/_index.md index 2018c098d4..db37da46fe 100644 --- a/html/russian/net/advanced-features/_index.md +++ b/html/russian/net/advanced-features/_index.md @@ -45,7 +45,8 @@ Aspose.HTML для .NET — это мощный инструмент, позво ### [Создание потока памяти в C# – Руководство по пользовательскому созданию потока](./create-memory-stream-c-custom-stream-creation-guide/) Узнайте, как создать пользовательский поток памяти в C# с помощью Aspose.HTML, пошаговое руководство. - +### [Создание полужирного курсивного шрифта в C# – пошаговое руководство](./create-bold-italic-font-in-c-step-by-step-guide/) +Узнайте, как создать полужирный курсивный шрифт в C# с пошаговыми инструкциями. ## Заключение diff --git a/html/russian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/russian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..8fd61cdfd3 --- /dev/null +++ b/html/russian/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-08-15 +description: Быстро создайте полужирный курсивный шрифт в C#. Узнайте, как создать + шрифт в C# с полужирным и курсивным стилями, используя встроенный класс Font. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: ru +lastmod: 2026-08-15 +og_description: Создайте полужирный курсивный шрифт в C# с понятным примером. Этот + учебник показывает, как создать шрифт в C# с использованием флагов FontStyle и объясняет + распространённые подводные камни. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Создание жирного курсивного шрифта в C# – полное руководство по кодированию +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Создание полужирного курсивного шрифта в C# – пошаговое руководство +url: /ru/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание полужирного курсивного шрифта в C# – пошаговое руководство + +Если вам нужно **создать полужирный курсивный шрифт** в C#, это руководство покажет, как это сделать. Вы увидите полностью рабочий пример, который также демонстрирует, как **создавать шрифт в C#** с помощью стандартного класса .NET `Font`. + +Работа с пользовательскими шрифтами – обычная часть разработки Windows‑приложений, генерации PDF или рендеринга HTML на сервере. К концу этого урока вы сможете создать шрифт, который одновременно полужирный и курсивный, поймёте, почему используется побитовое `|`, и научитесь обрабатывать типичные ситуации, такие как отсутствие запрашиваемого семейства шрифтов. + +## Что вы узнаете + +* Как импортировать необходимые пространства имён для работы со шрифтами. +* Синтаксис объединения `FontStyle.Bold` и `FontStyle.Italic`. +* Как проверить, что шрифт был создан успешно. +* Советы по обработке резервных вариантов, когда требуемое семейство не установлено. + +Никакие внешние библиотеки не требуются — всё использует базовую библиотеку классов .NET Framework / .NET Core. + +## Предварительные требования + +* .NET 6.0 SDK или новее (код также работает на .NET Framework 4.6+). +* Редактор кода или IDE (Visual Studio, VS Code, Rider и т.д.). +* Базовое знакомство с синтаксисом C#. + +Если у вас есть эти требования, вы можете следовать инструкциям без дополнительной настройки. + +## Шаг 1: Добавьте необходимые директивы using + +Класс `Font` находится в пространстве имён `System.Drawing`, которое является частью пакета NuGet `System.Drawing.Common` для .NET Core/.NET 5+. Добавьте пространство имён в начале файла: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Почему это важно** – без строки `using System.Drawing;` компилятор не сможет найти `Font` или `FontStyle`, что приведёт к ошибке «type or namespace name could not be found». + +## Шаг 2: Объедините полужирный и курсивный стили с помощью побитового оператора OR + +В .NET `FontStyle` — это перечисление, помеченное атрибутом `[Flags]`. Это значит, что вы можете комбинировать несколько значений, используя оператор `|` (побитовое ИЛИ): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Пояснение + +* `"Arial"` – название семейства шрифта. Если в системе нет Arial, конструктор переключится на шрифт по умолчанию. +* `12` – размер в пунктах. +* `FontStyle.Bold | FontStyle.Italic` – объединяет два флага стиля. Оператор `|` объединяет бинарные представления каждого флага, получая единое значение, которое обозначает «полужирный + курсивный». + +> **Pro tip:** Всегда используйте имена перечислений (`FontStyle.Bold`), а не «магические» числа; это повышает читаемость и предотвращает ошибки при изменении значений перечисления. + +## Шаг 3: Проверьте созданный шрифт (необязательно, но рекомендуется) + +Вывод свойств шрифта помогает убедиться, что комбинация стилей прошла успешно, особенно при отладке на новой машине. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Ожидаемый вывод** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Если в выводе присутствуют оба `Bold` и `Italic`, шрифт создан корректно. + +## Шаг 4: Отрисуйте пример строки (визуальное подтверждение) + +В консольном приложении вы не увидите реального оформления глифов, но можете сгенерировать изображение, чтобы доказать результат. Ниже приведён фрагмент, который рисует «Hello, World!» полужирным курсивным шрифтом и сохраняет его как *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +После выполнения программы откройте *sample.png*, чтобы увидеть текст, отрисованный полужирным курсивным стилем. + +![Текст, отрисованный полужирным курсивным шрифтом](sample.png) + +*Текст alt: Скриншот текста, отрисованного полужирным курсивным шрифтом Arial в консольном окне C#* – этот alt‑текст удовлетворяет требованиям SEO для альтернативных описаний изображений. + +## Шаг 5: Корректный резервный вариант, когда семейство шрифта недоступно + +Если запрашиваемое семейство (например, «Arial») не установлено, конструктор `Font` бросает `ArgumentException`. Оберните создание в блок `try/catch` и переключитесь на известный безопасный шрифт, например «Segoe UI». + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Зачем это нужно?** В контейнеризованных или безголовых средах набор шрифтов может отличаться от типичного настольного компьютера. Предоставление резервного варианта предотвращает падения во время выполнения и обеспечивает единообразное оформление. + +## Полный, готовый к запуску пример + +Объединив всё вместе, получаем полную программу, которую можно скопировать, вставить и запустить: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Как запустить + +1. Сохраните код в файл с именем `Program.cs`. +2. Откройте терминал в каталоге с файлом. +3. Выполните `dotnet new console -n FontDemo` (если нужен шаблон проекта). +4. Замените сгенерированный `Program.cs` на код выше. +5. Выполните `dotnet add package System.Drawing.Common` (требуется для .NET Core/5+). +6. Скомпилируйте и запустите командой `dotnet run`. + +Вы увидите вывод в консоли, подтверждающий свойства шрифта, а `sample.png` появится в папке проекта. + +## Распространённые подводные камни и как их избежать + +| Проблема | Почему происходит | Как исправить | +|----------|-------------------|---------------| +| **Отсутствует пакет `System.Drawing.Common`** | .NET Core не включает `System.Drawing` по умолчанию. | Выполните `dotnet add package System.Drawing.Common`. | +| **Семейство шрифта не установлено** | В безголовых Docker‑образах часто нет Windows‑шрифтов. | Используйте резервный шрифт или установите необходимые шрифты в контейнере. | +| **Неправильное использование `|`** | Использование `+` вместо `|` приводит к неверной комбинации. | Всегда комбинируйте значения `FontStyle` побитовым оператором OR (`|`). | +| **Не освобождаете объект `Font`** | Отсутствие вызова `Dispose` может привести к утечке GDI‑ресурсов. | Оберните `Font` в `using`‑блок или вызовите `font.Dispose()` после использования. | + +## Заключение + +Теперь вы знаете, как **создавать полужирный курсивный шрифт** в C# и как **создавать шрифт в C#** безопасно и эффективно. В руководстве рассмотрены импорт нужного пространства имён, объединение флагов `FontStyle`, проверка результата, визуальная отрисовка примера и обработка отсутствия семейства шрифтов. + +Далее вы можете изучить: + +* **Создание подчёркнутых или зачёркнутых шрифтов** – добавьте `FontStyle.Underline` или `FontStyle.Strikeout`. +* **Использование пользовательских TrueType‑шрифтов** – загрузите файл `.ttf` через `PrivateFontCollection`. +* **Применение шрифтов в WinForms, WPF или генерации PDF** – тот же объект `Font` можно передать UI‑контролам или сторонним библиотекам. + +Экспериментируйте с разными семействами, размерами и комбинациями стилей. Если возникнут проблемы, обратитесь к таблице «Распространённые подводные камни» или проверьте официальную [документацию .NET для System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Приятного кодинга! + +## Что изучать дальше? + +Следующие учебники охватывают смежные темы, которые опираются на техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/russian/net/working-with-html-documents/_index.md b/html/russian/net/working-with-html-documents/_index.md index 843e2ebedf..1812e04072 100644 --- a/html/russian/net/working-with-html-documents/_index.md +++ b/html/russian/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ HTML-документы являются основой Интернета, и ### [Как сохранить HTML в C# – Полное руководство с использованием пользовательского обработчика ресурсов](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [Как сделать заголовок жирным с помощью CSS и C# – Полное пошаговое руководство](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Создание пользовательского обработчика ресурсов в C# для загрузки HTML](./create-custom-resource-handler-in-c-for-html-loading/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/russian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/russian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..6c5d1fd9f7 --- /dev/null +++ b/html/russian/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-08-15 +description: Создайте пользовательский обработчик ресурсов на C# для управления HTML‑ресурсами, + такими как изображения и CSS. Изучите HTMLLoadOptions, потоки памяти и загрузку + HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: ru +lastmod: 2026-08-15 +og_description: Создайте пользовательский обработчик ресурсов на C# для контроля того, + как передаются HTML‑ресурсы. В этом руководстве показана настройка HTMLLoadOptions, + работа с потоками памяти и загрузка HTMLDocument с пользовательской логикой. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Создайте пользовательский обработчик ресурсов в C# – полное руководство + по управлению HTML‑ресурсами +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Создать пользовательский обработчик ресурсов на C# для загрузки HTML +url: /ru/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание пользовательского обработчика ресурсов в C# для загрузки HTML + +Если вам нужно **создать пользовательский обработчик ресурсов** для HTML‑файлов, это руководство покажет, как это сделать. Вы научитесь перехватывать изображения, CSS и другие активы при загрузке HTML‑документа, используя `HTMLLoadOptions` и поток, основанный на памяти. + +В руководстве рассматривается всё, что требуется для реализации переиспользуемого обработчика, настройки параметров загрузки и проверки корректного захвата ресурсов. Никакой внешней документации не требуется — только код ниже и пояснения. + +## Предварительные требования + +- .NET 6.0 или новее +- Базовые знания C# +- Ссылка на библиотеку обработки HTML, предоставляющую `HTMLDocument`, `HtmlLoadOptions` и `ResourceHandler` (например, GroupDocs.Viewer for .NET) + +## Обзор решения + +Мы будем: + +1. **Создавать пользовательский обработчик ресурсов**, наследуясь от `ResourceHandler`. +2. Настраивать `HTMLLoadOptions` для использования этого обработчика. +3. Загружать HTML‑файл с помощью `HTMLDocument`, при этом обработчик будет предоставлять поток для каждого ресурса. +4. (Опционально) Сохранять полученные ресурсы на диск для проверки. + +Каждый шаг включает полный исходный код и объяснение логики. + +## Шаг 1: Определите класс пользовательского обработчика ресурсов + +Создание собственного обработчика подразумевает переопределение `HandleResource`, чтобы библиотека могла записывать байты ресурса в поток, которым вы управляете. Использование `MemoryStream` сохраняет данные в памяти, что удобно для тестирования или дальнейшей обработки. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Почему это важно:** +Переопределяя `HandleResource`, вы получаете полный контроль над тем, куда направляются данные ресурса. Если позже понадобится кэшировать изображения, трансформировать CSS или вести журнал использования ресурсов, вы можете заменить `MemoryStream` любой другой реализацией потока. + +## Шаг 2: Настройте `HTMLLoadOptions` для использования обработчика + +`HTMLLoadOptions` позволяет подключить обработчик к конвейеру загрузки. Установка свойства `ResourceHandler` указывает просмотрщику вызывать `MyHandler` для каждого внешнего актива. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Почему это важно:** +Без назначения `ResourceHandler` просмотрщик записывал бы ресурсы в место по умолчанию (обычно во временную папку). Указав собственный обработчик, вы **создаёте пользовательский обработчик ресурсов**, который соответствует стратегии хранения вашего приложения. + +## Шаг 3: Загрузите HTML‑документ с настроенными параметрами + +Теперь загрузите HTML‑файл. Просмотрщик вызовет `MyHandler.HandleResource` для каждого найденного ресурса. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +На этом этапе HTML‑контент разобран, а все внешние ресурсы переданы в буферы памяти, предоставленные `MyHandler`. + +## Шаг 4 (опционально): Доступ к захваченным ресурсам + +Если необходимо проанализировать или сохранить ресурсы, вы можете изменить `MyHandler`, чтобы сохранять каждый `MemoryStream` в словарь, ключом которого будет имя ресурса. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +После загрузки можно пройтись по `handler.Resources` и записать каждый элемент на диск: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Почему это важно:** +Сохранение ресурсов позволяет выполнять постобработку, такую как оптимизация изображений, минификация CSS или архивирование. Это также даёт наглядную проверку того, что логика **создания пользовательского обработчика ресурсов** работает корректно. + +## Шаг 5: Очистка + +И `HTMLDocument`, и любые потоки следует освобождать, чтобы освободить неуправляемые ресурсы. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Полный рабочий пример + +Ниже представлена автономная программа, демонстрирующая все шаги от определения класса до извлечения ресурсов. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Ожидаемый вывод** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Консоль выводит каждый ресурс, который просмотрщик передал вашему пользовательскому обработчику, подтверждая успешное выполнение рабочего процесса **создания пользовательского обработчика ресурсов**. + +## Часто задаваемые вопросы и особые случаи + +| Вопрос | Ответ | +|----------|--------| +| *Что делать, если ресурс большой (например, изображение высокого разрешения)?* | Замените `MemoryStream` на `FileStream`, указывающий на временную папку. Это предотвратит чрезмерное потребление памяти. | +| *Можно ли фильтровать ресурсы по типу?* | Внутри `HandleResource` проверяйте `info.MimeType` или `info.Extension` и возвращайте `null` для нежелательных типов. Возврат `null` сообщает просмотрщику пропустить ресурс. | +| *Нужна ли потокобезопасность?* | Если один экземпляр обработчика используется в нескольких одновременных загрузках, защитите словарь `Resources` блокировкой или используйте конкурентную коллекцию. | +| *Как поддерживать относительные URL?* | `ResourceInfo` содержит оригинальный URL; вы можете объединить его с базовым путём HTML‑файла для разрешения относительных ссылок перед сохранением. | + +## Заключение + +Теперь вы знаете, как **создать пользовательский обработчик ресурсов** в C# для загрузки HTML, настроить `HTMLLoadOptions`, захватывать передаваемые активы и корректно освобождать ресурсы. Этот шаблон даёт полный контроль над управлением ресурсами, позволяя реализовывать такие сценарии, как обработка изображений «на лету», пере‑запись CSS или безопасное хранение. + +Далее изучайте связанные темы, такие как **загрузка HTMLDocument** с различными параметрами рендеринга, или расширяйте обработчик до **C# resource handler** реализаций, записывающих данные напрямую в облачное хранилище. Экспериментируйте с методом `HandleResource` вашего обработчика, чтобы он соответствовал специфическому рабочему процессу вашего проекта. + +## Что изучать дальше? + +Следующие руководства охватывают близкие темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, помогая вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/spanish/net/advanced-features/_index.md b/html/spanish/net/advanced-features/_index.md index 08c6f59105..1285103d01 100644 --- a/html/spanish/net/advanced-features/_index.md +++ b/html/spanish/net/advanced-features/_index.md @@ -46,6 +46,8 @@ Aprenda a convertir HTML a PDF, XPS e imágenes con Aspose.HTML para .NET. Tutor Aprenda a utilizar Aspose.HTML para .NET para generar documentos HTML de forma dinámica a partir de datos JSON. Aproveche el poder de la manipulación de HTML en sus aplicaciones .NET. ### [Cómo combinar fuentes programáticamente en C# – Guía paso a paso](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Aprenda a combinar fuentes en C# de forma programática con ejemplos claros y paso a paso. +### [Crear fuente en negrita y cursiva en C# – guía paso a paso](./create-bold-italic-font-in-c-step-by-step-guide/) +Aprenda a crear fuentes en negrita y cursiva en C# con ejemplos claros y paso a paso. ## Conclusión diff --git a/html/spanish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/spanish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..da54ead3d6 --- /dev/null +++ b/html/spanish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-08-15 +description: Crea una fuente en negrita y cursiva en C# rápidamente. Aprende cómo + crear una fuente en C# con estilos negrita y cursiva usando la clase Font incorporada. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: es +lastmod: 2026-08-15 +og_description: Crear una fuente en negrita y cursiva en C# con un ejemplo claro. + Este tutorial muestra cómo crear una fuente en C# usando los flags de FontStyle + y explica los errores comunes. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Crear fuente en negrita y cursiva en C# – guía completa de codificación +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Crear fuente en negrita y cursiva en C# – guía paso a paso +url: /es/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear fuente negrita cursiva en C# – guía paso a paso + +Si necesitas **crear una fuente negrita cursiva** en C#, esta guía te muestra exactamente cómo hacerlo. Verás un ejemplo completo y ejecutable que también demuestra cómo **crear una fuente en C#** usando la clase estándar de .NET `Font`. + +Trabajar con fuentes personalizadas es una parte rutinaria de la creación de aplicaciones de escritorio Windows, generación de PDFs o renderizado de HTML en el servidor. Al final de este tutorial podrás instanciar una fuente que sea tanto negrita como cursiva, entender por qué se usa el operador bit a bit `|` y manejar casos comunes como familias de fuentes ausentes. + +## Lo que aprenderás + +* Cómo importar los espacios de nombres requeridos para el manejo de fuentes. +* La sintaxis para combinar `FontStyle.Bold` y `FontStyle.Italic`. +* Cómo verificar que la fuente se creó correctamente. +* Consejos para el manejo de alternativas cuando la familia solicitada no está instalada. + +No se requieren bibliotecas externas: todo utiliza la biblioteca de clases base de .NET Framework / .NET Core. + +## Requisitos previos + +* SDK de .NET 6.0 o superior (el código también funciona en .NET Framework 4.6+). +* Un editor de código o IDE (Visual Studio, VS Code, Rider, etc.). +* Familiaridad básica con la sintaxis de C#. + +Si cumples con estos requisitos, puedes seguir los pasos sin ninguna configuración adicional. + +## Paso 1: Añadir las directivas `using` necesarias + +La clase `Font` se encuentra en el espacio de nombres `System.Drawing`, que forma parte del paquete NuGet `System.Drawing.Common` para .NET Core/.NET 5+. Añade el espacio de nombres al inicio de tu archivo: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Por qué este paso es importante** – Sin la línea `using System.Drawing;` el compilador no puede localizar `Font` o `FontStyle`, lo que produce un error de “type or namespace name could not be found”. + +## Paso 2: Combinar estilos negrita y cursiva con el operador OR bit a bit + +En .NET, `FontStyle` es un enum marcado con el atributo `[Flags]`. Esto significa que puedes combinar varios valores usando el operador `|` (OR bit a bit): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Explicación + +* `"Arial"` – el nombre de la familia de fuentes. Si el sistema no tiene Arial instalado, el constructor recurre a la fuente predeterminada. +* `12` – tamaño en puntos. +* `FontStyle.Bold | FontStyle.Italic` – combina los dos indicadores de estilo. El operador `|` fusiona la representación binaria de cada bandera, produciendo un único valor que representa “negrita + cursiva”. + +> **Consejo profesional:** Siempre usa los nombres del enum (`FontStyle.Bold`) en lugar de números mágicos; esto mejora la legibilidad y evita errores cuando los valores del enum cambian. + +## Paso 3: Verificar la fuente creada (opcional pero recomendado) + +Imprimir las propiedades de la fuente te ayuda a confirmar que la combinación de estilos se realizó con éxito, especialmente al depurar en una máquina nueva. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Salida esperada** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Si la salida muestra tanto `Bold` como `Italic`, la fuente se creó correctamente. + +## Paso 4: Renderizar una cadena de ejemplo (confirmación visual) + +Cuando ejecutas una aplicación de consola no puedes ver el estilo real de los glifos, pero puedes generar una imagen para demostrar el resultado. El siguiente fragmento dibuja “Hello, World!” usando la fuente negrita‑cursiva y la guarda como *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Después de que el programa termine, abre *sample.png* para ver el texto renderizado con el estilo negrita cursiva. + +![Texto de ejemplo renderizado con fuente negrita cursiva](sample.png) + +*Texto alternativo de la imagen: Captura de pantalla del texto renderizado con una fuente Arial negrita cursiva en una ventana de consola C#* – este texto alternativo satisface el requisito SEO para alt text de imágenes. + +## Paso 5: Alternativa elegante cuando la familia de fuentes no está disponible + +Si la familia solicitada (p. ej., “Arial”) no está instalada, el constructor `Font` lanza una `ArgumentException`. Envuelve la creación en un bloque `try/catch` y recurre a una fuente segura conocida como “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**¿Por qué manejar esto?** En entornos contenedorizados o sin interfaz gráfica el conjunto predeterminado de fuentes puede diferir del de un escritorio típico. Proveer una alternativa evita fallos en tiempo de ejecución y garantiza un estilo consistente. + +## Ejemplo completo y ejecutable + +Uniendo todo, aquí tienes un programa completo que puedes copiar, pegar y ejecutar: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Cómo ejecutar + +1. Guarda el código en un archivo llamado `Program.cs`. +2. Abre una terminal en el directorio del archivo. +3. Ejecuta `dotnet new console -n FontDemo` (si necesitas una estructura de proyecto). +4. Reemplaza el `Program.cs` generado con el código anterior. +5. Ejecuta `dotnet add package System.Drawing.Common` (requerido para .NET Core/5+). +6. Compila y ejecuta con `dotnet run`. + +Verás la salida en la consola confirmando las propiedades de la fuente, y `sample.png` aparecerá en la carpeta del proyecto. + +## Errores comunes y cómo evitarlos + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| **Falta el paquete `System.Drawing.Common`** | .NET Core no incluye `System.Drawing` por defecto. | Ejecuta `dotnet add package System.Drawing.Common`. | +| **Familia de fuentes no instalada** | Las imágenes Docker sin entorno gráfico suelen carecer de fuentes de Windows. | Usa una fuente alternativa o instala las fuentes necesarias en el contenedor. | +| **Uso incorrecto de `|`** | Usar `+` en lugar de `|` produce una combinación inválida. | Siempre combina valores de `FontStyle` con el operador OR bit a bit (`|`). | +| **No disponer del objeto `Font`** | No llamar a `Dispose` puede provocar fugas de recursos GDI. | Envuelve `Font` en un bloque `using` o llama a `font.Dispose()` cuando termines. | + +## Conclusión + +Ahora sabes cómo **crear una fuente negrita cursiva** en C# y cómo **crear una fuente en C#** de forma segura y eficiente. El tutorial cubrió la importación del espacio de nombres correcto, la combinación de banderas `FontStyle`, la verificación del resultado, la generación de una muestra visual y el manejo de familias de fuentes ausentes. + +A continuación, podrías explorar: + +* **Crear fuentes subrayadas o tachadas** – añade `FontStyle.Underline` o `FontStyle.Strikeout`. +* **Usar fuentes TrueType personalizadas** – carga un archivo `.ttf` con `PrivateFontCollection`. +* **Aplicar fuentes en WinForms, WPF o generación de PDFs** – el mismo objeto `Font` puede pasarse a controles UI o bibliotecas de terceros. + +Siéntete libre de experimentar con diferentes familias, tamaños y combinaciones de estilo. Si encuentras problemas, revisa la tabla “Errores comunes” o consulta la documentación oficial de [.NET para System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). ¡Feliz codificación! + +## ¿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. + +- [Cara Menggabungkan Font Secara Programatis di C# – Panduan Langkah demi Langkah](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [convert docx to png – create zip archive c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/spanish/net/working-with-html-documents/_index.md b/html/spanish/net/working-with-html-documents/_index.md index e0db1c958a..1e5734f2e4 100644 --- a/html/spanish/net/working-with-html-documents/_index.md +++ b/html/spanish/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ Una vez que haya comprendido los conceptos básicos, profundizaremos en el proce Ahora, llevemos tus habilidades al siguiente nivel. Editar documentos HTML es una tarea común para los desarrolladores web, y Aspose.HTML simplifica este proceso significativamente. En esta sección, cubriremos la creación, manipulación y estilo de documentos. Descubrirás cómo mejorar la apariencia y la funcionalidad de tu contenido web, haciéndolo atractivo y fácil de usar. ### [Cómo guardar HTML en C# – Guía completa usando un controlador de recursos personalizado](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [Crear controlador de recursos personalizado en C# para cargar HTML](./create-custom-resource-handler-in-c-for-html-loading/) + ### [Cómo poner en negrita un encabezado con CSS y C# – Guía completa paso a paso](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) Aprenda a aplicar estilo negrita a encabezados usando CSS y C# con este tutorial detallado. diff --git a/html/spanish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/spanish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..56f9e36f46 --- /dev/null +++ b/html/spanish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-08-15 +description: Crea un manejador de recursos personalizado en C# para gestionar recursos + HTML como imágenes y CSS. Aprende sobre HTMLLoadOptions, flujos de memoria y la + carga de HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: es +lastmod: 2026-08-15 +og_description: Crea un controlador de recursos personalizado en C# para controlar + cómo se transmiten los recursos HTML. Este tutorial muestra la configuración de + HTMLLoadOptions, el manejo de streams de memoria y la carga de HTMLDocument con + lógica personalizada. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Crear controlador de recursos personalizado en C# – guía completa para la + gestión de recursos HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Crear controlador de recursos personalizado en C# para cargar HTML +url: /es/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear un manejador de recursos personalizado en C# para la carga de HTML + +Si necesitas **crear un manejador de recursos personalizado** para archivos HTML, esta guía te muestra exactamente cómo. Aprenderás a interceptar imágenes, CSS y otros recursos al cargar un documento HTML, usando `HTMLLoadOptions` y un flujo basado en memoria. + +El tutorial cubre todo lo necesario para implementar un manejador reutilizable, configurar las opciones de carga y verificar que los recursos se capturan correctamente. No se necesita documentación externa, solo el código a continuación y las explicaciones. + +## Requisitos previos + +- .NET 6.0 o posterior +- Familiaridad básica con C# +- Una referencia a la biblioteca de procesamiento HTML que proporcione `HTMLDocument`, `HtmlLoadOptions` y `ResourceHandler` (p. ej., GroupDocs.Viewer for .NET) + +## Visión general de la solución + +Vamos a: + +1. **Crear un manejador de recursos personalizado** mediante la subclase de `ResourceHandler`. +2. Configurar `HTMLLoadOptions` para usar el manejador. +3. Cargar un archivo HTML con `HTMLDocument` mientras el manejador suministra un flujo para cada recurso. +4. (Opcional) Almacenar los recursos recibidos en disco para verificación. + +Cada paso incluye el código fuente completo y el razonamiento detrás de él. + +## Paso 1: Definir la clase del manejador de recursos personalizado + +Crear un manejador personalizado significa sobrescribir `HandleResource` para que la biblioteca pueda escribir los bytes del recurso en un flujo que tú controlas. Usar un `MemoryStream` mantiene los datos en memoria, lo que es ideal para pruebas o procesamiento posterior. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Por qué es importante:** +Sobrescribir `HandleResource` te brinda control total sobre dónde se envían los datos del recurso. Si más adelante necesitas almacenar en caché imágenes, transformar CSS o registrar el uso de recursos, puedes reemplazar el `MemoryStream` por cualquier implementación de flujo personalizada. + +## Paso 2: Configurar `HTMLLoadOptions` para usar el manejador + +`HTMLLoadOptions` te permite conectar el manejador en la cadena de carga. Asignar la propiedad `ResourceHandler` indica al visor que invoque `MyHandler` para cada activo externo. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Por qué es importante:** +Sin asignar `ResourceHandler`, el visor escribiría los recursos en su ubicación predeterminada (a menudo una carpeta temporal). Al especificar tu propio manejador, **creas un manejador de recursos personalizado** que se alinea con la estrategia de almacenamiento de tu aplicación. + +## Paso 3: Cargar el documento HTML con las opciones configuradas + +Ahora carga el archivo HTML. El visor llamará a `MyHandler.HandleResource` por cada recurso que encuentre. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +En este punto el contenido HTML se ha analizado y todos los recursos externos se han transmitido a los búferes de memoria suministrados por `MyHandler`. + +## Paso 4 (opcional): Acceder a los recursos capturados + +Si necesitas inspeccionar o persistir los recursos, puedes modificar `MyHandler` para almacenar cada `MemoryStream` en un diccionario indexado por el nombre del recurso. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Después de la carga, puedes iterar sobre `handler.Resources` y escribir cada uno en disco: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Por qué es importante:** +Almacenar los recursos permite el post‑procesamiento, como optimización de imágenes, minificación de CSS o archivado. También proporciona una verificación tangible de que la lógica de **crear un manejador de recursos personalizado** funciona como se espera. + +## Paso 5: Limpieza + +Tanto `HTMLDocument` como cualquier flujo deben disponerse para liberar recursos no administrados. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Ejemplo completo ejecutable + +A continuación se muestra un programa autocontenido que demuestra todos los pasos, desde la definición de la clase hasta la extracción de recursos. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Salida esperada** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +La consola enumera cada recurso que el visor transmitió a través de tu manejador personalizado, confirmando que el flujo de **crear un manejador de recursos personalizado** se completó con éxito. + +## Preguntas frecuentes y casos límite + +| Pregunta | Respuesta | +|----------|-----------| +| *¿Qué pasa si un recurso es grande (p. ej., una imagen de alta resolución)?* | Reemplaza `MemoryStream` por un `FileStream` que apunte a una carpeta temporal. Esto evita un consumo excesivo de memoria. | +| *¿Puedo filtrar recursos por tipo?* | Dentro de `HandleResource`, inspecciona `info.MimeType` o `info.Extension` y devuelve `null` para los tipos no deseados. Devolver `null` indica al visor que omita el recurso. | +| *¿Se requiere seguridad en hilos?* | Si la misma instancia del manejador se usa en múltiples cargas concurrentes, protege el diccionario `Resources` con un bloqueo o utiliza una colección concurrente. | +| *¿Cómo admito URLs relativas?* | `ResourceInfo` contiene la URL original; puedes combinarla con la ruta base del archivo HTML para resolver referencias relativas antes de almacenarlas. | + +## Conclusión + +Ahora sabes cómo **crear un manejador de recursos personalizado** en C# para la carga de HTML, configurar `HTMLLoadOptions`, capturar los activos transmitidos y limpiar de forma responsable. Este patrón te brinda control total sobre la gestión de recursos, habilitando escenarios como procesamiento de imágenes en tiempo real, reescritura de CSS o almacenamiento seguro. + +A continuación, explora temas relacionados como la **carga de HTMLDocument** con diferentes opciones de renderizado, o extiende el manejador a implementaciones de **manejador de recursos en C#** que escriban directamente en almacenamiento en la nube. Experimenta con el método `HandleResource` del manejador para adaptarlo al flujo de recursos específico de tu proyecto. + +## ¿Qué deberías aprender a continuación? + +Los tutoriales siguientes cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/swedish/net/advanced-features/_index.md b/html/swedish/net/advanced-features/_index.md index 87a29e398e..b840a75b1b 100644 --- a/html/swedish/net/advanced-features/_index.md +++ b/html/swedish/net/advanced-features/_index.md @@ -46,6 +46,7 @@ Lär dig hur du konverterar HTML till PDF, XPS och bilder med Aspose.HTML för . Lär dig hur du använder Aspose.HTML för .NET för att dynamiskt generera HTML-dokument från JSON-data. Utnyttja kraften i HTML-manipulation i dina .NET-applikationer. ### [Hur du kombinerar teckensnitt programatiskt i C# – Steg‑för‑steg‑guide](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) Lär dig att kombinera flera teckensnitt i ett HTML-dokument med C# och Aspose.HTML i en enkel steg‑för‑steg‑guide. +### [Skapa fet kursiv font i C# – steg‑för‑steg‑guide](./create-bold-italic-font-in-c-step-by-step-guide/) ## Slutsats diff --git a/html/swedish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/swedish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..b278491126 --- /dev/null +++ b/html/swedish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-08-15 +description: Skapa fet kursiv font i C# snabbt. Lär dig hur du skapar en font i C# + med fet och kursiv stil med den inbyggda Font‑klassen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: sv +lastmod: 2026-08-15 +og_description: Skapa fet kursiv font i C# med ett tydligt exempel. Denna handledning + visar hur man skapar font i C# med FontStyle‑flaggor och förklarar vanliga fallgropar. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Skapa fet kursiv teckensnitt i C# – komplett kodningsguide +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Skapa fet kursiv teckensnitt i C# – steg‑för‑steg guide +url: /sv/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa fet kursiv font i C# – steg‑för‑steg guide + +Om du behöver **skapa fet kursiv font** i C#, visar den här guiden exakt hur du gör det. Du får se ett komplett, körbart exempel som också demonstrerar hur du **skapar font i C#** med den standard .NET `Font`-klassen. + +Att arbeta med anpassade fonter är en rutinmässig del av att bygga Windows‑desktop‑appar, generera PDF‑filer eller rendera HTML på servern. I slutet av den här handledningen kommer du att kunna instansiera en font som både är fet och kursiv, förstå varför den bitvisa `|`‑operatorn används, och hantera vanliga edge‑cases som saknade font‑familjer. + +## Vad du kommer att lära dig + +* Hur du importerar de nödvändiga namnområdena för font‑hantering. +* Syntaxen för att kombinera `FontStyle.Bold` och `FontStyle.Italic`. +* Hur du verifierar att fonten skapades framgångsrikt. +* Tips för fallback‑hantering när den begärda familjen inte är installerad. + +Inga externa bibliotek krävs—allt använder .NET Framework / .NET Core basbiblioteket. + +## Förutsättningar + +* .NET 6.0 SDK eller senare (koden fungerar även på .NET Framework 4.6+). +* En kodredigerare eller IDE (Visual Studio, VS Code, Rider, osv.). +* Grundläggande kunskap om C#‑syntax. + +Om du uppfyller dessa förutsättningar kan du följa stegen utan någon extra konfiguration. + +## Steg 1: Lägg till nödvändiga using‑direktiv + +`Font`‑klassen finns i `System.Drawing`‑namnområdet, som är en del av NuGet‑paketet `System.Drawing.Common` för .NET Core/.NET 5+. Lägg till namnområdet högst upp i din fil: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Varför detta steg är viktigt** – Utan raden `using System.Drawing;` kan kompilatorn inte hitta `Font` eller `FontStyle`, vilket resulterar i ett felmeddelandet “type or namespace name could not be found”. + +## Steg 2: Kombinera fet och kursiv stil med den bitvisa OR‑operatorn + +I .NET är `FontStyle` en enum markerad med attributet `[Flags]`. Det betyder att du kan kombinera flera värden med `|`‑operatorn (bitvis OR): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Förklaring + +* `"Arial"` – fontfamiljens namn. Om systemet inte har Arial installerat, faller konstruktorn tillbaka till standardfonten. +* `12` – punktstorlek. +* `FontStyle.Bold | FontStyle.Italic` – kombinerar de två stilflaggorna. `|`‑operatorn slår ihop den binära representationen av varje flagga och producerar ett enda värde som representerar “bold + italic”. + +> **Proffstips:** Använd alltid enum‑namnen (`FontStyle.Bold`) istället för magiska tal; detta förbättrar läsbarheten och förhindrar buggar när enum‑värdena ändras. + +## Steg 3: Verifiera den skapade fonten (valfritt men rekommenderat) + +Att skriva ut fontens egenskaper hjälper dig bekräfta att stilkombinationen lyckades, särskilt när du felsöker på en ny maskin. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Förväntad output** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Om outputen listar både `Bold` och `Italic` har fonten skapats korrekt. + +## Steg 4: Rendera en exempelsträng (visuell bekräftelse) + +När du kör en konsolapp kan du inte se den faktiska glyf‑stilen, men du kan generera en bild för att bevisa resultatet. Följande kodsnutt ritar “Hello, World!” med den feta‑kursiva fonten och sparar den som *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +När programmet har körts, öppna *sample.png* för att se texten renderad med fet kursiv stil. + +![Exempeltext renderad med fet kursiv font](sample.png) + +*Bild‑alt‑text: Skärmdump av text renderad med en fet kursiv Arial‑font i ett C#‑konsolfönster* – denna alt‑text uppfyller SEO‑kravet för bild‑alt‑text. + +## Steg 5: Graceful fallback när fontfamiljen är otillgänglig + +Om den begärda familjen (t.ex. “Arial”) inte är installerad kastar `Font`‑konstruktorn ett `ArgumentException`. Omge skapandet med ett `try/catch`‑block och falla tillbaka till en känd säker font som “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Varför hantera detta?** I containeriserade eller huvudlösa miljöer kan standarduppsättningen av fonter skilja sig från en vanlig skrivbordsmiljö. Att tillhandahålla en fallback förhindrar krasch vid körning och säkerställer konsekvent styling. + +## Fullständigt, körbart exempel + +Sätter vi ihop allt får du ett komplett program som du kan kopiera, klistra in och köra: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Så kör du + +1. Spara koden i en fil med namnet `Program.cs`. +2. Öppna en terminal i filens katalog. +3. Kör `dotnet new console -n FontDemo` (om du behöver ett projekt‑scaffold). +4. Byt ut den genererade `Program.cs` mot koden ovan. +5. Kör `dotnet add package System.Drawing.Common` (krävs för .NET Core/5+). +6. Bygg och kör med `dotnet run`. + +Du kommer att se konsolutdata som bekräftar fontens egenskaper, och `sample.png` kommer att dyka upp i projektmappen. + +## Vanliga fallgropar och hur du undviker dem + +| Fallgrop | Varför det händer | Åtgärd | +|----------|-------------------|--------| +| **Missing `System.Drawing.Common` package** | .NET Core inkluderar inte `System.Drawing` som standard. | Kör `dotnet add package System.Drawing.Common`. | +| **Font family not installed** | Huvudlösa Docker‑bilder saknar ofta Windows‑fonter. | Använd en fallback‑font eller installera de nödvändiga fonterna i containern. | +| **Incorrect use of `|`** | Att använda `+` istället för `|` ger en ogiltig kombination. | Kombinera alltid `FontStyle`‑värden med den bitvisa OR‑operatorn (`|`). | +| **Disposing the `Font` object** | Att inte anropa `Dispose` kan leda till läckage av GDI‑resurser. | Omge `Font` med ett `using`‑block eller anropa `font.Dispose()` när du är klar. | + +## Slutsats + +Du vet nu hur du **skapar fet kursiv font** i C# och hur du **skapar font i C#** på ett säkert och effektivt sätt. Handledningen täckte import av rätt namnrymd, kombination av `FontStyle`‑flaggor, verifiering av resultatet, rendering av ett visuellt exempel och hantering av saknade fontfamiljer. + +Nästa steg kan du utforska: + +* **Skapa understrukna eller genomstrukna fonter** – lägg till `FontStyle.Underline` eller `FontStyle.Strikeout`. +* **Använda anpassade TrueType‑fonter** – ladda en `.ttf`‑fil med `PrivateFontCollection`. +* **Applicera fonter i WinForms, WPF eller PDF‑generering** – samma `Font`‑objekt kan skickas till UI‑kontroller eller tredjepartsbibliotek. + +Du är välkommen att experimentera med olika familjer, storlekar och stilkombinationer. Om du stöter på problem, gå tillbaka till tabellen “Vanliga fallgropar” eller kontrollera den officiella [.NET‑dokumentationen för System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Lycka till med kodandet! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man kombinerar fonter programatiskt i C# – steg‑för‑steg‑guide](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Skapa HTML‑dokument med formaterad text och exportera till PDF – fullständig guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [konvertera docx till png – skapa zip‑arkiv c#‑handledning](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/swedish/net/working-with-html-documents/_index.md b/html/swedish/net/working-with-html-documents/_index.md index a3260bb44c..9cc776005f 100644 --- a/html/swedish/net/working-with-html-documents/_index.md +++ b/html/swedish/net/working-with-html-documents/_index.md @@ -43,6 +43,10 @@ Lär dig spara HTML i C# med en anpassad resurs‑hanterare och generera komplet Lär dig hur du använder CSS och C# för att göra rubriker fetstilta i dina HTML‑dokument med en steg‑för‑steg‑guide. +### [Skapa en anpassad resurs‑hanterare i C# för HTML‑laddning](./create-custom-resource-handler-in-c-for-html-loading/) + +Lär dig skapa en anpassad resurs‑hanterare i C# för att ladda HTML‑dokument. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/swedish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/swedish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..c557a999b0 --- /dev/null +++ b/html/swedish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-08-15 +description: Skapa en anpassad resurs‑hanterare i C# för att hantera HTML‑resurser + som bilder och CSS. Lär dig HTMLLoadOptions, minnesströmmar och laddning av HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: sv +lastmod: 2026-08-15 +og_description: Skapa en anpassad resurs‑hanterare i C# för att kontrollera hur HTML‑resurser + strömmas. Denna handledning visar hur man konfigurerar HTMLLoadOptions, hanterar + minnesström och laddar HTMLDocument med anpassad logik. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Skapa anpassad resurs‑hanterare i C# – fullständig guide för HTML‑resurshantering +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Skapa anpassad resurs‑hanterare i C# för HTML‑laddning +url: /sv/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa anpassad resurs‑hanterare i C# för HTML‑laddning + +Om du behöver **create custom resource handler** för HTML‑filer, visar den här guiden exakt hur. Du kommer att lära dig att avlyssna bilder, CSS och andra resurser när du laddar ett HTML‑dokument, med hjälp av `HTMLLoadOptions` och en minnes‑baserad ström. + +Handledningen täcker allt som krävs för att implementera en återanvändbar hanterare, konfigurera laddningsalternativ och verifiera att resurser fångas korrekt. Ingen extern dokumentation behövs—bara koden nedan och förklaringarna. + +## Förutsättningar + +- .NET 6.0 eller senare +- Grundläggande kunskap om C# +- En referens till HTML‑bearbetningsbiblioteket som tillhandahåller `HTMLDocument`, `HtmlLoadOptions` och `ResourceHandler` (t.ex. GroupDocs.Viewer för .NET) + +## Översikt av lösningen + +Vi kommer att: + +1. **Create a custom resource handler** genom att subklassa `ResourceHandler`. +2. Konfigurera `HTMLLoadOptions` för att använda hanteraren. +3. Ladda en HTML‑fil med `HTMLDocument` medan hanteraren tillhandahåller en ström för varje resurs. +4. (Valfritt) Spara mottagna resurser till disk för verifiering. + +Varje steg innehåller full källkod och resonemanget bakom. + +## Steg 1: Definiera den anpassade resurs‑hanterarklassen + +Att skapa en anpassad hanterare innebär att åsidosätta `HandleResource` så att biblioteket kan skriva resurs‑byte till en ström du kontrollerar. Att använda en `MemoryStream` håller data i minnet, vilket är idealiskt för testning eller vidare bearbetning. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Varför detta är viktigt:** +Att åsidosätta `HandleResource` ger dig full kontroll över var resursdata placeras. Om du senare behöver cacha bilder, transformera CSS eller logga resursanvändning, kan du ersätta `MemoryStream` med någon anpassad ström‑implementation. + +## Steg 2: Konfigurera `HTMLLoadOptions` för att använda hanteraren + +`HTMLLoadOptions` låter dig ansluta hanteraren till laddnings‑pipeline. Genom att sätta egenskapen `ResourceHandler` instrueras visaren att anropa `MyHandler` för varje extern tillgång. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Varför detta är viktigt:** +Utan att tilldela `ResourceHandler` skulle visaren skriva resurser till sin standardplats (ofta en temporär mapp). Genom att specificera din egen hanterare, **create custom resource handler**‑beteendet som matchar din applikations lagringsstrategi. + +## Steg 3: Ladda HTML‑dokumentet med de konfigurerade alternativen + +Ladda nu HTML‑filen. Visaren kommer att anropa `MyHandler.HandleResource` för varje resurs den stöter på. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Vid detta tillfälle har HTML‑innehållet parsats och alla externa resurser har strömmas in i minnesbuffertarna som tillhandahålls av `MyHandler`. + +## Steg 4 (valfritt): Åtkomst till de fångade resurserna + +Om du behöver inspektera eller lagra resurserna kan du modifiera `MyHandler` för att spara varje `MemoryStream` i en dictionary nycklad med resursnamnet. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Efter laddning kan du iterera över `handler.Resources` och skriva varje till disk: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Varför detta är viktigt:** +Att lagra resurser möjliggör efterbehandling såsom bildoptimering, CSS‑minifiering eller arkivering. Det ger också en påtaglig verifiering att **create custom resource handler**‑logiken fungerar som avsett. + +## Steg 5: Rensa upp + +Både `HTMLDocument` och alla strömmar bör avyttras för att frigöra ohanterade resurser. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Fullt körbart exempel + +Nedan är ett fristående program som demonstrerar alla steg från klassdefinition till resursutvinning. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Förväntad output** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Konsolen listar varje resurs som visaren strömmade genom din anpassade hanterare, vilket bekräftar att **create custom resource handler**‑arbetsflödet lyckades. + +## Vanliga frågor och kantfall + +| Question | Answer | +|----------|--------| +| *Vad händer om en resurs är stor (t.ex. högupplöst bild)?* | Ersätt `MemoryStream` med en `FileStream` som pekar på en temporär mapp. Detta förhindrar överdriven minnesanvändning. | +| *Kan jag filtrera resurser efter typ?* | Inuti `HandleResource`, inspektera `info.MimeType` eller `info.Extension` och returnera `null` för oönskade typer. Att returnera `null` instruerar visaren att hoppa över resursen. | +| *Krävs trådsäkerhet?* | Om samma hanterarinstans används över flera samtidiga laddningar, skydda `Resources`‑dictionaryn med en låsning eller använd en trådsäker samling. | +| *Hur stödjer jag relativa URL:er?* | `ResourceInfo` innehåller den ursprungliga URL:en; du kan kombinera den med basvägen för HTML‑filen för att lösa relativa referenser innan lagring. | + +## Slutsats + +Du vet nu hur du **create custom resource handler** i C# för HTML‑laddning, konfigurerar `HTMLLoadOptions`, fångar strömmade tillgångar och rensar upp på ett ansvarsfullt sätt. Detta mönster ger dig full kontroll över resurshantering, vilket möjliggör scenarier som bildbehandling i farten, CSS‑omskrivning eller säker lagring. + +Nästa steg, utforska relaterade ämnen som **HTMLDocument loading** med olika renderingsalternativ, eller utöka hanteraren till **C# resource handler**‑implementationer som skriver direkt till molnlagring. Experimentera med hanterarens `HandleResource`‑metod för att anpassa den till ditt projekts specifika resursarbetsflöde. + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker nära besläktade ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementeringsmetoder i dina egna projekt. + +- [Skapa HTML från sträng i C# – Guide för anpassad resurs‑hanterare](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Anpassad resurs‑hanterare i C# – Konvertera HTML till ZIP‑handledning](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [Hur man sparar HTML i C# – Komplett guide med en anpassad resurs‑hanterare](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/thai/net/advanced-features/_index.md b/html/thai/net/advanced-features/_index.md index 3f7a46f935..a86ce697f2 100644 --- a/html/thai/net/advanced-features/_index.md +++ b/html/thai/net/advanced-features/_index.md @@ -46,6 +46,7 @@ Aspose.HTML สำหรับ .NET เป็นเครื่องมือ เรียนรู้วิธีใช้ Aspose.HTML สำหรับ .NET เพื่อสร้างเอกสาร HTML แบบไดนามิกจากข้อมูล JSON ใช้ประโยชน์จากพลังของการจัดการ HTML ในแอปพลิเคชัน .NET ของคุณ ### [วิธีรวมฟอนต์โดยใช้โปรแกรมใน C# – คู่มือขั้นตอนต่อขั้นตอน](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) เรียนรู้วิธีรวมฟอนต์หลายแบบใน C# ด้วย Aspose.HTML อย่างละเอียด พร้อมตัวอย่างโค้ดและคำแนะนำทีละขั้นตอน +### [สร้างฟอนต์หนาเอียงใน C# – คู่มือขั้นตอนต่อขั้นตอน](./create-bold-italic-font-in-c-step-by-step-guide/) ## บทสรุป diff --git a/html/thai/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/thai/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..5b713623b7 --- /dev/null +++ b/html/thai/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-08-15 +description: สร้างฟอนต์หนาและเอียงใน C# อย่างรวดเร็ว เรียนรู้วิธีสร้างฟอนต์ใน C# ด้วยสไตล์หนาและเอียงโดยใช้คลาส + Font ที่มีมาในตัว. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: th +lastmod: 2026-08-15 +og_description: สร้างฟอนต์หนาเอียงใน C# พร้อมตัวอย่างที่ชัดเจน บทเรียนนี้แสดงวิธีสร้างฟอนต์ใน + C# ด้วยการใช้แฟล็ก FontStyle และอธิบายข้อผิดพลาดทั่วไป +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: สร้างฟอนต์หนาเอียงใน C# – คู่มือการเขียนโค้ดฉบับเต็ม +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: สร้างฟอนต์หนาและเอียงใน C# – คู่มือแบบทีละขั้นตอน +url: /th/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างฟอนต์หนาและเอียงใน C# – คู่มือขั้นตอนโดยละเอียด + +หากคุณต้องการ **สร้างฟอนต์หนาและเอียง** ใน C# คู่มือนี้จะแสดงให้คุณเห็นขั้นตอนทั้งหมดอย่างชัดเจน คุณจะได้เห็นตัวอย่างที่ทำงานได้เต็มรูปแบบซึ่งยังสาธิตวิธี **สร้างฟอนต์ใน C#** ด้วยคลาสมาตรฐานของ .NET `Font` + +การทำงานกับฟอนต์แบบกำหนดเองเป็นส่วนหนึ่งของการพัฒนาแอปพลิเคชัน Windows desktop, การสร้าง PDF, หรือการเรนเดอร์ HTML บนเซิร์ฟเวอร์ เมื่อจบบทเรียนนี้คุณจะสามารถสร้างอ็อบเจ็กต์ฟอนต์ที่เป็นทั้งหนาและเอียง, เข้าใจเหตุผลที่ใช้ตัวดำเนินการบิตวายส์ `|`, และจัดการกับกรณีขอบเขตทั่วไปเช่นฟอนต์ตระกูลที่หายไป + +## สิ่งที่คุณจะได้เรียนรู้ + +* วิธีนำเข้า namespace ที่จำเป็นสำหรับการจัดการฟอนต์ +* ไวยากรณ์การรวม `FontStyle.Bold` กับ `FontStyle.Italic` +* วิธีตรวจสอบว่าฟอนต์ถูกสร้างสำเร็จหรือไม่ +* เคล็ดลับการจัดการ fallback เมื่อตระกูลฟอนต์ที่ร้องขอไม่ได้ติดตั้ง + +ไม่ต้องใช้ไลบรารีภายนอก—ทั้งหมดใช้ .NET Framework / .NET Core base class library + +## ข้อกำหนดเบื้องต้น + +* .NET 6.0 SDK หรือใหม่กว่า (โค้ดนี้ยังทำงานบน .NET Framework 4.6+) +* โปรแกรมแก้ไขโค้ดหรือ IDE (Visual Studio, VS Code, Rider ฯลฯ) +* ความคุ้นเคยพื้นฐานกับไวยากรณ์ C# + +หากคุณตรงตามข้อกำหนดเหล่านี้ คุณสามารถทำตามขั้นตอนต่อไปได้โดยไม่ต้องตั้งค่าเพิ่มเติม + +## ขั้นตอนที่ 1: เพิ่ม using directives ที่จำเป็น + +คลาส `Font` อยู่ใน namespace `System.Drawing` ซึ่งเป็นส่วนหนึ่งของแพคเกจ NuGet `System.Drawing.Common` สำหรับ .NET Core/.NET 5+ เพิ่ม namespace นี้ที่ส่วนบนของไฟล์ของคุณ: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **ทำไมขั้นตอนนี้สำคัญ** – หากไม่มีบรรทัด `using System.Drawing;` ตัวคอมไพเลอร์จะไม่สามารถหา `Font` หรือ `FontStyle` ได้ ทำให้เกิดข้อผิดพลาด “type or namespace name could not be found” + +## ขั้นตอนที่ 2: รวมสไตล์หนาและเอียงด้วยตัวดำเนินการบิตวายส์ OR + +ใน .NET, `FontStyle` เป็น enum ที่มี attribute `[Flags]` ซึ่งหมายความว่าคุณสามารถรวมค่าหลายค่าเข้าด้วยกันโดยใช้ตัวดำเนินการ `|` (บิตวายส์ OR): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### คำอธิบาย + +* `"Arial"` – ชื่อฟอนต์ตระกูล หากระบบไม่มี Arial ติดตั้ง ตัวสร้างจะ fallback ไปยังฟอนต์เริ่มต้น +* `12` – ขนาดจุด +* `FontStyle.Bold | FontStyle.Italic` – รวมสอง flag ของสไตล์เข้าด้วยกัน ตัวดำเนินการ `|` จะผสานการแสดงผลไบนารีของแต่ละ flag ให้เป็นค่าหนึ่งที่แทน “หนา + เอียง” + +> **เคล็ดลับระดับมืออาชีพ:** ควรใช้ชื่อ enum (`FontStyle.Bold`) แทนการใช้ตัวเลขคงที่; วิธีนี้ทำให้โค้ดอ่านง่ายและลดโอกาสเกิดบั๊กเมื่อค่า enum มีการเปลี่ยนแปลง + +## ขั้นตอนที่ 3: ตรวจสอบฟอนต์ที่สร้าง (ไม่บังคับแต่แนะนำ) + +การพิมพ์คุณสมบัติของฟอนต์ช่วยให้คุณยืนยันว่าการรวมสไตล์สำเร็จหรือไม่ โดยเฉพาะเมื่อทำการดีบักบนเครื่องใหม่ + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**ผลลัพธ์ที่คาดหวัง** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +หากผลลัพธ์แสดงทั้ง `Bold` และ `Italic` แสดงว่าฟอนต์ถูกสร้างอย่างถูกต้อง + +## ขั้นตอนที่ 4: แสดงตัวอย่างข้อความ (ยืนยันด้วยภาพ) + +เมื่อรันแอปคอนโซลคุณจะไม่เห็นสไตล์ glyph จริง แต่คุณสามารถสร้างภาพเพื่อพิสูจน์ผลลัพธ์ได้ โค้ดต่อไปนี้วาดข้อความ “Hello, World!” ด้วยฟอนต์หนา‑เอียงและบันทึกเป็น *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +หลังจากโปรแกรมทำงานเสร็จ ให้เปิด *sample.png* เพื่อดูข้อความที่เรนเดอร์ด้วยสไตล์หนาและเอียง + +![Sample text rendered with bold italic font](sample.png) + +*ข้อความแทนภาพ: ภาพหน้าจอของข้อความที่เรนเดอร์ด้วยฟอนต์ Arial หนาและเอียงในหน้าต่างคอนโซลของ C#* – ข้อความแทนภาพนี้ตอบสนองความต้องการ SEO สำหรับ alt text ของภาพ + +## ขั้นตอนที่ 5: จัดการ fallback อย่างราบรื่นเมื่อฟอนต์ตระกูลไม่พร้อมใช้งาน + +หากฟอนต์ตระกูลที่ร้องขอ (เช่น “Arial”) ไม่ได้ติดตั้ง ตัวสร้าง `Font` จะโยน `ArgumentException` ให้ห่อการสร้างในบล็อก `try/catch` และ fallback ไปยังฟอนต์ที่ปลอดภัยเช่น “Segoe UI” + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**ทำไมต้องจัดการกรณีนี้?** ในสภาพแวดล้อมแบบคอนเทนเนอร์หรือ headless ชุดฟอนต์เริ่มต้นอาจแตกต่างจากเดสก์ท็อปทั่วไป การมี fallback จะป้องกันการพังของแอปในขณะรันไทม์และทำให้สไตล์คงที่ + +## ตัวอย่างเต็มที่สามารถรันได้ + +รวมทุกอย่างเข้าด้วยกัน นี่คือโปรแกรมสมบูรณ์ที่คุณสามารถคัดลอก, วาง, แล้วรันได้: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### วิธีรัน + +1. บันทึกโค้ดเป็นไฟล์ชื่อ `Program.cs` +2. เปิดเทอร์มินัลในโฟลเดอร์ที่ไฟล์อยู่ +3. รัน `dotnet new console -n FontDemo` (หากต้องการ scaffold โปรเจกต์) +4. แทนที่ `Program.cs` ที่สร้างขึ้นด้วยโค้ดด้านบน +5. รัน `dotnet add package System.Drawing.Common` (จำเป็นสำหรับ .NET Core/5+) +6. สร้างและรันด้วย `dotnet run` + +คุณจะเห็นผลลัพธ์ในคอนโซลที่ยืนยันคุณสมบัติของฟอนต์ และไฟล์ `sample.png` จะปรากฏในโฟลเดอร์โปรเจกต์ + +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +| ปัญหา | สาเหตุ | วิธีแก้ | +|---------|----------------|-----| +| **Missing `System.Drawing.Common` package** | .NET Core ไม่ได้รวม `System.Drawing` มาโดยอัตโนมัติ | รัน `dotnet add package System.Drawing.Common` | +| **Font family not installed** | ภาพ Docker แบบ headless มักไม่มีฟอนต์ Windows | ใช้ฟอนต์ fallback หรือทำการติดตั้งฟอนต์ที่ต้องการในคอนเทนเนอร์ | +| **Incorrect use of `|`** | ใช้ `+` แทน `|` ทำให้การรวมค่าไม่ถูกต้อง | ต้องรวมค่า `FontStyle` ด้วยตัวดำเนินการบิตวายส์ OR (`|`) เท่านั้น | +| **Disposing the `Font` object** | ไม่เรียก `Dispose` ทำให้ทรัพยากร GDI รั่ว | ห่อ `Font` ด้วย `using` block หรือเรียก `font.Dispose()` หลังใช้งานเสร็จ | + +## สรุป + +คุณได้เรียนรู้วิธี **สร้างฟอนต์หนาและเอียง** ใน C# และวิธี **สร้างฟอนต์ใน C#** อย่างปลอดภัยและมีประสิทธิภาพ บทเรียนนี้ครอบคลุมการนำเข้า namespace ที่ถูกต้อง, การรวม flag ของ `FontStyle`, การตรวจสอบผลลัพธ์, การเรนเดอร์ตัวอย่างภาพ, และการจัดการกรณีฟอนต์ตระกูลหายไป + +ต่อไปคุณอาจสนใจ: + +* **สร้างฟอนต์ที่มีการขีดเส้นใต้หรือขีดฆ่า** – เพิ่ม `FontStyle.Underline` หรือ `FontStyle.Strikeout` +* **ใช้ฟอนต์ TrueType แบบกำหนดเอง** – โหลดไฟล์ `.ttf` ด้วย `PrivateFontCollection` +* **นำฟอนต์ไปใช้ใน WinForms, WPF, หรือการสร้าง PDF** – อ็อบเจ็กต์ `Font` เดียวกันสามารถส่งต่อให้คอนโทรล UI หรือไลบรารีของบุคคลที่สามได้ + +ลองทดลองเปลี่ยนตระกูล, ขนาด, และการรวมสไตล์ต่าง ๆ หากเจอปัญหา ให้กลับไปตรวจสอบตาราง “ข้อผิดพลาดทั่วไป” หรือดูเอกสารอย่างเป็นทางการของ [.NET documentation for System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font) ขอให้สนุกกับการเขียนโค้ด! + +## สิ่งที่คุณควรเรียนต่อไป + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [วิธีการรวมฟอนต์โดยโปรแกรมใน C# – คู่มือขั้นตอนโดยละเอียด](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [สร้างเอกสาร HTML พร้อมข้อความสไตล์และส่งออกเป็น PDF – คู่มือเต็ม](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [แปลง docx เป็น png – สร้างไฟล์ zip c# tutorial](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/thai/net/working-with-html-documents/_index.md b/html/thai/net/working-with-html-documents/_index.md index d8de34f36b..5b5a2de00d 100644 --- a/html/thai/net/working-with-html-documents/_index.md +++ b/html/thai/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ url: /th/net/working-with-html-documents/ ตอนนี้ มาพัฒนาทักษะของคุณไปอีกขั้น การแก้ไขเอกสาร HTML เป็นงานทั่วไปสำหรับนักพัฒนาเว็บ และ Aspose.HTML ช่วยลดความยุ่งยากของกระบวนการนี้ได้อย่างมาก ในส่วนนี้ เราจะพูดถึงการสร้าง การจัดการ และการจัดรูปแบบเอกสาร คุณจะค้นพบวิธีปรับปรุงรูปลักษณ์และฟังก์ชันการทำงานของเนื้อหาเว็บของคุณ ให้ดึงดูดและใช้งานง่าย ### [วิธีบันทึก HTML ใน C# – คู่มือฉบับสมบูรณ์โดยใช้ Custom Resource Handler](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [สร้างตัวจัดการทรัพยากรแบบกำหนดเองใน C# สำหรับการโหลด HTML](./create-custom-resource-handler-in-c-for-html-loading/) + ### [วิธีทำให้หัวเรื่องเป็นตัวหนาด้วย CSS & C# – คู่มือขั้นตอนเต็ม](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) เรียนรู้วิธีทำให้หัวเรื่องเป็นตัวหนาด้วย CSS ใน C# อย่างละเอียด พร้อมขั้นตอนครบถ้วนเพื่อปรับปรุงการออกแบบเว็บของคุณ diff --git a/html/thai/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/thai/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..7c345d6ca1 --- /dev/null +++ b/html/thai/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-08-15 +description: สร้างตัวจัดการทรัพยากรแบบกำหนดเองใน C# เพื่อจัดการทรัพยากร HTML เช่น + รูปภาพและ CSS เรียนรู้ HTMLLoadOptions, memory streams, และการโหลด HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: th +lastmod: 2026-08-15 +og_description: สร้างตัวจัดการทรัพยากรแบบกำหนดเองใน C# เพื่อควบคุมการสตรีมทรัพยากร + HTML บทเรียนนี้แสดงการตั้งค่า HTMLLoadOptions การจัดการ Memory Stream และการโหลด + HTMLDocument ด้วยตรรกะแบบกำหนดเอง +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: สร้างตัวจัดการทรัพยากรแบบกำหนดเองใน C# – คู่มือเต็มสำหรับการจัดการทรัพยากร + HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: สร้างตัวจัดการทรัพยากรแบบกำหนดเองใน C# สำหรับการโหลด HTML +url: /th/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างตัวจัดการทรัพยากรแบบกำหนดเองใน C# สำหรับการโหลด HTML + +หากคุณต้องการ **create custom resource handler** สำหรับไฟล์ HTML คำแนะนำนี้จะแสดงให้คุณเห็นอย่างละเอียด คุณจะได้เรียนรู้การดักจับรูปภาพ, CSS, และทรัพยากรอื่น ๆ ขณะโหลดเอกสาร HTML โดยใช้ `HTMLLoadOptions` และสตรีมที่อยู่ในหน่วยความจำ + +บทแนะนำนี้ครอบคลุมทุกอย่างที่จำเป็นสำหรับการสร้างตัวจัดการที่ใช้ซ้ำได้, การกำหนดค่า load options, และการตรวจสอบว่าทรัพยากรถูกจับได้อย่างถูกต้อง ไม่ต้องอ้างอิงเอกสารภายนอก—เพียงโค้ดด้านล่างและคำอธิบายเท่านั้น + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า +- ความคุ้นเคยพื้นฐานกับ C# +- การอ้างอิงไลบรารีการประมวลผล HTML ที่ให้ `HTMLDocument`, `HtmlLoadOptions`, และ `ResourceHandler` (เช่น GroupDocs.Viewer for .NET) + +## ภาพรวมของวิธีแก้ + +เราจะทำดังนี้: + +1. **Create a custom resource handler** โดยสืบทอดจาก `ResourceHandler` +2. กำหนดค่า `HTMLLoadOptions` ให้ใช้ตัวจัดการนี้ +3. โหลดไฟล์ HTML ด้วย `HTMLDocument` ขณะตัวจัดการให้สตรีมสำหรับแต่ละทรัพยากร +4. (ทางเลือก) เก็บทรัพยากรที่ได้รับลงดิสก์เพื่อยืนยันผล + +แต่ละขั้นตอนจะมีโค้ดเต็มรูปแบบและเหตุผลที่อยู่เบื้องหลัง + +## ขั้นตอนที่ 1: กำหนดคลาสตัวจัดการทรัพยากรแบบกำหนดเอง + +การสร้างตัวจัดการแบบกำหนดเองหมายถึงการเขียนทับ `HandleResource` เพื่อให้ไลบรารีสามารถเขียนไบต์ของทรัพยากรลงสตรีมที่คุณควบคุมได้ การใช้ `MemoryStream` ทำให้ข้อมูลอยู่ในหน่วยความจำ ซึ่งเหมาะสำหรับการทดสอบหรือการประมวลผลต่อไป + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**ทำไมจึงสำคัญ:** +การเขียนทับ `HandleResource` ให้คุณควบคุมเต็มที่ว่าข้อมูลทรัพยากรจะไปที่ไหน หากภายหลังคุณต้องแคชรูปภาพ, แปลง CSS, หรือบันทึกการใช้ทรัพยากร คุณสามารถเปลี่ยน `MemoryStream` เป็นสตรีมแบบกำหนดเองใด ๆ ก็ได้ + +## ขั้นตอนที่ 2: กำหนดค่า `HTMLLoadOptions` ให้ใช้ตัวจัดการ + +`HTMLLoadOptions` ให้คุณเชื่อมต่อตัวจัดการเข้ากับ pipeline การโหลด การตั้งค่า `ResourceHandler` จะบอก viewer ให้เรียก `MyHandler` สำหรับทุก asset ภายนอก + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**ทำไมจึงสำคัญ:** +หากไม่ได้กำหนด `ResourceHandler` viewer จะเขียนทรัพยากรไปยังตำแหน่งเริ่มต้น (มักเป็นโฟลเดอร์ชั่วคราว) การระบุตัวจัดการของคุณเองทำให้คุณ **create custom resource handler** พฤติกรรมที่สอดคล้องกับกลยุทธ์การจัดเก็บของแอปพลิเคชัน + +## ขั้นตอนที่ 3: โหลดเอกสาร HTML ด้วยตัวเลือกที่กำหนดค่าแล้ว + +ตอนนี้โหลดไฟล์ HTML ตัว viewer จะเรียก `MyHandler.HandleResource` สำหรับแต่ละทรัพยากรที่พบ + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +ในขั้นตอนนี้เนื้อหา HTML ถูกพาร์สและทรัพยากรภายนอกทั้งหมดถูกสตรีมเข้าสู่บัฟเฟอร์หน่วยความจำที่ `MyHandler` จัดหาให้ + +## ขั้นตอนที่ 4 (ทางเลือก): เข้าถึงทรัพยากรที่จับได้ + +หากต้องการตรวจสอบหรือบันทึกทรัพยากร คุณสามารถแก้ไข `MyHandler` ให้เก็บ `MemoryStream` แต่ละอันในดิกชันนารีโดยใช้ชื่อทรัพยากรเป็นคีย์ + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +หลังจากโหลดเสร็จ คุณสามารถวนลูป `handler.Resources` และเขียนแต่ละไฟล์ลงดิสก์ได้: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**ทำไมจึงสำคัญ:** +การเก็บทรัพยากรช่วยให้ทำการประมวลผลต่อ เช่น การเพิ่มประสิทธิภาพรูปภาพ, การย่อ CSS, หรือการเก็บสำรอง นอกจากนี้ยังเป็นการยืนยันอย่างเป็นรูปธรรมว่า logic **create custom resource handler** ทำงานตามที่คาดหวัง + +## ขั้นตอนที่ 5: ทำความสะอาด + +ทั้ง `HTMLDocument` และสตรีมใด ๆ ควรทำการ dispose เพื่อปล่อยทรัพยากรที่ไม่ได้จัดการ + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## ตัวอย่างเต็มที่สามารถรันได้ + +ด้านล่างเป็นโปรแกรมที่รวมทุกขั้นตอนตั้งแต่การกำหนดคลาสจนถึงการสกัดทรัพยากร + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**ผลลัพธ์ที่คาดหวัง** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +คอนโซลจะแสดงรายการทรัพยากรแต่ละรายการที่ viewer สตรีมผ่านตัวจัดการของคุณ ยืนยันว่า workflow **create custom resource handler** สำเร็จ + +## คำถามที่พบบ่อยและกรณีขอบ + +| Question | Answer | +|----------|--------| +| *What if a resource is large (e.g., high‑resolution image)?* | แทนที่ `MemoryStream` ด้วย `FileStream` ที่ชี้ไปยังโฟลเดอร์ชั่วคราว เพื่อป้องกันการใช้หน่วยความจำมากเกินไป | +| *Can I filter resources by type?* | ภายใน `HandleResource` ตรวจสอบ `info.MimeType` หรือ `info.Extension` แล้วคืนค่า `null` สำหรับประเภทที่ไม่ต้องการ การคืนค่า `null` จะบอก viewer ให้ข้ามทรัพยากรนั้น | +| *Is thread safety required?* | หากใช้ instance ของตัวจัดการเดียวกันในหลายการโหลดพร้อมกัน ควรปกป้องดิกชันนารี `Resources` ด้วย lock หรือใช้คอลเลกชันแบบ concurrent | +| *How do I support relative URLs?* | `ResourceInfo` มี URL ดั้งเดิม คุณสามารถผสานกับ base path ของไฟล์ HTML เพื่อแก้ไข URL แบบ relative ก่อนบันทึก | + +## สรุป + +คุณได้เรียนรู้วิธี **create custom resource handler** ใน C# สำหรับการโหลด HTML, การกำหนดค่า `HTMLLoadOptions`, การจับทรัพยากรที่สตรีม, และการทำความสะอาดอย่างรับผิดชอบ รูปแบบนี้ให้คุณควบคุมการจัดการทรัพยากรได้เต็มที่ รองรับสถานการณ์เช่น การประมวลผลรูปภาพแบบเรียลไทม์, การเขียนทับ CSS, หรือการจัดเก็บอย่างปลอดภัย + +ต่อไปให้สำรวจหัวข้อที่เกี่ยวข้องเช่น **HTMLDocument loading** ด้วยตัวเลือกการเรนเดอร์ต่าง ๆ, หรือขยายตัวจัดการให้เป็น **C# resource handler** ที่เขียนโดยตรงไปยังคลาวด์สตอเรจ ทดลองใช้เมธอด `HandleResource` ของตัวจัดการเพื่อให้ตรงกับ workflow ของโครงการของคุณ + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานแบบอื่นในโปรเจกต์ของคุณ + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/turkish/net/advanced-features/_index.md b/html/turkish/net/advanced-features/_index.md index 921bb6ad11..35524d16fa 100644 --- a/html/turkish/net/advanced-features/_index.md +++ b/html/turkish/net/advanced-features/_index.md @@ -44,7 +44,9 @@ Aspose.HTML for .NET ile HTML'yi PDF, XPS ve resimlere nasıl dönüştüreceği ### [Aspose.HTML ile .NET'te HTML Şablonlarını Kullanma](./using-html-templates/) JSON verilerinden HTML belgelerini dinamik olarak oluşturmak için Aspose.HTML for .NET'i nasıl kullanacağınızı öğrenin. .NET uygulamalarınızda HTML manipülasyonunun gücünden yararlanın. ### [C# ile Programlı Olarak Yazı Tiplerini Birleştirme – Adım Adım Kılavuz](./how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) -C# kullanarak yazı tiplerini programlı şekilde birleştirmenin adımlarını öğrenin ve dinamik PDF/HTML çıktıları oluşturun. + +### [C#'ta kalın ve italik yazı tipi oluşturma – adım adım kılavuz](./create-bold-italic-font-in-c-step-by-step-guide/) +C# kullanarak kalın ve italik yazı tiplerini programlı şekilde oluşturmanın adımlarını öğrenin. ## Çözüm diff --git a/html/turkish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/turkish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..f2bb031d86 --- /dev/null +++ b/html/turkish/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-08-15 +description: C#'ta kalın ve italik yazı tipini hızlıca oluşturun. Yerleşik Font sınıfını + kullanarak C#'ta kalın ve italik stillerle yazı tipi oluşturmayı öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: tr +lastmod: 2026-08-15 +og_description: C#'ta kalın italik bir yazı tipi oluşturun, net bir örnekle. Bu öğretici, + FontStyle bayraklarını kullanarak C#'ta yazı tipi oluşturmayı gösterir ve yaygın + hataları açıklar. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: C#'ta kalın italik yazı tipi oluşturma – tam kodlama rehberi +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: C#'ta kalın italik yazı tipi oluşturma – adım adım rehber +url: /tr/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta kalın italik yazı tipi oluşturma – adım adım kılavuz + +C#'ta **kalın italik yazı tipi oluşturmanız** gerekiyorsa, bu kılavuz tam olarak nasıl yapılacağını gösterir. Standart .NET `Font` sınıfını kullanarak **C#'ta yazı tipi oluşturma** nasıl yapılır gösteren tam, çalıştırılabilir bir örnek göreceksiniz. + +Özel yazı tipleriyle çalışmak, Windows masaüstü uygulamaları oluştururken, PDF üretirken veya sunucuda HTML render ederken rutin bir parçadır. Bu öğreticinin sonunda hem kalın hem de italik bir yazı tipini örnekleyebilecek, bit düzeyinde `|` operatörünün neden kullanıldığını anlayacak ve eksik yazı tipi aileleri gibi yaygın kenar durumlarını ele alabileceksiniz. + +## Öğrenecekleriniz + +* Yazı tipi işleme için gerekli ad alanlarını nasıl içe aktaracağınızı öğrenin. +* `FontStyle.Bold` ve `FontStyle.Italic` birleştirme sözdizimini öğrenin. +* Yazı tipinin başarıyla oluşturulup oluşturulmadığını nasıl doğrulayacağınızı öğrenin. +* İstenen aile yüklü olmadığında geri dönüş (fallback) işlemlerine dair ipuçları. + +Harici kütüphane gerekmez—her şey .NET Framework / .NET Core temel sınıf kitaplığını kullanır. + +## Önkoşullar + +* .NET 6.0 SDK veya daha yeni bir sürüm (kod .NET Framework 4.6+ üzerinde de çalışır). +* Bir kod editörü veya IDE (Visual Studio, VS Code, Rider vb.). +* C# sözdizimine temel aşinalık. + +Eğer bu önkoşulları karşılıyorsanız, ek bir kurulum yapmadan adımları izleyebilirsiniz. + +## Adım 1: Gerekli using yönergelerini ekleyin + +`Font` sınıfı `System.Drawing` ad alanında bulunur; bu, .NET Core/.NET 5+ için `System.Drawing.Common` NuGet paketinin bir parçasıdır. Dosyanızın en üstüne bu ad alanını ekleyin: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Bu adımın önemi** – `using System.Drawing;` satırı olmadan derleyici `Font` veya `FontStyle`'ı bulamaz ve “type or namespace name could not be found” hatası verir. + +## Adım 2: Kalın ve italik stilleri bit düzeyinde OR operatörüyle birleştirin + +.NET'te `FontStyle`, `[Flags]` niteliğiyle işaretlenmiş bir enum'dur. Bu, birden fazla değeri `|` (bit düzeyinde OR) operatörüyle birleştirebileceğiniz anlamına gelir: + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Açıklama + +* `"Arial"` – yazı tipi ailesi adı. Sistem Arial yüklü değilse, yapıcı varsayılan yazı tipine geri döner. +* `12` – punto büyüklüğü. +* `FontStyle.Bold | FontStyle.Italic` – iki stil bayrağını birleştirir. `|` operatörü her bayrağın ikili temsilini birleştirerek “kalın + italik” anlamına gelen tek bir değer üretir. + +> **Pro ipucu:** Her zaman sihirli sayılar yerine enum adlarını (`FontStyle.Bold`) kullanın; bu okunabilirliği artırır ve enum değerleri değiştiğinde hataları önler. + +## Adım 3: Oluşturulan yazı tipini doğrulayın (isteğe bağlı ancak önerilir) + +Yazı tipinin özelliklerini yazdırmak, stil kombinasyonunun başarılı olduğunu doğrulamanıza yardımcı olur, özellikle yeni bir makinede hata ayıklarken. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Beklenen çıktı** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Eğer çıktı hem `Bold` hem de `Italic` değerlerini listeliyorsa, yazı tipi doğru oluşturulmuş demektir. + +## Adım 4: Örnek bir dize render edin (görsel doğrulama) + +Bir konsol uygulaması çalıştırdığınızda gerçek glif stilini göremezsiniz, ancak sonucu kanıtlamak için bir görüntü oluşturabilirsiniz. Aşağıdaki kod parçacığı, kalın‑italik yazı tipini kullanarak “Hello, World!” çizer ve *sample.png* olarak kaydeder: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Program çalıştıktan sonra, kalın italik stilinde render edilen metni görmek için *sample.png* dosyasını açın. + +![Bold italic font ile render edilen örnek metin](sample.png) + +*Görsel alt metni: C# konsol penceresinde kalın italik Arial yazı tipiyle render edilen metnin ekran görüntüsü* – bu alt metin, görsel alt metin SEO gereksinimini karşılar. + +## Adım 5: Yazı tipi ailesi mevcut olmadığında nazik geri dönüş + +İstenen aile (ör. “Arial”) yüklü değilse, `Font` yapıcı `ArgumentException` fırlatır. Oluşturmayı bir `try/catch` bloğuna sarın ve “Segoe UI” gibi bilinen güvenli bir yazı tipine geri dönün. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Neden ele alınmalı?** Konteynerleştirilmiş veya başsız (headless) ortamlarda varsayılan yazı tipi seti tipik bir masaüstünden farklı olabilir. Bir geri dönüş sağlamak, çalışma zamanı çöküşlerini önler ve tutarlı stil garantiler. + +## Tam, çalıştırılabilir örnek + +Her şeyi bir araya getirerek, kopyalayıp yapıştırıp çalıştırabileceğiniz tam bir program aşağıdadır: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### Nasıl çalıştırılır + +1. Kodu `Program.cs` adlı bir dosyaya kaydedin. +2. Dosyanın bulunduğu dizinde bir terminal açın. +3. `dotnet new console -n FontDemo` komutunu çalıştırın (eğer bir proje iskeleti gerekiyorsa). +4. Oluşturulan `Program.cs` dosyasını yukarıdaki kodla değiştirin. +5. `dotnet add package System.Drawing.Common` komutunu çalıştırın (.NET Core/5+ için gereklidir). +6. `dotnet run` ile derleyin ve çalıştırın. + +Konsol çıktısında yazı tipi özelliklerinin onaylandığını göreceksiniz ve `sample.png` proje klasöründe görünecek. + +## Yaygın tuzaklar ve nasıl önlenir + +| Tuzak | Neden olur | Çözüm | +|---------|----------------|-----| +| **`System.Drawing.Common` paketinin eksik olması** | .NET Core varsayılan olarak `System.Drawing` içermez. | `dotnet add package System.Drawing.Common` komutunu çalıştırın. | +| **Yazı tipi ailesi yüklü değil** | Başsız Docker görüntüleri genellikle Windows yazı tiplerine sahip değildir. | Bir geri dönüş yazı tipi kullanın veya gerekli yazı tiplerini konteyner içinde kurun. | +| **`|` yanlış kullanımı** | `+` kullanmak geçersiz bir kombinasyona yol açar. | `FontStyle` değerlerini her zaman bit düzeyinde OR operatörü (`|`) ile birleştirin. | +| **`Font` nesnesini dispose etmemek** | `Dispose` çağrılmadığında GDI kaynakları sızabilir. | `Font` nesnesini bir `using` bloğuna alın veya işiniz bittiğinde `font.Dispose()` çağırın. | + +## Sonuç + +Artık C#'ta **kalın italik yazı tipi oluşturmayı** ve **C#'ta yazı tipi oluşturmayı** güvenli ve verimli bir şekilde nasıl yapacağınızı biliyorsunuz. Eğitim, doğru ad alanını içe aktarmayı, `FontStyle` bayraklarını birleştirmeyi, sonucu doğrulamayı, görsel bir örnek render etmeyi ve eksik yazı tipi ailelerini ele almayı kapsadı. + +Sonraki adımda şunları keşfedebilirsiniz: + +* **Altı çizili veya üstü çizili yazı tipleri oluşturma** – `FontStyle.Underline` veya `FontStyle.Strikeout` ekleyin. +* **Özel TrueType yazı tipleri kullanma** – `.ttf` dosyasını `PrivateFontCollection` ile yükleyin. +* **WinForms, WPF veya PDF oluşturma içinde yazı tiplerini uygulama** – aynı `Font` nesnesi UI kontrollerine veya üçüncü‑taraf kütüphanelere aktarılabilir. + +Farklı aileler, boyutlar ve stil kombinasyonlarıyla denemeler yapmaktan çekinmeyin. Sorunla karşılaşırsanız, “Yaygın tuzaklar” tablosuna tekrar bakın veya resmi [.NET System.Drawing.Font belgelerine](https://learn.microsoft.com/dotnet/api/system.drawing.font) göz atın. Kodlamanın tadını çıkarın! + +## Sonra Ne Öğrenmelisiniz? + +- [C#'ta Programatik Olarak Fontları Birleştirme – Adım Adım Kılavuz](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Stilize Metinli HTML Belgesi Oluşturma ve PDF'ye Dışa Aktarma – Tam Kılavuz](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [docx'i png'ye dönüştür – zip arşivi oluşturma c# öğreticisi](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/turkish/net/working-with-html-documents/_index.md b/html/turkish/net/working-with-html-documents/_index.md index 1aee408b6b..dca3d74e65 100644 --- a/html/turkish/net/working-with-html-documents/_index.md +++ b/html/turkish/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ Temelleri kavradığınızda, oluşturma sürecine daha derinlemesine dalacağı ### [C#'ta HTML Kaydetme – Özel Kaynak İşleyicisi Kullanarak Tam Kılavuz](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [CSS ve C# ile Başlığı Kalınlaştırma – Tam Adım Adım Kılavuz](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [C#'ta HTML Yükleme İçin Özel Kaynak İşleyicisi Oluşturma](./create-custom-resource-handler-in-c-for-html-loading/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/turkish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..ad3f1373b5 --- /dev/null +++ b/html/turkish/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-08-15 +description: C#'ta resim ve CSS gibi HTML kaynaklarını yönetmek için özel kaynak işleyicisi + oluşturun. HTMLLoadOptions, bellek akışları ve HTMLDocument yüklemeyi öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: tr +lastmod: 2026-08-15 +og_description: C#'ta HTML kaynaklarının akışını kontrol etmek için özel kaynak işleyicisi + oluşturun. Bu öğreticide HTMLLoadOptions ayarı, bellek akışı işleme ve özel mantıkla + HTMLDocument yükleme gösterilmektedir. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: C#'ta Özel Kaynak İşleyicisi Oluşturma – HTML Kaynak Yönetimi İçin Tam Kılavuz +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: HTML yükleme için C#'ta özel kaynak işleyicisi oluştur +url: /tr/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML yükleme için C#'ta özel kaynak işleyicisi oluşturma + +HTML dosyaları için **özel kaynak işleyicisi oluşturmanız** gerekiyorsa, bu kılavuz tam olarak nasıl yapılacağını gösterir. `HTMLLoadOptions` ve bellek tabanlı bir akış kullanarak bir HTML belgesi yüklerken görüntüleri, CSS'i ve diğer varlıkları yakalamayı öğreneceksiniz. + +Bu öğretici, yeniden kullanılabilir bir işleyici uygulamak, yükleme seçeneklerini yapılandırmak ve kaynakların doğru şekilde yakalandığını doğrulamak için gereken her şeyi kapsar. Harici bir belgeye gerek yok—yalnızca aşağıdaki kod ve açıklamalar yeterlidir. + +## Önkoşullar + +- .NET 6.0 veya üzeri +- C# hakkında temel bilgi +- `HTMLDocument`, `HtmlLoadOptions` ve `ResourceHandler` sağlayan HTML işleme kütüphanesine referans (ör. GroupDocs.Viewer for .NET) + +## Çözümün Genel Bakışı + +We will: + +1. `ResourceHandler` sınıfını alt sınıf yaparak **özel bir kaynak işleyicisi oluşturma**. +2. `HTMLLoadOptions`'ı işleyiciyi kullanacak şekilde yapılandırma. +3. `HTMLDocument` ile bir HTML dosyasını yükleme; işleyici her kaynak için bir akış sağlar. +4. (İsteğe bağlı) Alınan kaynakları doğrulama amacıyla diske kaydetme. + +Her adım tam kaynak kodu ve bunun arkasındaki mantığı içerir. + +## Adım 1: Özel kaynak işleyici sınıfını tanımlama + +Özel bir işleyici oluşturmak, kütüphanenin kaynak baytlarını kontrol ettiğiniz bir akışa yazabilmesi için `HandleResource` metodunu geçersiz kılmak anlamına gelir. `MemoryStream` kullanmak veriyi bellekte tutar; bu, test veya sonraki işleme için idealdir. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Neden önemlidir:** +`HandleResource`'u geçersiz kılmak, kaynak verilerinin nereye gideceği üzerinde tam kontrol sağlar. Daha sonra görüntüleri önbelleğe almanız, CSS'i dönüştürmeniz veya kaynak kullanımını kaydetmeniz gerekirse, `MemoryStream`'i herhangi bir özel akış uygulamasıyla değiştirebilirsiniz. + +## Adım 2: `HTMLLoadOptions`'ı işleyiciyi kullanacak şekilde yapılandırma + +`HTMLLoadOptions`, işleyiciyi yükleme işlem hattına bağlamanızı sağlar. `ResourceHandler` özelliğini ayarlamak, görüntüleyiciye her dış varlık için `MyHandler`'ı çağırmasını söyler. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Neden önemlidir:** +`ResourceHandler` atanmazsa, görüntüleyici kaynakları varsayılan konumuna (genellikle geçici bir klasör) yazar. Kendi işleyicinizi belirleyerek, uygulamanızın depolama stratejisiyle uyumlu **özel kaynak işleyicisi oluşturma** davranışı elde edersiniz. + +## Adım 3: Yapılandırılmış seçeneklerle HTML belgesini yükleme + +Şimdi HTML dosyasını yükleyin. Görüntüleyici, karşılaştığı her kaynak için `MyHandler.HandleResource` metodunu çağıracaktır. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Bu noktada HTML içeriği ayrıştırılmış ve tüm dış kaynaklar `MyHandler` tarafından sağlanan bellek tamponlarına akıtılmıştır. + +## Adım 4 (isteğe bağlı): Yakalanan kaynaklara erişme + +Kaynakları incelemeniz veya kalıcı hale getirmeniz gerekiyorsa, `MyHandler`'ı her `MemoryStream`'i kaynak adına göre anahtarlanan bir sözlükte saklayacak şekilde değiştirebilirsiniz. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Yükleme sonrasında, `handler.Resources` üzerinde döngü yaparak her birini diske yazabilirsiniz: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Neden önemlidir:** +Kaynakları depolamak, görüntü optimizasyonu, CSS küçültme veya arşivleme gibi son‑işlemeleri mümkün kılar. Ayrıca **özel kaynak işleyicisi oluşturma** mantığının amaçlandığı gibi çalıştığını somut bir şekilde doğrular. + +## Adım 5: Temizleme + +`HTMLDocument` ve tüm akışlar, yönetilmeyen kaynakları serbest bırakmak için dispose edilmelidir. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Tam Çalıştırılabilir Örnek + +Aşağıda, sınıf tanımından kaynak çıkarımına kadar tüm adımları gösteren bağımsız bir program bulunmaktadır. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Beklenen çıktı** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Konsol, görüntüleyicinin özel işleyiciniz üzerinden akıttığı her kaynağı listeler ve **özel kaynak işleyicisi oluşturma** iş akışının başarılı olduğunu doğrular. + +## Yaygın sorular ve uç durumlar + +| Soru | Cevap | +|----------|--------| +| *Kaynak büyük olursa (ör. yüksek çözünürlüklü görüntü)?* | `MemoryStream` yerine geçici bir klasöre işaret eden bir `FileStream` kullanın. Bu, aşırı bellek tüketimini önler. | +| *Kaynakları tipe göre filtreleyebilir miyim?* | `HandleResource` içinde `info.MimeType` veya `info.Extension` değerlerini inceleyin ve istenmeyen tipler için `null` döndürün. `null` döndürmek, görüntüleyiciye kaynağı atlamasını söyler. | +| *İş parçacığı güvenliği gerekli mi?* | Aynı işleyici örneği birden çok eşzamanlı yüklemede kullanılıyorsa, `Resources` sözlüğünü bir kilit ile koruyun veya eşzamanlı bir koleksiyon kullanın. | +| *Göreli URL'leri nasıl desteklerim?* | `ResourceInfo` orijinal URL'yi içerir; depolamadan önce göreli referansları çözmek için bunu HTML dosyasının temel yolu ile birleştirebilirsiniz. | + +## Sonuç + +Artık C#'ta HTML yükleme için **özel kaynak işleyicisi oluşturma**, `HTMLLoadOptions` yapılandırma, akıtılan varlıkları yakalama ve sorumlu bir şekilde temizleme konularını biliyorsunuz. Bu desen, kaynak yönetimi üzerinde tam kontrol sağlar; anlık görüntü işleme, CSS yeniden yazma veya güvenli depolama gibi senaryoları mümkün kılar. + +Sonra, farklı render seçenekleriyle **HTMLDocument yükleme** gibi ilgili konuları keşfedin veya işleyiciyi doğrudan bulut depolamaya yazan **C# resource handler** uygulamalarına genişletin. İşleyicinin `HandleResource` metoduyla projenizin özel kaynak iş akışına uyacak şekilde deneyler yapın. + +## Bir Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan yakından ilgili konuları kapsar. Her kaynak, adım adım açıklamalarla tam çalışan kod örnekleri içerir ve ek API özelliklerini öğrenmenize ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olur. + +- [C#'ta Dizeden HTML Oluşturma – Özel Kaynak İşleyici Kılavuzu](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [C#'ta Özel Kaynak İşleyici – HTML'yi ZIP'e Dönüştürme Öğreticisi](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [C#'ta HTML Kaydetme – Özel Kaynak İşleyicisi Kullanarak Tam Kılavuz](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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/html/vietnamese/net/advanced-features/_index.md b/html/vietnamese/net/advanced-features/_index.md index 5551ea5944..f4718347fe 100644 --- a/html/vietnamese/net/advanced-features/_index.md +++ b/html/vietnamese/net/advanced-features/_index.md @@ -44,7 +44,8 @@ Tìm hiểu cách chuyển đổi HTML sang PDF, XPS và hình ảnh bằng Aspo Tìm hiểu cách sử dụng Aspose.HTML cho .NET để tạo tài liệu HTML động từ dữ liệu JSON. Khai thác sức mạnh của thao tác HTML trong các ứng dụng .NET của bạn. ### [Tạo memory stream C# – Hướng dẫn tạo luồng tùy chỉnh](./create-memory-stream-c-custom-stream-creation-guide/) Hướng dẫn chi tiết cách tạo memory stream trong C# bằng Aspose.HTML, bao gồm các bước thực hiện và ví dụ thực tế. - +### [Tạo phông chữ in đậm nghiêng trong C# – hướng dẫn từng bước](./create-bold-italic-font-in-c-step-by-step-guide/) +Hướng dẫn chi tiết cách tạo phông chữ in đậm và nghiêng trong C# bằng Aspose.HTML, bao gồm các bước thực hiện và ví dụ thực tế. ## Phần kết luận diff --git a/html/vietnamese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md b/html/vietnamese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md new file mode 100644 index 0000000000..812faec8c3 --- /dev/null +++ b/html/vietnamese/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-08-15 +description: Tạo phông chữ in đậm và nghiêng trong C# nhanh chóng. Tìm hiểu cách tạo + phông chữ trong C# với kiểu in đậm và nghiêng bằng lớp Font có sẵn. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create bold italic font +- create font in c# +- C# FontStyle +- text styling C# +- System.Drawing.Font +language: vi +lastmod: 2026-08-15 +og_description: Tạo phông chữ in đậm nghiêng trong C# với ví dụ rõ ràng. Hướng dẫn + này cho thấy cách tạo phông chữ trong C# bằng cách sử dụng các cờ FontStyle và giải + thích các lỗi thường gặp. +og_image_alt: Screenshot of text rendered with a bold italic Arial font in a C# console + window +og_title: Tạo phông chữ in đậm nghiêng trong C# – hướng dẫn lập trình đầy đủ +schemas: +- author: Aspose + dateModified: '2026-08-15' + description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + headline: Create bold italic font in C# – step‑by‑step guide + type: TechArticle +- description: Create bold italic font in C# quickly. Learn how to create font in + C# with bold and italic styles using the built‑in Font class. + name: Create bold italic font in C# – step‑by‑step guide + steps: + - name: Save the code to a file named `Program.cs`. + text: Save the code to a file named `Program.cs`. + - name: Open a terminal in the file’s directory. + text: Open a terminal in the file’s directory. + - name: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + text: Execute `dotnet new console -n FontDemo` (if you need a project scaffold). + - name: Replace the generated `Program.cs` with the code above. + text: Replace the generated `Program.cs` with the code above. + - name: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + text: Run `dotnet add package System.Drawing.Common` (required for .NET Core/5+). + - name: Build and run with `dotnet run`. + text: Build and run with `dotnet run`. + type: HowTo +tags: +- C# +- fonts +- text styling +title: Tạo phông chữ in đậm và nghiêng trong C# – hướng dẫn từng bước +url: /vi/net/advanced-features/create-bold-italic-font-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo phông chữ in đậm nghiêng trong C# – hướng dẫn từng bước + +Nếu bạn cần **tạo phông chữ in đậm nghiêng** trong C#, hướng dẫn này sẽ chỉ cho bạn cách thực hiện chính xác. Bạn sẽ thấy một ví dụ đầy đủ, có thể chạy được, đồng thời minh họa cách **tạo phông chữ trong C#** bằng lớp `Font` chuẩn của .NET. + +Làm việc với các phông chữ tùy chỉnh là một phần thường xuyên khi xây dựng ứng dụng desktop Windows, tạo PDF, hoặc render HTML trên máy chủ. Khi kết thúc tutorial này, bạn sẽ có khả năng khởi tạo một phông chữ vừa in đậm vừa nghiêng, hiểu vì sao lại dùng toán tử bitwise `|`, và xử lý các trường hợp phổ biến như thiếu họ phông chữ. + +## Những gì bạn sẽ học + +* Cách nhập các namespace cần thiết để xử lý phông chữ. +* Cú pháp để kết hợp `FontStyle.Bold` và `FontStyle.Italic`. +* Cách xác minh rằng phông chữ đã được tạo thành công. +* Mẹo xử lý dự phòng khi họ font được yêu cầu không được cài đặt. + +Không cần thư viện bên ngoài—tất cả đều sử dụng .NET Framework / .NET Core base class library. + +## Yêu cầu trước + +* .NET 6.0 SDK hoặc mới hơn (code cũng hoạt động trên .NET Framework 4.6+). +* Một trình soạn thảo mã hoặc IDE (Visual Studio, VS Code, Rider, v.v.). +* Kiến thức cơ bản về cú pháp C#. + +Nếu bạn đáp ứng các yêu cầu này, bạn có thể làm theo các bước mà không cần thiết lập thêm. + +## Step 1: Add the necessary using directives + +Lớp `Font` nằm trong namespace `System.Drawing`, là một phần của gói NuGet `System.Drawing.Common` cho .NET Core/.NET 5+. Thêm namespace này ở đầu tệp của bạn: + +```csharp +using System; +using System.Drawing; // Provides Font and FontStyle +``` + +> **Tại sao bước này quan trọng** – Nếu không có dòng `using System.Drawing;` trình biên dịch sẽ không tìm thấy `Font` hoặc `FontStyle`, gây ra lỗi “type or namespace name could not be found”. + +## Step 2: Combine bold and italic styles with the bitwise OR operator + +Trong .NET, `FontStyle` là một enum được đánh dấu bằng thuộc tính `[Flags]`. Điều này cho phép bạn kết hợp nhiều giá trị bằng toán tử `|` (bitwise OR): + +```csharp +// Step 2: Create a Font that is both bold and italic +var font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +``` + +### Explanation + +* `"Arial"` – tên họ font. Nếu hệ thống không có Arial được cài đặt, hàm khởi tạo sẽ quay lại font mặc định. +* `12` – kích thước điểm. +* `FontStyle.Bold | FontStyle.Italic` – kết hợp hai cờ style. Toán tử `|` hợp nhất biểu diễn nhị phân của mỗi cờ, tạo ra một giá trị duy nhất đại diện cho “đậm + nghiêng”. + +> **Mẹo chuyên nghiệp:** Luôn sử dụng tên enum (`FontStyle.Bold`) thay vì các số ma thuật; cách này cải thiện khả năng đọc và ngăn ngừa lỗi khi giá trị enum thay đổi. + +## Step 3: Verify the created font (optional but recommended) + +In ra các thuộc tính của phông chữ giúp bạn xác nhận rằng việc kết hợp style đã thành công, đặc biệt khi debug trên máy mới. + +```csharp +// Step 3: Output the font details to the console +Console.WriteLine($"Font family: {font.Name}"); +Console.WriteLine($"Size (pt): {font.Size}"); +Console.WriteLine($"Style: {font.Style}"); +``` + +**Kết quả mong đợi** + +``` +Font family: Arial +Size (pt): 12 +Style: Bold, Italic +``` + +Nếu kết quả liệt kê cả `Bold` và `Italic`, phông chữ đã được tạo đúng. + +## Step 4: Render a sample string (visual confirmation) + +Khi chạy một ứng dụng console, bạn không thể thấy kiểu glyph thực tế, nhưng có thể tạo một hình ảnh để chứng minh kết quả. Đoạn mã dưới đây vẽ “Hello, World!” bằng phông chữ in đậm‑nghiêng và lưu dưới dạng *sample.png*: + +```csharp +// Step 4: Draw text to an image file for visual confirmation +using (var bitmap = new Bitmap(300, 100)) +using (var graphics = Graphics.FromImage(bitmap)) +{ + graphics.Clear(Color.White); + var brush = Brushes.Black; + graphics.DrawString("Hello, World!", font, brush, new PointF(10, 30)); + bitmap.Save("sample.png"); + Console.WriteLine("Image saved as sample.png"); +} +``` + +Sau khi chương trình chạy, mở *sample.png* để xem văn bản được render với style in đậm nghiêng. + +![Văn bản mẫu được hiển thị với phông chữ in đậm nghiêng](sample.png) + +*Văn bản thay thế hình ảnh: Ảnh chụp màn hình văn bản được hiển thị với phông chữ Arial in đậm nghiêng trong cửa sổ console C#* – văn bản thay thế này đáp ứng yêu cầu SEO cho văn bản thay thế hình ảnh. + +## Step 5: Graceful fallback when the font family is unavailable + +Nếu họ font được yêu cầu (ví dụ, “Arial”) không được cài đặt, hàm khởi tạo `Font` sẽ ném `ArgumentException`. Bao việc tạo trong khối `try/catch` và dùng một phông chữ an toàn đã biết như “Segoe UI”. + +```csharp +Font font; +try +{ + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); +} +catch (ArgumentException) +{ + Console.WriteLine("Arial not found – falling back to Segoe UI."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); +} +``` + +**Tại sao cần xử lý điều này?** Trong môi trường container hoặc headless, bộ phông chữ mặc định có thể khác so với máy tính để bàn thông thường. Cung cấp dự phòng ngăn ngừa lỗi runtime và đảm bảo kiểu dáng nhất quán. + +## Full, runnable example + +Kết hợp mọi thứ lại, đây là một chương trình hoàn chỉnh mà bạn có thể sao chép, dán và chạy: + +```csharp +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Create the font (bold + italic) + Font font; + try + { + font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); + } + catch (ArgumentException) + { + Console.WriteLine("Arial not found – using Segoe UI as fallback."); + font = new Font("Segoe UI", 12, FontStyle.Bold | FontStyle.Italic); + } + + // Display font information + Console.WriteLine($"Font family: {font.Name}"); + Console.WriteLine($"Size (pt): {font.Size}"); + Console.WriteLine($"Style: {font.Style}"); + + // Render a sample image + using (var bitmap = new Bitmap(300, 100)) + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(10, 30)); + bitmap.Save("sample.png"); + } + + Console.WriteLine("Sample image saved as sample.png"); + } +} +``` + +### How to run + +1. Lưu mã vào tệp có tên `Program.cs`. +2. Mở terminal trong thư mục chứa tệp. +3. Chạy `dotnet new console -n FontDemo` (nếu bạn cần khung dự án). +4. Thay thế `Program.cs` được tạo ra bằng mã ở trên. +5. Chạy `dotnet add package System.Drawing.Common` (cần thiết cho .NET Core/5+). +6. Biên dịch và chạy bằng `dotnet run`. + +Bạn sẽ thấy đầu ra console xác nhận các thuộc tính của phông chữ, và `sample.png` sẽ xuất hiện trong thư mục dự án. + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| **Thiếu gói `System.Drawing.Common`** | .NET Core không bao gồm `System.Drawing` theo mặc định. | Chạy `dotnet add package System.Drawing.Common`. | +| **Họ font không được cài đặt** | Các image Docker không giao diện thường thiếu các font Windows. | Sử dụng font dự phòng hoặc cài đặt các font cần thiết trong container. | +| **Sử dụng sai `|`** | Sử dụng `+` thay vì `|` sẽ tạo ra sự kết hợp không hợp lệ. | Luôn kết hợp các giá trị `FontStyle` bằng toán tử OR bitwise (`|`). | +| **Không giải phóng đối tượng `Font`** | Không gọi `Dispose` có thể rò rỉ tài nguyên GDI. | Bao `Font` trong khối `using` hoặc gọi `font.Dispose()` sau khi sử dụng. | + +## Conclusion + +Bạn giờ đã biết cách **tạo phông chữ in đậm nghiêng** trong C# và cách **tạo phông chữ trong C#** một cách an toàn và hiệu quả. Tutorial đã bao gồm việc nhập namespace đúng, kết hợp các cờ `FontStyle`, xác minh kết quả, render mẫu trực quan, và xử lý trường hợp thiếu họ phông chữ. + +Tiếp theo, bạn có thể khám phá: + +* **Tạo phông chữ gạch chân hoặc gạch ngang** – thêm `FontStyle.Underline` hoặc `FontStyle.Strikeout`. +* **Sử dụng phông chữ TrueType tùy chỉnh** – tải tệp `.ttf` bằng `PrivateFontCollection`. +* **Áp dụng phông chữ trong WinForms, WPF hoặc tạo PDF** – đối tượng `Font` giống nhau có thể được truyền cho các điều khiển UI hoặc thư viện bên thứ ba. + +Hãy thoải mái thử nghiệm với các họ, kích thước và kết hợp style khác nhau. Nếu gặp vấn đề, hãy xem lại bảng “Common pitfalls” hoặc kiểm tra tài liệu chính thức [.NET documentation for System.Drawing.Font](https://learn.microsoft.com/dotnet/api/system.drawing.font). Chúc bạn lập trình vui! + +## What Should You Learn Next? + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với 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 kết hợp phông chữ một cách lập trình trong C# – Hướng dẫn từng bước](/html/indonesian/net/advanced-features/how-to-combine-fonts-programmatically-in-c-step-by-step-guid/) +- [Tạo tài liệu HTML với văn bản có kiểu và xuất ra PDF – Hướng dẫn đầy đủ](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [chuyển đổi docx sang png – tạo tệp zip c# hướng dẫn](/html/english/net/generate-jpg-and-png-images/convert-docx-to-png-create-zip-archive-c-tutorial/) + +{{< /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/html/vietnamese/net/working-with-html-documents/_index.md b/html/vietnamese/net/working-with-html-documents/_index.md index ce506e2888..91f25af39f 100644 --- a/html/vietnamese/net/working-with-html-documents/_index.md +++ b/html/vietnamese/net/working-with-html-documents/_index.md @@ -41,6 +41,9 @@ Bây giờ, hãy đưa kỹ năng của bạn lên một tầm cao mới. Chỉn ### [Cách làm tiêu đề đậm bằng CSS & C# – Hướng dẫn chi tiết từng bước](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) Hướng dẫn chi tiết cách sử dụng CSS và C# để làm tiêu đề in đậm, kèm ví dụ mã và các bước thực hiện cụ thể. + +### [Tạo trình xử lý tài nguyên tùy chỉnh trong C# để tải HTML](./create-custom-resource-handler-in-c-for-html-loading/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/vietnamese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md b/html/vietnamese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md new file mode 100644 index 0000000000..589bea702f --- /dev/null +++ b/html/vietnamese/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-08-15 +description: Tạo trình xử lý tài nguyên tùy chỉnh bằng C# để quản lý các tài nguyên + HTML như hình ảnh và CSS. Tìm hiểu HTMLLoadOptions, luồng bộ nhớ và việc tải HTMLDocument. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create custom resource handler +- C# resource handler +- HTMLLoadOptions +- HTMLDocument loading +- memory stream for resources +language: vi +lastmod: 2026-08-15 +og_description: Tạo trình xử lý tài nguyên tùy chỉnh trong C# để kiểm soát cách các + tài nguyên HTML được truyền. Hướng dẫn này trình bày cách thiết lập HTMLLoadOptions, + xử lý luồng bộ nhớ và tải HTMLDocument với logic tùy chỉnh. +og_image_alt: Screenshot of C# code defining a custom resource handler class for HTML + loading +og_title: Tạo trình xử lý tài nguyên tùy chỉnh trong C# – hướng dẫn đầy đủ về quản + lý tài nguyên HTML +schemas: +- author: GroupDocs + dateModified: '2026-08-15' + description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + headline: Create custom resource handler in C# for HTML loading + type: TechArticle +- description: Create custom resource handler in C# to manage HTML resources like + images and CSS. Learn HTMLLoadOptions, memory streams, and HTMLDocument loading. + name: Create custom resource handler in C# for HTML loading + steps: + - name: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + text: '**Create a custom resource handler** by subclassing `ResourceHandler`.' + - name: Configure `HTMLLoadOptions` to use the handler. + text: Configure `HTMLLoadOptions` to use the handler. + - name: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + text: Load an HTML file with `HTMLDocument` while the handler supplies a stream + for each resource. + - name: (Optional) Store received resources to disk for verification. + text: (Optional) Store received resources to disk for verification. + type: HowTo +tags: +- C# +- HTML +- resource handling +title: Tạo trình xử lý tài nguyên tùy chỉnh trong C# để tải HTML +url: /vi/net/working-with-html-documents/create-custom-resource-handler-in-c-for-html-loading/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo bộ xử lý tài nguyên tùy chỉnh trong C# để tải HTML + +Nếu bạn cần **tạo bộ xử lý tài nguyên tùy chỉnh** cho các tệp HTML, hướng dẫn này sẽ chỉ cho bạn cách thực hiện. Bạn sẽ học cách chặn các hình ảnh, CSS và các tài nguyên khác khi tải tài liệu HTML, sử dụng `HTMLLoadOptions` và một luồng dựa trên bộ nhớ. + +Bài học bao gồm mọi thứ cần thiết để triển khai một bộ xử lý có thể tái sử dụng, cấu hình các tùy chọn tải và xác minh rằng các tài nguyên được ghi nhận đúng cách. Không cần tài liệu bên ngoài—chỉ cần đoạn mã dưới đây và các giải thích kèm theo. + +## Yêu cầu trước + +- .NET 6.0 trở lên +- Kiến thức cơ bản về C# +- Tham chiếu tới thư viện xử lý HTML cung cấp `HTMLDocument`, `HtmlLoadOptions` và `ResourceHandler` (ví dụ: GroupDocs.Viewer for .NET) + +## Tổng quan về giải pháp + +Chúng ta sẽ: + +1. **Tạo một bộ xử lý tài nguyên tùy chỉnh** bằng cách kế thừa `ResourceHandler`. +2. Cấu hình `HTMLLoadOptions` để sử dụng bộ xử lý này. +3. Tải tệp HTML bằng `HTMLDocument` trong khi bộ xử lý cung cấp luồng cho mỗi tài nguyên. +4. (Tùy chọn) Lưu các tài nguyên nhận được vào đĩa để kiểm tra. + +Mỗi bước đều kèm theo mã nguồn đầy đủ và lý do thực hiện. + +## Bước 1: Định nghĩa lớp bộ xử lý tài nguyên tùy chỉnh + +Tạo một bộ xử lý tùy chỉnh có nghĩa là ghi đè `HandleResource` để thư viện có thể ghi byte tài nguyên vào một luồng bạn kiểm soát. Việc sử dụng `MemoryStream` giữ dữ liệu trong bộ nhớ, rất thích hợp cho việc thử nghiệm hoặc xử lý tiếp theo. + +```csharp +using System; +using System.IO; +using GroupDocs.Viewer.Handler; // Adjust namespace to match your library + +namespace HtmlResourceDemo +{ + /// + /// Provides a memory stream for each HTML resource (images, CSS, etc.). + /// + public class MyHandler : ResourceHandler + { + /// + /// Called by the viewer for every external resource referenced in the HTML. + /// + /// Information about the resource (name, MIME type, etc.). + /// A writable stream that receives the resource data. + public override Stream HandleResource(ResourceInfo info) + { + // A fresh MemoryStream ensures the viewer can write the resource bytes. + // You could replace this with a FileStream to save directly to disk. + return new MemoryStream(); + } + } +} +``` + +**Tại sao điều này quan trọng:** +Ghi đè `HandleResource` cho phép bạn kiểm soát hoàn toàn nơi dữ liệu tài nguyên được đưa tới. Nếu sau này bạn cần cache hình ảnh, biến đổi CSS, hoặc ghi log việc sử dụng tài nguyên, bạn có thể thay thế `MemoryStream` bằng bất kỳ triển khai luồng tùy chỉnh nào. + +## Bước 2: Cấu hình `HTMLLoadOptions` để sử dụng bộ xử lý + +`HTMLLoadOptions` cho phép bạn gắn bộ xử lý vào quy trình tải. Đặt thuộc tính `ResourceHandler` sẽ khiến viewer gọi `MyHandler` cho mỗi tài nguyên ngoại vi. + +```csharp +using GroupDocs.Viewer.Options; // Namespace for HtmlLoadOptions + +// ... + +var loadOptions = new HtmlLoadOptions +{ + // Attach the custom handler defined in Step 1 + ResourceHandler = new MyHandler() +}; +``` + +**Tại sao điều này quan trọng:** +Nếu không gán `ResourceHandler`, viewer sẽ ghi tài nguyên vào vị trí mặc định (thường là thư mục tạm). Bằng cách chỉ định bộ xử lý của riêng bạn, bạn **tạo bộ xử lý tài nguyên tùy chỉnh** phù hợp với chiến lược lưu trữ của ứng dụng. + +## Bước 3: Tải tài liệu HTML với các tùy chọn đã cấu hình + +Bây giờ tải tệp HTML. Viewer sẽ gọi `MyHandler.HandleResource` cho mỗi tài nguyên mà nó gặp. + +```csharp +using GroupDocs.Viewer; // Namespace for HTMLDocument + +// Path to the source HTML file +string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + +// Load the document using the custom load options +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); +``` + +Tại thời điểm này nội dung HTML đã được phân tích, và tất cả các tài nguyên ngoại vi đã được truyền vào các bộ đệm bộ nhớ do `MyHandler` cung cấp. + +## Bước 4 (tùy chọn): Truy cập các tài nguyên đã ghi nhận + +Nếu bạn cần kiểm tra hoặc lưu trữ các tài nguyên, có thể sửa `MyHandler` để lưu mỗi `MemoryStream` vào một từ điển, khóa bằng tên tài nguyên. + +```csharp +public class MyHandler : ResourceHandler +{ + // Stores streams for later retrieval + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } +} +``` + +Sau khi tải, bạn có thể duyệt `handler.Resources` và ghi mỗi tài nguyên ra đĩa: + +```csharp +var handler = new MyHandler(); +var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; +HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions); + +// Save each captured resource +foreach (var kvp in handler.Resources) +{ + string fileName = Path.Combine("output_resources", kvp.Key); + File.WriteAllBytes(fileName, kvp.Value.ToArray()); + Console.WriteLine($"Saved resource: {fileName}"); +} +``` + +**Tại sao điều này quan trọng:** +Lưu trữ tài nguyên cho phép xử lý hậu kỳ như tối ưu hoá hình ảnh, minify CSS, hoặc lưu trữ. Nó cũng cung cấp bằng chứng cụ thể rằng logic **tạo bộ xử lý tài nguyên tùy chỉnh** hoạt động như mong đợi. + +## Bước 5: Dọn dẹp + +Cả `HTMLDocument` và bất kỳ luồng nào cũng nên được giải phóng để giải phóng tài nguyên không quản lý. + +```csharp +doc.Dispose(); // Releases internal buffers +foreach (var stream in handler.Resources.Values) +{ + stream.Dispose(); // Flushes and releases memory +} +``` + +## Ví dụ đầy đủ có thể chạy được + +Dưới đây là một chương trình tự chứa minh họa tất cả các bước từ định nghĩa lớp đến trích xuất tài nguyên. + +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using GroupDocs.Viewer; +using GroupDocs.Viewer.Handler; +using GroupDocs.Viewer.Options; + +namespace HtmlResourceDemo +{ + public class MyHandler : ResourceHandler + { + public Dictionary Resources { get; } = new(); + + public override Stream HandleResource(ResourceInfo info) + { + var stream = new MemoryStream(); + Resources[info.Name] = stream; + return stream; + } + } + + class Program + { + static void Main() + { + // 1️⃣ Prepare paths + string htmlPath = Path.Combine("YOUR_DIRECTORY", "input.html"); + string outputDir = Path.Combine("output_resources"); + Directory.CreateDirectory(outputDir); + + // 2️⃣ Create handler and load options + var handler = new MyHandler(); + var loadOptions = new HtmlLoadOptions { ResourceHandler = handler }; + + // 3️⃣ Load the HTML document + using (HTMLDocument doc = new HTMLDocument(htmlPath, loadOptions)) + { + // Document is now loaded; resources are in handler.Resources + } + + // 4️⃣ Persist captured resources + foreach (var kvp in handler.Resources) + { + string filePath = Path.Combine(outputDir, kvp.Key); + File.WriteAllBytes(filePath, kvp.Value.ToArray()); + Console.WriteLine($"Saved: {filePath}"); + } + + // 5️⃣ Clean up streams + foreach (var stream in handler.Resources.Values) + stream.Dispose(); + + Console.WriteLine("All resources processed."); + } + } +} +``` + +**Kết quả mong đợi** + +``` +Saved: output_resources/logo.png +Saved: output_resources/styles.css +Saved: output_resources/banner.jpg +All resources processed. +``` + +Bảng điều khiển sẽ liệt kê mỗi tài nguyên mà viewer đã truyền qua bộ xử lý tùy chỉnh của bạn, xác nhận quy trình **tạo bộ xử lý tài nguyên tùy chỉnh** đã thành công. + +## Câu hỏi thường gặp và các trường hợp đặc biệt + +| Câu hỏi | Trả lời | +|----------|--------| +| *Nếu một tài nguyên quá lớn (ví dụ: ảnh độ phân giải cao)?* | Thay `MemoryStream` bằng `FileStream` trỏ tới thư mục tạm. Điều này ngăn việc tiêu thụ bộ nhớ quá mức. | +| *Tôi có thể lọc tài nguyên theo loại không?* | Trong `HandleResource`, kiểm tra `info.MimeType` hoặc `info.Extension` và trả về `null` cho các loại không muốn. Trả về `null` sẽ khiến viewer bỏ qua tài nguyên. | +| *Cần đảm bảo tính an toàn đa luồng không?* | Nếu cùng một thể hiện bộ xử lý được dùng cho nhiều lần tải đồng thời, hãy bảo vệ từ điển `Resources` bằng một lock hoặc dùng collection đồng thời. | +| *Làm sao hỗ trợ URL tương đối?* | `ResourceInfo` chứa URL gốc; bạn có thể kết hợp nó với đường dẫn cơ sở của tệp HTML để giải quyết các tham chiếu tương đối trước khi lưu. | + +## Kết luận + +Bạn đã biết cách **tạo bộ xử lý tài nguyên tùy chỉnh** trong C# để tải HTML, cấu hình `HTMLLoadOptions`, ghi nhận các tài nguyên được truyền luồng, và dọn dẹp một cách có trách nhiệm. Mô hình này cho phép bạn kiểm soát toàn bộ việc quản lý tài nguyên, hỗ trợ các kịch bản như xử lý ảnh ngay lúc tải, viết lại CSS, hoặc lưu trữ an toàn. + +Tiếp theo, khám phá các chủ đề liên quan như **tải HTMLDocument** với các tùy chọn render khác nhau, hoặc mở rộng bộ xử lý để thực hiện **C# resource handler** ghi trực tiếp lên lưu trữ đám mây. Thử nghiệm phương thức `HandleResource` của bộ xử lý để phù hợp với quy trình tài nguyên cụ thể của dự án. + +## Bạn Nên Học Gì Tiếp Theo? + + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong bài viết này. Mỗi tài nguyên đều bao gồm mã mẫu đầy đủ và giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Custom Resource Handler in C# – Convert HTML to ZIP Tutorial](/html/english/net/html-extensions-and-conversions/custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +{{< /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