From f09e56af586a9b513ad8c7a14a8a9f3bf29aa65b Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Thu, 23 Apr 2026 18:52:28 +0000 Subject: [PATCH] Add 3 html net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: generate-jpg-and-png-images, html-document-manipulation, html-extensions-and-conversions Source: AI Search API Tutorials: - how to zip html in C# – custom resource handler guide - Create PNG from HTML – Step‑by‑Step Guide for C# Developers - Apply Font Style Programmatically – Quick C# Guide Auto-generated by Professionalize.Tutorials Agent --- .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 238 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 4 +- .../_index.md | 239 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 245 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 236 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 223 ++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 245 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 4 +- .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 238 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 245 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 3 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 34 +-- .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 238 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 227 ++++++++++++++++ .../html-extensions-and-conversions/_index.md | 3 +- .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 7 +- .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 5 +- .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 236 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 13 + .../_index.md | 237 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 245 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 1 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 +- .../_index.md | 246 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 4 +- .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 246 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 236 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 237 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 + .../_index.md | 245 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 238 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 239 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 +- .../_index.md | 245 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 248 ++++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 229 ++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 246 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 238 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 239 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 246 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 1 + .../_index.md | 241 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/generate-jpg-and-png-images/_index.md | 2 + .../_index.md | 239 +++++++++++++++++ .../net/html-document-manipulation/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 248 ++++++++++++++++++ 138 files changed, 16823 insertions(+), 26 deletions(-) create mode 100644 html/arabic/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/arabic/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/chinese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/chinese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/czech/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/czech/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/dutch/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/dutch/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/english/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/english/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/french/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/french/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/german/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/german/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/greek/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/greek/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/hindi/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/hindi/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/hongkong/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/hongkong/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/hungarian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/hungarian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/indonesian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/indonesian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/italian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/italian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/japanese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/japanese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/korean/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/korean/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/polish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/polish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/portuguese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/portuguese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/russian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/russian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/spanish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/spanish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/swedish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/swedish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/thai/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/thai/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/turkish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/turkish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md create mode 100644 html/vietnamese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md create mode 100644 html/vietnamese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md create mode 100644 html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md diff --git a/html/arabic/net/generate-jpg-and-png-images/_index.md b/html/arabic/net/generate-jpg-and-png-images/_index.md index 432f80cdc..b66fcfd29 100644 --- a/html/arabic/net/generate-jpg-and-png-images/_index.md +++ b/html/arabic/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET هي مكتبة قوية تتيح للمطورين إنشا تعلم كيفية تمكين مضاد التعرج عند تحويل ملفات DOCX إلى صور PNG أو JPG باستخدام Aspose.HTML. ### [تحويل docx إلى png – إنشاء أرشيف zip في C# – دليل تعليمي](./convert-docx-to-png-create-zip-archive-c-tutorial/) تعلم كيفية تحويل ملفات docx إلى صور PNG وإنشاء أرشيف ZIP باستخدام C# و Aspose.HTML. +### [إنشاء PNG من HTML – دليل خطوة بخطوة لمطوري C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +تعلم كيفية تحويل HTML إلى صورة PNG باستخدام Aspose.HTML لـ .NET مع شرح مفصل لكل خطوة للمطورين. ## خاتمة diff --git a/html/arabic/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/arabic/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..e61d0ba60 --- /dev/null +++ b/html/arabic/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-04-23 +description: إنشاء PNG من HTML بسرعة باستخدام Aspose.HTML. تعلّم كيفية تحويل HTML + إلى PNG، وتحديد حجم القماش، وإضافة لون خلفية، وحفظ الصورة المُصدرة في دقائق. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: ar +og_description: إنشاء PNG من HTML باستخدام Aspose.HTML. يوضح هذا الدليل كيفية تحويل + HTML إلى PNG، وتحديد حجم القماش، وإضافة لون خلفية، وحفظ الصورة المُعالجة. +og_title: إنشاء PNG من HTML – دليل كامل لتصيير C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: إنشاء PNG من HTML – دليل خطوة بخطوة لمطوري C# +url: /ar/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء PNG من HTML – دليل شامل لتصوير C# + +هل احتجت يومًا إلى **إنشاء PNG من HTML** لكنك لم تكن متأكدًا أي مكتبة ستعطيك نتائج واضحة ومضادة للتنعيم؟ لست وحدك. في العديد من خطوط تحويل الويب إلى صورة، النقطة الأكثر إزعاجًا هي جعل النص والرسومات تبدو حادة كما هي في المتصفح. + +الخبر السار؟ مع Aspose.HTML يمكنك **render HTML to PNG** في بضع أسطر، التحكم في حجم القماش (canvas)، إضافة لون خلفية صلب، وأخيرًا **save rendered image** إلى القرص—كل ذلك دون الحاجة إلى متصفح. في هذا الدرس سنستعرض العملية بالكامل، نشرح لماذا كل إعداد مهم، ونظهر لك مثالًا جاهزًا للتنفيذ. + +## ما ستتعلمه + +- كيفية تحميل HTML من سلسلة نصية، ملف، أو URL +- كيفية تكوين **set canvas size** و **add background color** للحصول على مخرجات متوقعة +- تمكين مضاد التنعيم وتلميحات النص تحت البكسل للحصول على عناوين حادة للغاية +- الخطوات الدقيقة لـ **save rendered image** كملف PNG +- المشكلات الشائعة وتعديلات اختيارية لسيناريوهات مختلفة + +لا تحتاج إلى أي خبرة سابقة مع Aspose.HTML؛ مجرد إعداد أساسي لـ C# و Visual Studio (أو بيئة التطوير المفضلة لديك). + +--- + +## الخطوة 1: تثبيت Aspose.HTML لـ .NET + +قبل كتابة أي كود، تأكد من أن حزمة NuGet الخاصة بـ Aspose.HTML مُشار إليها في مشروعك. + +```bash +dotnet add package Aspose.HTML +``` + +> **نصيحة احترافية:** استخدم أحدث نسخة مستقرة (اعتبارًا من أبريل 2026، 23.9.0) للحصول على أحدث محرك تصوير وإصلاحات الأخطاء. + +--- + +## الخطوة 2: تحميل مصدر HTML – إنشاء PNG من HTML + +يمكنك إمداد المُصوّر بسلسلة نصية مضمَّنة، ملف محلي، أو URL بعيد. لهذا العرض سنستخدم سلسلة نصية بسيطة تحتوي على عنوان بخط مخصص. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**لماذا هذا مهم:** تحميل HTML إلى `HTMLDocument` يمنح المحرك تحكمًا كاملًا في تحليل DOM، تسلسل CSS، وحسابات التخطيط. كما أنه يعزل عملية التصوير عن أي حالة متصفح خارجية، مما يضمن نتائج قابلة لإعادة الإنتاج. + +--- + +## الخطوة 3: تكوين خيارات التصوير – ضبط حجم القماش وإضافة لون خلفية + +فئة `ImageRenderingOptions` تتيح لك ضبط الصورة الناتجة بدقة. هنا سنفعّل مضاد التنعيم، نحدد خلفية بيضاء، ونعرّف صراحةً قماشًا بحجم **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**لماذا قد تغير هذه القيم:** +- **Canvas size:** إذا كنت تحتاج إلى صورة مصغرة، قلل الأبعاد؛ للطباعة عالية الدقة، زدها. +- **Background color:** يمكن إنشاء PNG شفاف، لكن العديد من الأدوات اللاحقة (مثل PowerPoint) تتوقع خلفية غير شفافة. + +--- + +## الخطوة 4: التصوير و**Save Rendered Image** كـ PNG + +الآن يحدث الجزء الثقيل. `ImageRenderer` يستهلك `HTMLDocument` والخيارات التي حددناها، ثم يكتب تدفق PNG إلى القرص. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +عند تشغيل البرنامج، ستجد `result.png` على سطح المكتب. افتحه، ويجب أن ترى عنوانًا نظيفًا ومضادًا للتنعيم مركَّزًا على قماش أبيض. + +> **الناتج المتوقع:** PNG بحجم 800 × 600 مع خلفية بيضاء والنص “Antialiased Heading” مُصوَّر بخط Arial، يبدو ناعمًا كما هو في Chrome. + +--- + +## الخطوة 5: التحقق من النتيجة – فحوصات سريعة + +1. **وجود الملف:** `File.Exists(outputPath)` يجب أن تُعيد `true`. +2. **الأبعاد:** افتح PNG في أي عارض صور؛ يجب أن يُظهر 800 × 600 px. +3. **جودة الصورة:** قرب إلى 200 % – يجب أن تظل حواف النص ناعمة، لا متعرجة. + +إذا ظهر أي شيء غير صحيح، تحقق مرة أخرى من أن `UseAntialiasing` و `UseHinting` مُعَيَّنَين إلى `true`. هذان الإعدادان هما السر للحصول على تصوير عالي الجودة. + +--- + +## تنوعات شائعة وحالات حافة + +| السيناريو | ما الذي يجب تعديله | السبب | +|----------|-------------------|-------| +| **تصوير صفحة ويب عن بُعد** | استبدل `new HTMLDocument(htmlContent)` بـ `new HTMLDocument("https://example.com")` | يتيح لك التقاط مواقع حية دون نسخ HTML يدويًا. | +| **خلفية شفافة** | عيّن `BackgroundColor = Color.Transparent` واستخدم `ImageFormat.Png` | مفيد لتراكب PNG على رسومات أخرى. | +| **تنسيق صورة مختلف** | غيّر `renderer.Save(pngStream, ImageFormat.Jpeg)` | قد يكون JPEG أصغر للصور الفوتوغرافية، لكنه يفقد الجودة غير الضائعة. | +| **حجم قماش ديناميكي** | استخدم `imgOptions.Width = htmlDoc.Body.ClientWidth;` بعد التخطيط | يجعل الصورة تتطابق مع العرض الطبيعي لمحتوى HTML. | +| **إخراج DPI عالي** | اضرب `Width` و `Height` بمعامل مقياس (مثلاً 2) | يولد أصولًا جاهزة للريتنا للعرض على شاشات حديثة. | + +--- + +## مثال كامل جاهز للنسخ واللصق + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +شغّل البرنامج (`dotnet run` أو اضغط F5 في Visual Studio) وستحصل على PNG مُصوَّر بشكل مثالي جاهز للاستخدام في الرسائل الإلكترونية، التقارير، أو أي مكان تحتاج فيه صورة ثابتة لـ HTML. + +--- + +## الأسئلة المتكررة + +**س: هل يعمل هذا مع ميزات CSS 3 مثل flexbox؟** +ج: نعم. Aspose.HTML يدعم معظم CSS الحديثة، بما في ذلك flexbox، grid، واستعلامات الوسائط. فقط تأكد من أنك تستخدم أحدث نسخة من المكتبة. + +**س: ماذا لو كان HTML الخاص بي ي引用 صورًا خارجية؟** +ج: المُصوّر يتبع عناوين URL النسبية بناءً على URI الأساسي للمستند. إذا حمّلت HTML من سلسلة نصية، عيّن `doc.BaseUrl` إلى المجلد الذي يحتوي على الأصول. + +**س: هل يمكنني تصوير صفحات متعددة في PNG واحد؟** +ج: ليس مباشرة—كل استدعاء لـ `ImageRenderer` ينتج صورة نقطية واحدة. للحصول على إخراج متعدد الصفحات، صوّر كل صفحة على حدة ثم اجمعها باستخدام مكتبة رسومات (مثل ImageSharp). + +--- + +## الخلاصة + +أصبح لديك الآن حل شامل من البداية إلى النهاية **إنشاء PNG من HTML** باستخدام Aspose.HTML. من خلال تكوين خيارات **render html to png**—مثل **set canvas size**، **add background color**، وتفعيل مضاد التنعيم—يمكنك توليد صور ذات جودة احترافية دون الحاجة إلى متصفح. + +من الآن فصاعدًا يمكنك تجربة DPI أعلى، خلفيات شفافة، أو معالجة دفعات من مقاطع HTML. النمط نفسه ينطبق سواء كنت تبني خدمة صور مصغرة، خط أنابيب توليد PDF، أو أداة معاينة موقع ثابت. + +تصوير سعيد، ولا تتردد في ترك تعليق إذا واجهت أي صعوبة! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/arabic/net/html-document-manipulation/_index.md b/html/arabic/net/html-document-manipulation/_index.md index 5dca51c48..efeb2b916 100644 --- a/html/arabic/net/html-document-manipulation/_index.md +++ b/html/arabic/net/html-document-manipulation/_index.md @@ -51,7 +51,7 @@ url: /ar/net/html-document-manipulation/ ## دروس تعليمية حول التعامل مع مستندات HTML ### [تحميل مستندات HTML بشكل غير متزامن في .NET باستخدام Aspose.HTML](./load-html-doc-asynchronously/) تعرف على كيفية استخدام Aspose.HTML for .NET للعمل مع مستندات HTML. دليل خطوة بخطوة مع أمثلة وأسئلة شائعة للمطورين. -### [تحميل مستندات HTML باستخدام بيانات الاعتماد في .NET باستخدام Aspose.HTML](./load-html-doc-with-credentials/) +### [تحميل مستندات HTML باستخدام بيانات الاعتماد في .NET باستخدام Aspose.HTML](./load-html-with-credentials/) تعرف على كيفية تعزيز تحسين محرك البحث الخاص بك باستخدام Aspose.HTML لـ .NET. قم بتعزيز التصنيفات وتحليل محتوى الويب وتحسينه لمحركات البحث. ### [تحميل HTML باستخدام خادم بعيد في .NET مع Aspose.HTML](./load-html-using-remote-server/) اكتشف إمكانات Aspose.HTML لـ .NET من خلال دليلنا الشامل. تعرّف على كيفية استيراد مساحات الأسماء والوصول إلى مستندات HTML عن بُعد والمزيد. @@ -71,6 +71,8 @@ url: /ar/net/html-document-manipulation/ أطلق العنان لإمكانات تطوير الويب باستخدام Aspose.HTML for .NET. أنشئ مستندات HTML وحولها وتعامل معها بسهولة. ### [إنشاء HTML من سلسلة في C# – دليل معالج الموارد المخصص](./create-html-from-string-in-c-custom-resource-handler-guide/) تعرف على كيفية إنشاء مستند HTML من سلسلة نصية في C# باستخدام معالج موارد مخصص. +### [تطبيق نمط الخط برمجيًا – دليل سريع C#](./apply-font-style-programmatically-quick-c-guide/) +دليل سريع لتطبيق أنماط الخط برمجيًا على مستندات HTML باستخدام Aspose.HTML في C#. ## خاتمة diff --git a/html/arabic/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/arabic/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..e6edbfadb --- /dev/null +++ b/html/arabic/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-04-23 +description: تطبيق نمط الخط برمجيًا وتعلم كيفية إزالة الخط السفلي من النص، وتغيير + نمط النص، وتعيين النص الغامق برمجيًا في دليل مختصر. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: ar +og_description: تطبيق نمط الخط برمجياً واكتشاف كيفية إزالة الخط السفلي من النص، وتغيير + نمط النص، وتعيين النص الغامق برمجياً في دليل قصير عملي. +og_title: تطبيق نمط الخط برمجياً – دليل C# سريع +tags: +- csharp +- ui +- text-formatting +- programming +title: تطبيق نمط الخط برمجيًا – دليل C# السريع +url: /ar/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تطبيق نمط الخط برمجيًا – دليل سريع بلغة C# + +هل احتجت يومًا إلى **تطبيق نمط الخط** على عنصر واجهة المستخدم لكن لم تكن متأكدًا من أين تبدأ؟ لست وحدك—معظم المطورين يواجهون هذه المشكلة عندما يبدأون بالتحكم الديناميكي في تنسيق النص. الخبر السار؟ خلال دقائق قليلة ستعرف بالضبط كيف تغير مظهر تسمية، وتزيل الخط السفلي من النص، وتضبط النص الغامق برمجيًا دون الحاجة للبحث في وثائق لا نهائية. + +في هذا **الدليل لتنسيق النص** سنستعرض مثالًا كاملًا قابلًا للتنفيذ، نشرح "السبب" وراء كل سطر، ونضيف نصائح عملية يمكنك نسخها‑لصقها في أي مشروع WinForms أو WPF. لا حشو، فقط ما ينجز المهمة. + +--- + +## ما ستتعلمه + +- كيف **تطبق نمط الخط** باستخدام فئة مساعدة صغيرة. +- الخطوات الدقيقة **لإزالة الخط السفلي من النص** مع الحفاظ على الأنماط الأخرى. +- طرق **تغيير نمط النص** (غامق، مائل، تحته خط) في الوقت الحقيقي. +- مقتطف كامل جاهز للنسخ **يضبط النص الغامق برمجيًا**. +- الأخطاء الشائعة وتعامل مع الحالات الحدية حتى لا تُفاجأ لاحقًا. + +**المتطلبات المسبقة:** .NET 6+ (أو أي نسخة حديثة من .NET Framework)، معرفة أساسية بـ C#، وبيئة تطوير من اختيارك (Visual Studio، Rider، أو VS Code). هذا كل ما تحتاجه—لا حزم NuGet إضافية مطلوبة. + +--- + +## الخطوة 1 – تطبيق نمط الخط على التحكم الخاص بك + +جوهر أي عملية **تطبيق نمط الخط** هو تعداد `FontStyle` مع كائن `Font`. لجعل الكود منظمًا سنغلف منطق التعداد داخل فئة صغيرة تسمى `WebFontStyle`. هذه الفئة تعكس الخصائص التي رأيتها في المقتطف الأصلي (`Bold`, `Italic`, `Underline`) وتُنشئ قيمة `FontStyle` يمكنك تمريرها إلى `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**لماذا هذا مهم:** +من خلال عزل منطق بناء العلامات، تتجنب نشر عمليات bitwise `|` في كل مكان في كود الواجهة. يصبح الكود أسهل للقراءة، وأسهل للاختبار،—والأهم—يجعل نية **تطبيق نمط الخط** واضحة تمامًا. + +--- + +## الخطوة 2 – إزالة الخط السفلي من النص (مع الحفاظ على الأنماط الأخرى) + +افترض أنك ورثت تسمية مُحددة بالفعل بخط سفلي، لكن التصميم يتطلب نصًا غامقًا عاديًا. لا تريد فقدان الغامق أثناء إزالة الخط السفلي. هنا تتألق فئة `WebFontStyle`. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**النقطة الأساسية:** ضبط `Underline = false` صراحةً يخبر المساعد *باستبعاد* علامة الخط السفلي. إذا حذفت السطر تمامًا، سيستمر الخط السفلي السابق، وهذا مصدر شائع للأخطاء عندما يقتصر المطورون على تبديل خاصية `Bold` فقط. + +--- + +## الخطوة 3 – تغيير نمط النص: غامق، مائل، وأكثر + +قد تتساءل، “ماذا لو أردت تبديل المائل أيضًا؟” نفس الكائن يعمل لأي تركيبة. أدناه مصفوفة سريعة يمكنك الرجوع إليها أثناء البرمجة. + +| النمط المطلوب | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **غامق فقط** | true | false | false | +| *مائل فقط* | false | true | false | +| **غامق + مائل** | true | true | false | +| **غامق + تحته خط** | true | false | true | + +ما عليك سوى ضبط الخصائص التي تحتاجها واستدعاء `ToFont`. المساعد يقوم بالعمل الشاق نيابةً عنك، لتتمكن من التركيز على منطق الواجهة. + +--- + +## مثال كامل – ضبط النص الغامق برمجيًا + +فيما يلي مثال **كامل وقابل للتنفيذ على WinForms** يوضح كل ما تناولناه. الصقه في مشروع WinForms جديد من نوع console‑style واضغط **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### النتيجة المتوقعة + +عند تشغيل البرنامج، تظهر نافذة تحتوي على النص **“Hello, world!”** معروضًا **غامقًا**، **ليس مائلًا**، و**بدون أي خط سفلي**. هذا التأكيد البصري يُظهر أن منطق **تطبيق نمط الخط** عمل بشكل مثالي. + +--- + +## نصائح احترافية وحالات حدية + +- **التحديثات الديناميكية:** إذا احتجت لتغيير النمط بعد إظهار النموذج (مثلاً استجابةً لمربع اختيار)، ما عليك سوى إنشاء كائن `WebFontStyle` جديد أو تعديل خصائصه وإعادة تعيين `lbl.Font`. ستُحدَّث الواجهة فورًا. +- **اعتبارات DPI العالية:** عند استبدال كائن `Font`، يقوم Windows تلقائيًا بتكييفه بناءً على DPI الحالي. لا تحتاج إلى كود إضافي إلا إذا كنت تتعامل مع التحجيم يدويًا. +- **المكافئ في WPF:** في WPF ستربط `FontWeight`، `FontStyle`، و`TextDecorations` بدلاً من استبدال كائن `Font`. نفس الفكرة المنطقية تُطبق—احتفظ بمنطق النمط خارج طبقة العرض. +- **تجنب تسرب الذاكرة:** إعادة تعيين `Label.Font` يُنشئ كائن `Font` جديد. قم بتحرير الكائن القديم إذا كنت تبدل الأنماط بشكل متكرر: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## الخلاصة + +أنت الآن تعرف كيف **تطبق نمط الخط** على أي عنصر .NET، **تزيل الخط السفلي من النص**، و**تغير نمط النص** في الوقت الحقيقي—كل ذلك مع الحفاظ على نظافة وإعادة استخدام الكود. المساعد الصغير `WebFontStyle` يحول مجموعة من العلامات البوليانية إلى مكوّن ثابت وقابل للاختبار، والمثال الكامل يثبت أنك تستطيع **ضبط النص الغامق برمجيًا** في بضع أسطر فقط. + +ما الخطوة التالية؟ جرّب دمج هذا النهج مع إعدادات يُحددها المستخدم، أو استكشف علامات `FontStyle` أخرى مثل `Strikeout`. يمكنك حتى إنشاء لوحة تحكم صغيرة تسمح للمستخدمين غير التقنيين باختيار الغامق أو المائل أو الخط السفلي أثناء التشغيل—دون الحاجة لإعادة التجميع. + +إذا وجدت هذا **الدليل لتنسيق النص** مفيدًا، لا تتردد في ترك تعليق أو مشاركة تنويعاتك الخاصة. برمجة سعيدة، ولتظهر واجهاتك دائمًا كما تريد! + +--- + +![لقطة شاشة تُظهر كيفية تطبيق نمط الخط على تسمية في C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/arabic/net/html-extensions-and-conversions/_index.md index 980eb7013..48d46b0c5 100644 --- a/html/arabic/net/html-extensions-and-conversions/_index.md +++ b/html/arabic/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ url: /ar/net/html-extensions-and-conversions/ تعلم كيفية حفظ مستند HTML كملف ZIP باستخدام Aspose.HTML في C# خطوة بخطوة. ### [حفظ HTML إلى ZIP في C# – مثال كامل في الذاكرة](./save-html-to-zip-in-c-complete-in-memory-example/) تعلم كيفية حفظ مستند HTML كملف ZIP في الذاكرة باستخدام C# ومكتبة Aspose.HTML. +### [كيفية ضغط HTML في C# – دليل معالج الموارد المخصص](./how-to-zip-html-in-c-custom-resource-handler-guide/) +تعلم كيفية ضغط ملفات HTML باستخدام C# ومعالج الموارد المخصص في Aspose.HTML. ## خاتمة diff --git a/html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..db5471757 --- /dev/null +++ b/html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-23 +description: تعلم كيفية ضغط HTML في C# باستخدام معالج موارد مخصص – دليل خطوة بخطوة + لحفظ HTML كملف zip، تحويل HTML إلى zip، وإنشاء zip من HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: ar +og_description: 'كيفية ضغط HTML في C# موضحًا: استخدم معالج موارد مخصص لحفظ HTML كملف + zip، تحويل HTML إلى zip، وإنشاء zip من HTML في دقائق.' +og_title: كيفية ضغط ملفات HTML في C# – دليل معالج الموارد المخصص +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: كيفية ضغط ملفات HTML في C# – دليل معالج الموارد المخصص +url: /ar/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية ضغط HTML في C# – دليل معالج الموارد المخصص + +هل تساءلت يومًا **كيفية ضغط HTML** مباشرةً من كود C# الخاص بك دون سحب الملفات إلى القرص أولاً؟ أنت لست وحدك. يواجه العديد من المطورين صعوبة عندما يحتاجون إلى حزم صفحة HTML مع ملفات CSS والصور والخطوط لتوزيعها دون اتصال، وينتهي بهم الأمر بكتابة كود نظام ملفات عشوائي يتحول بسرعة إلى كابوس صيانة. + +في هذا الدرس سنحل هذه المشكلة من خلال إظهار نهج نظيف وقابل لإعادة الاستخدام **يحفظ HTML كأرشيف ZIP** باستخدام `ResourceHandler` الخاص بـ Aspose.HTML. سنناقش أيضًا كيفية **تحويل HTML إلى ZIP**، وسنظهر نمطًا يمكنك إعادة استخدامه **لإنشاء ZIP من HTML** في أي مشروع .NET. لا سكريبتات خارجية، ولا مجلدات مؤقتة—فقط C# نقي. + +بنهاية الدليل ستحصل على مثال جاهز للتنفيذ ينتج ملف `result.zip` يحتوي على كل الموارد المرتبطة، بالإضافة إلى مجموعة من النصائح العملية التي يمكنك تطبيقها في مشاريعك الخاصة. + +## المتطلبات المسبقة + +- .NET 6+ (الكود يعمل أيضًا على .NET Framework 4.7.2، لكن نوصي بأحدث SDK) +- حزمة NuGet لـ Aspose.HTML للـ .NET (`Aspose.HTML`) – تثبيت عبر `dotnet add package Aspose.HTML` +- إلمام أساسي بـ streams ومساحة الاسم `System.IO.Compression` +- بيئة تطوير أو محرر حسب اختيارك (Visual Studio، VS Code، Rider…) + +إذا كان لديك هذه المكونات بالفعل، رائع—لننتقل مباشرة إلى الكود. إذا لم يكن كذلك، الخطوة الإضافية الوحيدة هي تثبيت سطر واحد عبر NuGet؛ كل شيء آخر متكامل ذاتيًا. + +## الخطوة 1: إنشاء مستند HTML بسيط في الذاكرة + +أولاً نحتاج إلى كائن `HTMLDocument` يمثل الصفحة التي نريد ضغطها. في سيناريو واقعي قد تقوم بتحميله من URL أو ملف، لكن للتوضيح سنبني مستندًا صغيرًا داخل الكود. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **لماذا هذا مهم:** +> من خلال إبقاء المستند في الذاكرة نتجنب أي عمليات I/O للملفات الوسيطة، مما يجعل خطوة **تحويل html إلى zip** لاحقًا سريعة وآمنة للـ thread. + +## الخطوة 2: إعداد تدفق ZIP في الذاكرة + +بدلاً من كتابة ملف `.zip` مؤقت على القرص، سنستخدم `MemoryStream`. هذا يبقي كل شيء في الذاكرة RAM، وهو مثالي لخدمات الويب أو وظائف الخلفية التي تحتاج إلى إرجاع الأرشيف مباشرةً إلى العميل. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **نصيحة:** يضمن بيان `using` التخلص التلقائي من التدفق، مما يمنع تسرب الذاكرة. + +## الخطوة 3: تنفيذ معالج موارد مخصص + +Aspose.HTML يستدعي `ResourceHandler` لكل مورد خارجي يكتشفه (ملفات CSS، الصور، الخطوط، إلخ). من خلال إنشاء فئة فرعية من `ResourceHandler` يمكننا تحديد بالضبط أين ينتهي كل مورد—في حالتنا، كإدخال داخل أرشيف ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### لماذا معالج مخصص؟ + +- **التحكم في التسمية** – أنت تقرر كيف يظهر كل ملف في الأرشيف. +- **عدم وجود ملفات مؤقتة** – المعالج يكتب مباشرةً في ZIP الموجود في الذاكرة. +- **قابلية إعادة الاستخدام** – يمكنك إضافة هذه الفئة إلى أي مشروع يحتاج إلى **حفظ html كـ zip**. + +## الخطوة 4: حفظ مستند HTML باستخدام المعالج + +الآن نجمع كل شيء معًا. ستستدعي طريقة `Save` `HandleResource` لكل مورد مرتبط، وسيقوم المعالج ببث تلك البايتات إلى أرشيف ZIP الذي أنشأناه مسبقًا. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **ماذا يحدث خلف الكواليس؟** +> يقوم Aspose بتحليل HTML، يكتشف المرجع ``، يطلب من المعالج تدفقًا، ويقوم المعالج بإنشاء إدخال `logo.png` داخل ZIP. يتكرر نفس التدفق للـ CSS، الخطوط، أو أي مورد خارجي آخر. + +## الخطوة 5: حفظ أرشيف ZIP على القرص (أو إرجاعه) + +أخيرًا نكتب الأرشيف الموجود في الذاكرة إلى ملف. في واجهة ويب API يمكنك بدلاً من ذلك إرجاع `zipMemoryStream.ToArray()` كمصفوفة بايت. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### النتيجة المتوقعة + +افتح `result.zip` ويجب أن ترى: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +إذا فتحت الأرشيف في مستكشف الملفات ستلاحظ أن ملف HTML مخزن كـ `resource.bin` لأننا لم نعطه اسمًا واضحًا. يمكنك تحسين ذلك بسهولة عن طريق فحص `resourceInfo.ContentType` وتعيين `.html` عندما يكون مناسبًا. + +## مثال كامل يعمل + +فيما يلي البرنامج الكامل الجاهز للنسخ واللصق والذي يدمج جميع الخطوات السابقة. شغّله من تطبيق console، وستحصل على ملف ZIP جاهز للمشاركة. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**تشغيل هذا الكود** سيولد `result.zip` في دليل عمل البرنامج. افتحه وستجد `index.html` (صفحتنا الأصلية) بالإضافة إلى `logo.png` إذا كان ذلك الصورة موجودة على القرص أو تم جلبها من URL. + +## الاختلافات الشائعة وحالات الحافة + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/chinese/net/generate-jpg-and-png-images/_index.md index 3a7bc53dc..005da5399 100644 --- a/html/chinese/net/generate-jpg-and-png-images/_index.md +++ b/html/chinese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET 提供了一种将 HTML 转换为图像的简单方法。 了解如何在使用 Aspose.HTML for .NET 将 DOCX 文档转换为 PNG 或 JPG 图像时启用抗锯齿,以提升图像质量。 ### [使用 C# 将 docx 转换为 png 并创建 zip 存档教程](./convert-docx-to-png-create-zip-archive-c-tutorial/) 学习如何使用 C# 将 DOCX 文档转换为 PNG 图像并打包为 ZIP 文件的完整步骤。 +### [从 HTML 创建 PNG – C# 开发者分步指南](./create-png-from-html-step-by-step-guide-for-c-developers/) +学习使用 Aspose.HTML for .NET 将 HTML 转换为 PNG 图像的完整步骤,适用于 C# 开发者。 ## 结论 diff --git a/html/chinese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/chinese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..14f3f5d8e --- /dev/null +++ b/html/chinese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-04-23 +description: 使用 Aspose.HTML 快速将 HTML 转换为 PNG。学习如何将 HTML 渲染为 PNG、设置画布大小、添加背景颜色,并在几分钟内保存渲染后的图像。 +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: zh +og_description: 使用 Aspose.HTML 将 HTML 转换为 PNG。本指南展示了如何将 HTML 渲染为 PNG、设置画布大小、添加背景颜色以及保存渲染后的图像。 +og_title: 将 HTML 转换为 PNG – 完整的 C# 渲染教程 +tags: +- C# +- Aspose.HTML +- Image Rendering +title: 将HTML转换为PNG – C# 开发者的逐步指南 +url: /zh/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 从 HTML 创建 PNG – 完整的 C# 渲染教程 + +是否曾经需要**从 HTML 创建 PNG**,但不确定哪个库能够提供清晰、抗锯齿的效果?你并不孤单。在许多 web‑to‑image 流程中,最大的痛点是让文本和图形看起来像在浏览器中一样锐利。 + +好消息是?使用 Aspose.HTML,你可以在几行代码中**将 HTML 渲染为 PNG**,控制画布大小,添加纯色背景,最后**将渲染的图像**保存到磁盘——全部无需打开浏览器。在本教程中,我们将完整演示整个过程,解释每个设置的意义,并展示一个可直接运行的示例。 + +## 您将学习 + +- 如何从字符串、文件或 URL 加载 HTML +- 如何配置 **set canvas size** 和 **add background color** 以获得可预测的输出 +- 启用抗锯齿和子像素文字提示,以实现锐利的标题 +- 将 **save rendered image** 保存为 PNG 文件的完整步骤 +- 常见陷阱以及针对不同场景的可选调整 + +无需事先了解 Aspose.HTML;只需基本的 C# 环境和 Visual Studio(或您喜欢的 IDE)即可。 + +--- + +## 第一步:安装 Aspose.HTML for .NET + +在编写任何代码之前,请确保在项目中引用了 Aspose.HTML NuGet 包。 + +```bash +dotnet add package Aspose.HTML +``` + +> **专业提示:** 使用最新的稳定版本(截至 2026 年 4 月,23.9.0)以获取最新的渲染引擎和错误修复。 + +--- + +## 第二步:加载 HTML 源 – 从 HTML 创建 PNG + +你可以向渲染器提供内联字符串、本地文件或远程 URL。演示中我们使用一个包含自定义字体标题的简单内联字符串。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**为什么这很重要:** 将 HTML 加载到 `HTMLDocument` 中,使引擎能够完全控制 DOM 解析、CSS 级联和布局计算。它还将渲染与任何外部浏览器状态隔离,确保结果可复现。 + +--- + +## 第三步:配置渲染选项 – 设置画布大小并添加背景颜色 + +`ImageRenderingOptions` 类允许你细调输出图像。在这里我们将启用抗锯齿,设置白色背景,并明确定义 **800 × 600 px** 的画布。 + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**为什么可能需要更改这些值:** +- **Canvas size(画布大小):** 如果需要缩略图,可缩小尺寸;若用于高分辨率打印,则增大尺寸。 +- **Background color(背景颜色):** 可以使用透明 PNG,但许多下游工具(例如 PowerPoint)期望不透明背景。 + +--- + +## 第四步:渲染并 **Save Rendered Image** 为 PNG + +现在开始进行繁重的工作。`ImageRenderer` 使用我们刚定义的 `HTMLDocument` 和选项,然后将 PNG 流写入磁盘。 + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +运行程序后,你会在桌面上找到 `result.png`。打开它,你应该会看到一个居中在白色画布上的干净、抗锯齿的标题。 + +> **预期输出:** 一个 800 × 600 的 PNG,白色背景,文本 “Antialiased Heading” 使用 Arial 渲染,平滑程度与 Chrome 中相同。 + +--- + +## 第五步:验证结果 – 快速检查 + +1. **文件是否存在:** `File.Exists(outputPath)` 应返回 `true`。 +2. **尺寸:** 在任意图像查看器中打开 PNG,应该显示 800 × 600 px。 +3. **视觉质量:** 放大至 200 %——文字边缘必须保持平滑,而不是锯齿状。 + +如果出现异常,请再次确认 `UseAntialiasing` 和 `UseHinting` 均已设置为 `true`。这两个标志是高质量渲染的关键。 + +--- + +## 常见变体与边缘情况 + +| 场景 | 调整内容 | 原因 | +|----------|----------------|-----| +| **渲染远程网页** | Replace `new HTMLDocument(htmlContent)` with `new HTMLDocument("https://example.com")` | 允许在不手动复制 HTML 的情况下捕获实时站点。 | +| **透明背景** | Set `BackgroundColor = Color.Transparent` and use `ImageFormat.Png` | 在其他图形上叠加 PNG 时很有用。 | +| **不同的图像格式** | Change `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG 对于照片内容可能更小,但会失去无损质量。 | +| **动态画布大小** | Use `imgOptions.Width = htmlDoc.Body.ClientWidth;` after layout | 使图像匹配 HTML 内容的自然宽度。 | +| **高 DPI 输出** | Multiply `Width` and `Height` by a scale factor (e.g., 2) | 为现代显示器生成 Retina 级别的资源。 | + +--- + +## 完整可运行示例(复制粘贴即可) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +运行程序(`dotnet run` 或在 Visual Studio 中按 F5),即可得到一张完美渲染的 PNG,可用于电子邮件、报告或任何需要 HTML 静态图像的场景。 + +--- + +## 常见问题 + +**问:这是否支持 CSS 3 的特性,如 flexbox?** +**答:** 是的。Aspose.HTML 支持大多数现代 CSS,包括 flexbox、grid 和媒体查询。只需确保使用最新的库版本。 + +**问:如果我的 HTML 引用了外部图片怎么办?** +**答:** 渲染器会根据文档的 base URI 解析相对 URL。如果你从字符串加载 HTML,请将 `doc.BaseUrl` 设置为包含资源的文件夹路径。 + +**问:能否将多个页面渲染为一个 PNG 吗?** +**答:** 不能直接实现——每次调用 `ImageRenderer` 都会生成单个光栅图像。若需多页输出,可分别渲染每页,然后使用图形库(例如 ImageSharp)将它们拼接在一起。 + +--- + +## 结论 + +现在,你已经拥有一个完整的、端到端的解决方案,使用 Aspose.HTML **从 HTML 创建 PNG**。通过配置 **render html to png** 选项——例如 **set canvas size**、**add background color**,以及启用抗锯齿,你可以在无需浏览器的情况下生成专业级图像。 + +接下来,你可以尝试更高 DPI、透明背景,或批量处理数十个 HTML 片段。无论是构建缩略图服务、PDF 生成流水线,还是静态站点预览工具,都是相同的模式。 + +祝渲染愉快,如遇问题欢迎留言!🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/chinese/net/html-document-manipulation/_index.md b/html/chinese/net/html-document-manipulation/_index.md index d79966fc2..08a839504 100644 --- a/html/chinese/net/html-document-manipulation/_index.md +++ b/html/chinese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML for .NET 以其简单性和强大性脱颖而出。它使您能够 使用 Aspose.HTML for .NET 释放 Web 开发的潜力。轻松创建、转换和操作 HTML 文档。 ### [在 C# 中从字符串创建 HTML – 自定义资源处理程序指南](./create-html-from-string-in-c-custom-resource-handler-guide/) 了解如何使用自定义资源处理程序将字符串转换为 HTML 文档。 +### [使用 Aspose.HTML 在 .NET 中以编程方式应用字体样式 – 快速 C# 指南](./apply-font-style-programmatically-quick-c-guide/) +了解如何使用 Aspose.HTML for .NET 在 C# 中以编程方式设置字体样式的快速指南。 ## 结论 diff --git a/html/chinese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/chinese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..1b0085b61 --- /dev/null +++ b/html/chinese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-04-23 +description: 通过编程应用字体样式,并在简明教程中学习如何去除文本下划线、更改文本样式以及以编程方式设置粗体文本。 +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: zh +og_description: 通过编程方式应用字体样式,并在简短实用的教程中了解如何去除文本下划线、更改文本样式以及以编程方式设置粗体文本。 +og_title: 以编程方式应用字体样式 – 快速 C# 指南 +tags: +- csharp +- ui +- text-formatting +- programming +title: 以编程方式应用字体样式 – 快速 C# 指南 +url: /zh/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 以编程方式应用字体样式 – 快速 C# 指南 + +是否曾经需要**apply font style**到 UI 元素,却不知从何入手?你并非唯一——大多数开发者在首次尝试动态文本格式化时都会遇到这个难题。好消息是?只需几分钟,你就能准确地了解如何更改标签的外观、去除文本下划线,以及以编程方式设置粗体文本,而无需在海量文档中搜索。 + +在本**text formatting tutorial**中,我们将逐步演示一个完整、可运行的示例,解释每行代码背后的“原因”,并提供可直接复制粘贴到任何 WinForms 或 WPF 项目中的实用技巧。没有废话,只有真正能完成任务的内容。 + +--- + +## 你将学到的内容 + +- 如何使用小型帮助类**apply font style**。 +- 在保持其他样式不变的情况下,**remove underline from text**的精确步骤。 +- 实时**change text style**(粗体、斜体、下划线)的方法。 +- 一个完整的、可直接复制的代码片段,**sets bold text programmatically**。 +- 常见陷阱和边缘情况的处理,避免后期意外。 + +**先决条件:** .NET 6+(或任何近期的 .NET Framework)、基本的 C# 知识,以及你选择的 IDE(Visual Studio、Rider 或 VS Code)。就这些——无需额外的 NuGet 包。 + +## 步骤 1 – Apply Font Style to Your Control + +任何**apply font style**操作的核心是 `FontStyle` 枚举与 `Font` 对象的组合。为保持代码整洁,我们将把枚举逻辑封装在一个小型 `WebFontStyle` 类中。该类映射了原始代码片段中的属性(`Bold`、`Italic`、`Underline`),并生成可传递给 `Font` 的 `FontStyle` 值。 + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**为什么这很重要:** +通过将标志构建逻辑隔离出来,你可以避免在 UI 代码中到处散布位运算 `|`。这使代码更易读、更易测试,且——最重要的是——让**apply font style**的意图一目了然。 + +## 步骤 2 – Remove Underline from Text(并保持其他样式完整) + +假设你继承了一个已经带下划线的标签,但设计要求是普通的粗体文本。你不想在去除下划线的同时失去粗体效果。此时 `WebFontStyle` 类就显得尤为重要。 + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**关键点:** 将 `Underline = false` 明确设置,告诉帮助类*排除*下划线标志。如果完全省略此行,之前的下划线仍会保留,这是开发者仅切换 `Bold` 属性时常见的错误来源。 + +## 步骤 3 – Change Text Style:粗体、斜体及更多 + +你可能会想,“如果我还需要切换斜体怎么办?”同一个对象可以处理任意组合。下面是一个快速矩阵,供编码时参考。 + +| 期望样式 | Bold | Italic | Underline | +|----------|------|--------|-----------| +| **仅粗体** | true | false | false | +| *仅斜体* | false | true | false | +| **粗体 + 斜体** | true | true | false | +| **粗体 + 下划线** | true | false | true | + +只需设置所需的属性并调用 `ToFont`。帮助类会为你完成繁重的工作,让你专注于 UI 逻辑。 + +## 完整示例 – Set Bold Text Programmatically + +下面是一个**完整、可运行的 WinForms**示例,演示了我们所覆盖的所有内容。将其粘贴到一个新的控制台式 WinForms 项目中,然后按 **F5** 运行。 + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### 预期结果 + +运行程序后,会弹出一个窗口,显示文本**“Hello, world!”**,其呈现为**粗体**、**非斜体**且**没有下划线**。这一视觉确认表明**apply font style**逻辑已完美工作。 + +## 专业技巧与边缘情况 + +- **动态更新:** 如果需要在窗体显示后更改样式(例如响应复选框),只需重新创建 `WebFontStyle` 实例或修改其属性,然后重新赋值给 `lbl.Font`。UI 会立即更新。 +- **高 DPI 考虑:** 当你替换 `Font` 对象时,Windows 会根据当前 DPI 自动进行缩放。除非手动处理缩放,否则无需额外代码。 +- **WPF 等价实现:** 在 WPF 中,你会绑定 `FontWeight`、`FontStyle` 和 `TextDecorations`,而不是交换 `Font` 对象。相同的逻辑分离仍然适用——将样式逻辑置于视图层之外。 +- **避免内存泄漏:** 重新赋值 `Label.Font` 会创建新的 `Font` 对象。如果频繁切换样式,请释放旧的对象:`var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +## 结论 + +现在你已经掌握了如何对任何 .NET 控件**apply font style**、**remove underline from text**以及实时**change text style**——同时保持代码清晰且可复用。小巧的 `WebFontStyle` 帮助类将少量布尔标志转换为可靠、可测试的组件,而完整示例则证明了只需几行代码即可**set bold text programmatically**。 + +接下来可以做什么?尝试将此方法与用户驱动的设置结合,或实验其他 `FontStyle` 标志,如 `Strikeout`。你甚至可以提供一个小型 UI 面板,让非技术用户在运行时选择粗体、斜体或下划线——无需重新编译。 + +如果你觉得本**text formatting tutorial**有帮助,欢迎留下评论或分享你的变体。祝编码愉快,愿你的 UI 始终如你所愿! + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/chinese/net/html-extensions-and-conversions/_index.md index a6c24babf..ed38070ac 100644 --- a/html/chinese/net/html-extensions-and-conversions/_index.md +++ b/html/chinese/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Aspose.HTML for .NET 不仅仅是一个库;它是 Web 开发领域的变革者 探索 Aspose.HTML for .NET 的强大功能:轻松将 HTML 转换为 XPS。包含先决条件、分步指南和常见问题解答。 ### [如何在 C# 中压缩 HTML – 将 HTML 保存为 Zip](./how-to-zip-html-in-c-save-html-to-zip/) 使用 Aspose.HTML for .NET 在 C# 中将 HTML 打包并保存为 Zip 文件的分步教程。 +### [如何在 C# 中压缩 HTML – 自定义资源处理程序指南](./how-to-zip-html-in-c-custom-resource-handler-guide/) +使用 Aspose.HTML for .NET 在 C# 中通过自定义资源处理程序将 HTML 打包为 ZIP 的完整指南。 ### [使用 Aspose.HTML 在 .NET 中创建带样式文本的 HTML 文档并导出为 PDF – 完整指南](./create-html-document-with-styled-text-and-export-to-pdf-full/) 本完整指南展示如何使用 Aspose.HTML for .NET 创建带样式的 HTML 文档并将其导出为 PDF,包含详细步骤和代码示例。 ### [使用 Aspose.HTML 在 C# 中将 HTML 创建为 PDF – 完整指南](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..137315ed5 --- /dev/null +++ b/html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-23 +description: 学习如何在 C# 中使用自定义资源处理程序压缩 HTML——一步步指南,教您将 HTML 保存为 ZIP、将 HTML 转换为 ZIP,以及从 + HTML 创建 ZIP。 +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: zh +og_description: 如何在 C# 中压缩 HTML:使用自定义资源处理程序将 HTML 保存为 ZIP,转换 HTML 为 ZIP,并在几分钟内从 HTML + 创建 ZIP。 +og_title: 如何在 C# 中压缩 HTML – 自定义资源处理程序指南 +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: 如何在 C# 中压缩 HTML – 自定义资源处理程序指南 +url: /zh/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中压缩 HTML – 自定义资源处理程序指南 + +是否曾想过 **直接在 C# 代码中压缩 HTML**,而不先将文件写入磁盘?你并不孤单。许多开发者在需要将 HTML 页面连同其 CSS、图片和字体一起打包用于离线分发时,常常卡在需要编写临时文件系统代码的难题上,这些代码很快就会变成维护噩梦。 + +在本教程中,我们将通过展示一种简洁、可复用的方法,使用 Aspose.HTML 的 `ResourceHandler` **将 HTML 保存为 ZIP 压缩包**。我们还会涉及 **将 HTML 转换为 ZIP** 的实现,并演示一种可以在任何 .NET 项目中复用的 **从 HTML 创建 ZIP** 的模式。无需外部脚本、无需临时文件夹——纯 C# 实现。 + +阅读完本指南后,你将拥有一个可直接运行的示例,它会生成一个 `result.zip`,其中包含所有关联资源,并提供一系列实用技巧,帮助你在自己的项目中快速上手。 + +## 前置条件 + +- .NET 6+(代码同样适用于 .NET Framework 4.7.2,但我们推荐使用最新 SDK) +- Aspose.HTML for .NET NuGet 包(`Aspose.HTML`)——通过 `dotnet add package Aspose.HTML` 安装 +- 对流(streams)和 `System.IO.Compression` 命名空间有基本了解 +- 任意你喜欢的 IDE 或编辑器(Visual Studio、VS Code、Rider …) + +如果这些条件已经具备,太好了——直接进入代码部分。如果还没有,只需执行一行 NuGet 安装指令,其他全部自包含。 + +## 第一步:在内存中创建一个简单的 HTML 文档 + +首先我们需要一个 `HTMLDocument` 对象,代表要压缩的页面。在真实场景中,你可能会从 URL 或文件加载它,但为保持清晰,这里直接在代码中构建一个小文档。 + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **为什么这很重要:** +> 将文档保存在内存中可以避免任何中间文件 I/O,使后续的 **convert html to zip** 步骤既快速又线程安全。 + +## 第二步:准备一个内存中的 ZIP 流 + +我们不再向磁盘写入临时的 `.zip` 文件,而是使用 `MemoryStream`。这样所有内容都保存在 RAM 中,非常适合需要直接将归档返回给客户端的 Web 服务或后台任务。 + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **提示:** `using` 语句会自动释放流,防止内存泄漏。 + +## 第三步:实现自定义 ResourceHandler + +Aspose.HTML 会为它发现的每个外部资源(CSS 文件、图片、字体等)调用 `ResourceHandler`。通过继承 `ResourceHandler`,我们可以精确决定每个资源的去向——在本例中,即写入 ZIP 包内的条目。 + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### 为什么需要自定义处理程序? + +- **命名可控** – 你可以自行决定每个文件在归档中的名称。 +- **无需临时文件** – 处理程序直接写入内存中的 ZIP。 +- **可复用** – 只要需要 **save html as zip**,就可以把此类放进任何项目。 + +## 第四步:使用自定义处理程序保存 HTML 文档 + +现在把所有部件组合起来。`Save` 方法会为每个关联资源调用 `HandleResource`,而处理程序会把这些字节流写入我们之前创建的 ZIP 包。 + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **内部到底发生了什么?** +> Aspose 解析 HTML,发现 `` 引用后,会请求处理程序提供流,处理程序随后在 ZIP 中创建 `logo.png` 条目。CSS、字体或其他外部资源的处理流程相同。 + +## 第五步:将 ZIP 归档持久化到磁盘(或返回给调用方) + +最后,我们把内存中的归档写入文件。在 Web API 场景下,你也可以直接返回 `zipMemoryStream.ToArray()` 作为字节数组。 + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### 预期结果 + +打开 `result.zip`,你应当看到: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +如果你在文件资源管理器中查看该压缩包,会发现 HTML 文件被存储为 `resource.bin`,因为我们没有为它指定友好的名称。你可以通过检查 `resourceInfo.ContentType` 并在合适时赋予 `.html` 扩展名来轻松改进。 + +## 完整可运行示例 + +下面是完整的、可直接复制粘贴的程序,涵盖了上述所有步骤。将其放入控制台应用程序中运行,即可得到一个可分享的 ZIP 文件。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**运行此代码** 将在程序工作目录下生成 `result.zip`。打开后,你会看到 `index.html`(原始页面)以及如果磁盘上存在或从 URL 获取到的 `logo.png`。 + +## 常见变体与边缘情况 + +| 场景 + +{{< /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/generate-jpg-and-png-images/_index.md b/html/czech/net/generate-jpg-and-png-images/_index.md index 11b9c8465..4cdcbd58f 100644 --- a/html/czech/net/generate-jpg-and-png-images/_index.md +++ b/html/czech/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Naučte se používat Aspose.HTML pro .NET k manipulaci s dokumenty HTML, převo Naučte se, jak při převodu dokumentů DOCX na PNG nebo JPG povolit antialiasing pro hladší výstup. ### [Převod docx na png – vytvoření zip archivu C# tutoriál](./convert-docx-to-png-create-zip-archive-c-tutorial/) Naučte se převést soubory DOCX na PNG a zabalit je do ZIP archivu pomocí C# a Aspose.HTML. +### [Vytvořte PNG z HTML – krok za krokem průvodce pro vývojáře C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Naučte se, jak pomocí Aspose.HTML pro .NET převést HTML na PNG v podrobném průvodci pro vývojáře C#. ## Závěr diff --git a/html/czech/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/czech/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..b02c2013d --- /dev/null +++ b/html/czech/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Rychle vytvořte PNG z HTML pomocí Aspose.HTML. Naučte se, jak převést + HTML na PNG, nastavit velikost plátna, přidat barvu pozadí a během několika minut + uložit vykreslený obrázek. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: cs +og_description: Vytvořte PNG z HTML pomocí Aspose.HTML. Tento průvodce ukazuje, jak + renderovat HTML do PNG, nastavit velikost plátna, přidat barvu pozadí a uložit vykreslený + obrázek. +og_title: Vytvořte PNG z HTML – Kompletní tutoriál renderování v C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Vytvořte PNG z HTML – krok za krokem průvodce pro vývojáře C# +url: /cs/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření PNG z HTML – Kompletní tutoriál renderování v C# + +Už jste někdy potřebovali **vytvořit PNG z HTML**, ale nebyli jste si jisti, která knihovna vám poskytne ostré, antialiasované výsledky? Nejste v tom sami. V mnoha pipelinech web‑na‑obrázek je největší problém získat text a grafiku tak ostré, jak vypadají v prohlížeči. + +Dobrá zpráva? S Aspose.HTML můžete **renderovat HTML do PNG** během několika řádků, ovládat velikost plátna, přidat plnou barvu pozadí a nakonec **uložit vykreslený obrázek** na disk — vše bez použití prohlížeče. V tomto tutoriálu projdeme celý proces, vysvětlíme, proč je každé nastavení důležité, a ukážeme vám připravený příklad. + +## Co se naučíte + +- Jak načíst HTML ze řetězce, souboru nebo URL +- Jak nakonfigurovat **nastavení velikosti plátna** a **přidání barvy pozadí** pro předvídatelný výstup +- Povolení antialiasingu a subpixelového hintingu textu pro břitce ostré nadpisy +- Přesné kroky k **uložení vykresleného obrázku** jako PNG souboru +- Běžné úskalí a volitelné úpravy pro různé scénáře + +Předchozí zkušenost s Aspose.HTML není vyžadována; stačí základní nastavení C# a Visual Studio (nebo vaše oblíbené IDE). + +--- + +## Krok 1: Instalace Aspose.HTML pro .NET + +Než napíšeme jakýkoli kód, ujistěte se, že je v projektu odkaz na NuGet balíček Aspose.HTML. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Použijte nejnovější stabilní verzi (k dubnu 2026, 23.9.0), abyste získali nejnovější renderovací engine a opravy chyb. + +--- + +## Krok 2: Načtení HTML zdroje – Vytvoření PNG z HTML + +Můžete rendereru předat inline řetězec, lokální soubor nebo vzdálenou URL. Pro tuto ukázku použijeme jednoduchý inline řetězec, který obsahuje nadpis s vlastní fontem. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Proč je to důležité:** Načtení HTML do `HTMLDocument` dává enginu plnou kontrolu nad parsováním DOM, kaskádou CSS a výpočty rozložení. Také izoluje renderování od jakéhokoli externího stavu prohlížeče, což zajišťuje reprodukovatelné výsledky. + +--- + +## Krok 3: Konfigurace možností renderování – Nastavení velikosti plátna a přidání barvy pozadí + +Třída `ImageRenderingOptions` vám umožní jemně doladit výstupní obrázek. Zde povolíme antialiasing, nastavíme bílé pozadí a explicitně definujeme plátno **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Proč byste mohli tyto hodnoty měnit:** +- **Velikost plátna:** Pokud potřebujete miniaturu, zmenšete rozměry; pro vysoce‑rozlišené tisky je zvětšete. +- **Barva pozadí:** Transparentní PNG jsou možné, ale mnoho následných nástrojů (např. PowerPoint) očekává neprůhledné pozadí. + +--- + +## Krok 4: Renderování a **uložení vykresleného obrázku** jako PNG + +Nyní se děje těžká práce. `ImageRenderer` spotřebuje `HTMLDocument` a právě definované možnosti a zapíše PNG stream na disk. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Když spustíte program, najdete `result.png` na ploše. Otevřete jej a měli byste vidět čistý, antialiasovaný nadpis vycentrovaný na bílém plátně. + +> **Očekávaný výstup:** PNG 800 × 600 s bílým pozadím a textem „Antialiased Heading“ vykresleným v Arial, vypadajícím stejně hladce jako v Chrome. + +--- + +## Krok 5: Ověření výsledku – Rychlé kontroly + +1. **Existence souboru:** `File.Exists(outputPath)` by měl vrátit `true`. +2. **Rozměry:** Otevřete PNG v libovolném prohlížeči obrázků; měl by uvádět 800 × 600 px. +3. **Vizální kvalita:** Přibližte na 200 % – hrany textu musí zůstat hladké, ne zubaté. + +Pokud něco vypadá špatně, zkontrolujte, že `UseAntialiasing` i `UseHinting` jsou nastaveny na `true`. Tyto dva příznaky jsou tajnou ingrediencí pro vysoce‑kvalitní renderování. + +--- + +## Běžné varianty a okrajové případy + +| Scénář | Co upravit | Proč | +|----------|----------------|-----| +| **Render a remote web page** | Replace `new HTMLDocument(htmlContent)` with `new HTMLDocument("https://example.com")` | Allows you to capture live sites without copying HTML manually. | +| **Transparent background** | Set `BackgroundColor = Color.Transparent` and use `ImageFormat.Png` | Useful for overlaying the PNG on other graphics. | +| **Different image format** | Change `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG may be smaller for photographic content, but loses lossless quality. | +| **Dynamic canvas size** | Use `imgOptions.Width = htmlDoc.Body.ClientWidth;` after layout | Lets the image match the natural width of the HTML content. | +| **High‑DPI output** | Multiply `Width` and `Height` by a scale factor (e.g., 2) | Generates retina‑ready assets for modern displays. | + +--- + +## Kompletní funkční příklad (připravený ke kopírování) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Spusťte program (`dotnet run` nebo stiskněte F5 ve Visual Studiu) a získáte perfektně vykreslené PNG připravené k použití v e‑mailech, reportech nebo kdekoliv, kde potřebujete statický obrázek HTML. + +--- + +## Často kladené otázky + +**Q: Funguje to s CSS 3 funkcemi jako flexbox?** +A: Ano. Aspose.HTML podporuje většinu moderního CSS, včetně flexboxu, gridu a media queries. Jen se ujistěte, že používáte nejnovější verzi knihovny. + +**Q: Co když moje HTML odkazuje na externí obrázky?** +A: Renderer následuje relativní URL na základě základního URI dokumentu. Pokud načítáte HTML ze řetězce, nastavte `doc.BaseUrl` na složku obsahující assety. + +**Q: Můžu renderovat více stránek do jednoho PNG?** +A: Ne přímo — každé volání `ImageRenderer` vytvoří jeden rastrový obrázek. Pro výstup více stránek renderujte každou stránku zvlášť a spojte je pomocí grafické knihovny (např. ImageSharp). + +--- + +## Závěr + +Nyní máte solidní end‑to‑end řešení pro **vytvoření PNG z HTML** pomocí Aspose.HTML. Konfigurací **render html to png** možností — jako je **nastavení velikosti plátna**, **přidání barvy pozadí** a povolení antialiasingu — můžete generovat profesionální obrázky bez prohlížeče. + +Od této chvíle můžete experimentovat s vyšším DPI, transparentními pozadími nebo hromadným zpracováním desítek HTML úryvků. Stejný vzor platí, ať už budujete službu pro miniatury, pipeline pro generování PDF nebo nástroj pro náhled statických stránek. + +Šťastné renderování a klidně zanechte komentář, pokud narazíte na nějaké problémy! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/czech/net/html-document-manipulation/_index.md index 6f2c68f80..5a100a70b 100644 --- a/html/czech/net/html-document-manipulation/_index.md +++ b/html/czech/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Naučte se používat Aspose.HTML pro .NET. Importujte jmenný prostor, slučujt Odemkněte potenciál vývoje webu s Aspose.HTML pro .NET. Snadno vytvářejte, převádějte a manipulujte s dokumenty HTML. ### [Vytvoření HTML ze řetězce v C# – Průvodce vlastním Resource Handlerem](./create-html-from-string-in-c-custom-resource-handler-guide/) Naučte se, jak vytvořit HTML dokument z řetězce v C# pomocí vlastního Resource Handleru. +### [Aplikujte styl písma programově – Rychlý průvodce C#](./apply-font-style-programmatically-quick-c-guide/) +Naučte se, jak pomocí Aspose.HTML pro .NET nastavit a měnit styly písma v HTML dokumentech pomocí C#. ## Závěr diff --git a/html/czech/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/czech/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..734c5955e --- /dev/null +++ b/html/czech/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Aplikujte styl písma programově a naučte se, jak odstranit podtržení + z textu, změnit styl textu a nastavit tučný text programově v stručném tutoriálu. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: cs +og_description: Aplikujte styl písma programově a objevte, jak odstranit podtržení + z textu, změnit styl textu a nastavit tučný text programově v krátkém praktickém + tutoriálu. +og_title: Aplikovat styl písma programově – Rychlý průvodce C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Aplikovat styl písma programově – rychlý průvodce C# +url: /cs/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Použití stylu písma programově – Rychlý průvodce C# + +Už jste někdy potřebovali **aplikovat styl písma** na UI prvek, ale nevedeli jste, kde začít? Nejste v tom sami — většina vývojářů narazí na tento problém, když poprvé experimentuje s dynamickým formátováním textu. Dobrá zpráva? Za pár minut budete přesně vědět, jak změnit vzhled popisku, odstranit podtržení z textu a nastavit tučný text programově, aniž byste museli prohledávat nekonečné dokumentace. + +V tomto **návodu na formátování textu** projdeme kompletním, spustitelným příkladem, vysvětlíme „proč“ za každým řádkem a přidáme praktické tipy, které můžete zkopírovat‑vložit do jakéhokoli projektu WinForms nebo WPF. Žádné zbytečnosti, jen to, co skutečně funguje. + +--- + +## Co se naučíte + +- Jak **aplikovat styl písma** pomocí malého pomocného třídy. +- Přesné kroky k **odstranění podtržení z textu** při zachování ostatních stylů. +- Způsoby, jak **změnit styl textu** (tučný, kurzíva, podtržení) za běhu. +- Kompletní, připravený úryvek kódu, který **nastavuje tučný text programově**. +- Běžné úskalí a řešení okrajových případů, aby vás nic nepřekvapilo. + +**Požadavky:** .NET 6+ (nebo jakýkoli novější .NET Framework), základní znalost C# a IDE dle výběru (Visual Studio, Rider nebo VS Code). To je vše — žádné další NuGet balíčky nejsou potřeba. + +--- + +## Krok 1 – Aplikujte styl písma na svůj ovládací prvek + +Jádrem každé operace **aplikovat styl písma** je výčet `FontStyle` kombinovaný s objektem `Font`. Aby byl kód přehledný, zabalíme logiku výčtu do malé třídy `WebFontStyle`. Tato třída odráží vlastnosti, které jste viděli v původním úryvku (`Bold`, `Italic`, `Underline`) a vytváří hodnotu `FontStyle`, kterou můžete předat `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Proč je to důležité:** +Izolací logiky sestavování příznaků se vyhnete rozptylování bitových operací `|` po celém UI kódu. Je to čitelnější, lépe testovatelné a — co je nejdůležitější — dělá záměr **aplikovat styl písma** naprosto jasným. + +--- + +## Krok 2 – Odstraňte podtržení z textu (a zachovejte ostatní styly) + +Předpokládejme, že jste zdědili popisek, který už je podtržený, ale design vyžaduje prostý tučný text. Nechcete ztratit tučnost při odstraňování podtržení. Zde se `WebFontStyle` třída ukáže jako užitečná. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Klíčový bod:** Nastavením `Underline = false` výslovně říkáte pomocníku, aby *vyloučil* příznak podtržení. Kdybyste tento řádek vynechali, předchozí podtržení by přetrvalo, což je častý zdroj chyb, když vývojáři mění jen vlastnost `Bold`. + +--- + +## Krok 3 – Změna stylu textu: tučný, kurzíva a další + +Možná se ptáte: „Co když potřebuji také přepínat kurzívu?“ Stejný objekt funguje pro libovolnou kombinaci. Níže je rychlá matice, kterou můžete při kódování použít. + +| Požadovaný styl | `Bold` | `Italic` | `Underline` | +|-----------------|--------|----------|-------------| +| **Bold only** | true | false | false | +| *Italic only* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +Stačí nastavit potřebné vlastnosti a zavolat `ToFont`. Pomocník udělá těžkou práci za vás, takže se můžete soustředit na logiku UI. + +--- + +## Kompletní příklad – Nastavte tučný text programově + +Níže je **kompletní, spustitelný WinForms** příklad, který demonstruje vše, co jsme probírali. Vložte jej do nového projektu WinForms typu console a stiskněte **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Očekávaný výsledek + +Po spuštění programu se objeví okno s textem **„Hello, world!“** vykresleným **tučně**, **nekurzívou** a **bez podtržení**. Tento vizuální výstup potvrzuje, že logika **aplikovat styl písma** funguje perfektně. + +--- + +## Profesionální tipy a okrajové případy + +- **Dynamické aktualizace:** Pokud potřebujete změnit styl po zobrazení formuláře (např. v reakci na zaškrtávací políčko), stačí znovu vytvořit instanci `WebFontStyle` nebo upravit její vlastnosti a přiřadit `lbl.Font` znovu. UI se aktualizuje okamžitě. +- **Úvahy o vysokém DPI:** Když nahradíte objekt `Font`, Windows jej automaticky škáluje podle aktuálního DPI. Žádný další kód není potřeba, pokud sami neřešíte vlastní škálování. +- **Ekvivalent pro WPF:** Ve WPF byste svázali `FontWeight`, `FontStyle` a `TextDecorations` místo výměny objektu `Font`. Stejný logický oddělení platí — udržujte logiku stylu mimo vrstvu zobrazení. +- **Prevence úniků paměti:** Při přiřazování `Label.Font` se vytváří nový objekt `Font`. Starý objekt uvolněte, pokud často měníte styly: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Závěr + +Nyní umíte **aplikovat styl písma** na libovolný .NET ovládací prvek, **odstranit podtržení z textu** a **měnit styl textu** za běhu — a to vše s čistým a znovupoužitelným kódem. Malý pomocník `WebFontStyle` promění pár booleanových příznaků na solidní, testovatelnou komponentu a celý příklad dokazuje, že **nastavit tučný text programově** jde během několika řádků. + +Co dál? Zkuste tento přístup spojit s nastavením řízeným uživatelem, nebo experimentujte s dalšími příznaky `FontStyle`, jako je `Strikeout`. Můžete dokonce vytvořit malé UI panel, který umožní netechnickým uživatelům během běhu vybrat tučné, kurzívu nebo podtržení — bez nutnosti rekompilace. + +Pokud se vám tento **návod na formátování textu** líbil, neváhejte zanechat komentář nebo sdílet své vlastní variace. Šťastné kódování a ať vaše UI vždy vypadá přesně tak, jak jste zamýšleli! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/czech/net/html-extensions-and-conversions/_index.md index dc8f6f072..6ad07dbbd 100644 --- a/html/czech/net/html-extensions-and-conversions/_index.md +++ b/html/czech/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Naučte se vytvořit HTML dokument se stylovaným textem a převést jej do PDF Naučte se, jak uložit HTML soubor jako ZIP archiv pomocí Aspose.HTML pro .NET v kompletním C# tutoriálu. ### [Uložte HTML do ZIP v C# – Kompletní příklad v paměti](./save-html-to-zip-in-c-complete-in-memory-example/) Naučte se, jak uložit HTML soubor do ZIP archivu v paměti pomocí Aspose.HTML pro .NET v C#. +### [Jak zkomprimovat HTML v C# – průvodce vlastním handlerem zdrojů](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Naučte se, jak pomocí Aspose.HTML v C# vytvořit vlastní resource handler pro kompresi HTML do ZIP. ## Závěr diff --git a/html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..39e3a2b04 --- /dev/null +++ b/html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Naučte se, jak zkomprimovat HTML v C# pomocí vlastního resource handleru + – krok za krokem návod, jak uložit HTML jako ZIP, převést HTML na ZIP a vytvořit + ZIP z HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: cs +og_description: 'Jak zabalit HTML do ZIP v C# vysvětleno: použijte vlastní handler + zdrojů k uložení HTML jako ZIP, převod HTML na ZIP a vytvoření ZIP z HTML během + několika minut.' +og_title: Jak zipovat HTML v C# – Průvodce vlastním handlerem zdrojů +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: Jak zipovat HTML v C# – průvodce vlastním handlerem zdrojů +url: /cs/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# jak zipovat html v C# – průvodce vlastním resource handlerem + +Už jste se někdy zamýšleli **jak zipovat html** přímo z vašeho C# kódu, aniž byste nejprve zapisovali soubory na disk? Nejste v tom sami. Mnoho vývojářů narazí na problém, když potřebují zabalit HTML stránku spolu s jejími CSS, obrázky a fonty pro offline distribuci, a končí tím, že píší ad‑hoc kód pracující se souborovým systémem, který se rychle mění v noční můru údržby. + +V tomto tutoriálu vyřešíme tento problém tím, že vám ukážeme čistý, znovupoužitelný přístup, který **ukládá HTML jako ZIP archiv** pomocí `ResourceHandler` z Aspose.HTML. Dotkneme se také toho, **jak převést HTML do ZIP**, a dokonce předvedeme vzor, který můžete znovu použít k **vytvoření ZIP z HTML** v jakémkoli .NET projektu. Žádné externí skripty, žádné dočasné složky – jen čistý C#. + +Na konci tohoto průvodce budete mít připravený ukázkový projekt, který vytvoří `result.zip` obsahující všechny propojené zdroje, plus několik praktických tipů, které můžete aplikovat ve svých projektech. + +## Požadavky + +- .NET 6+ (kód funguje také na .NET Framework 4.7.2, ale doporučujeme nejnovější SDK) +- NuGet balíček Aspose.HTML for .NET (`Aspose.HTML`) – nainstalujte pomocí `dotnet add package Aspose.HTML` +- Základní znalost streamů a jmenného prostoru `System.IO.Compression` +- IDE nebo editor dle vašeho výběru (Visual Studio, VS Code, Rider…) + +Pokud už máte všechny tyto komponenty, skvěle – rovnou přejděme k kódu. Pokud ne, jediný další krok je jednorázová instalace NuGet balíčku; vše ostatní je obsaženo v průvodci. + +## Krok 1: Vytvořte jednoduchý HTML dokument v paměti + +Nejprve potřebujeme objekt `HTMLDocument`, který představuje stránku, kterou chceme zipovat. Ve skutečném scénáři byste jej mohli načíst z URL nebo souboru, ale pro přehlednost vytvoříme malý dokument přímo v kódu. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Proč je to důležité:** +> Držením dokumentu v paměti se vyhneme jakémukoli mezilehlému souborovému I/O, což činí následný krok **convert html to zip** rychlým a thread‑safe. + +## Krok 2: Připravte in‑memory ZIP stream + +Místo zápisu do dočasného souboru `.zip` na disku použijeme `MemoryStream`. To vše drží v RAM, což je ideální pro webové služby nebo background úlohy, které potřebují archiv vrátit přímo klientovi. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** `using` blok zajišťuje automatické uvolnění streamu, čímž předchází únikům paměti. + +## Krok 3: Implementujte vlastní ResourceHandler + +Aspose.HTML volá `ResourceHandler` pro každý externí asset, který objeví (CSS soubory, obrázky, fonty atd.). Děděním z `ResourceHandler` můžeme přesně určit, kam každý zdroj skončí – v našem případě jako položka uvnitř ZIP archivu. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Proč vlastní handler? + +- **Kontrola nad pojmenováním** – rozhodnete, jak se každý soubor objeví v archivu. +- **Žádné dočasné soubory** – handler zapisuje přímo do in‑memory ZIP. +- **Znovupoužitelnost** – můžete tuto třídu vložit do libovolného projektu, který potřebuje **save html as zip**. + +## Krok 4: Uložte HTML dokument pomocí handleru + +Nyní vše spojíme. Metoda `Save` zavolá `HandleResource` pro každý propojený asset a handler pošle tyto bajty do ZIP archivu, který jsme vytvořili dříve. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Co se děje pod kapotou?** +> Aspose analyzuje HTML, najde odkaz ``, požádá handler o stream a handler vytvoří položku `logo.png` uvnitř ZIP. Stejný postup se opakuje pro CSS, fonty nebo jakýkoli jiný externí zdroj. + +## Krok 5: Uložte ZIP archiv na disk (nebo jej vraťte) + +Nakonec zapíšeme in‑memory archiv do souboru. Ve webovém API můžete místo toho vrátit `zipMemoryStream.ToArray()` jako pole bajtů. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Očekávaný výsledek + +Otevřete `result.zip` a uvidíte: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Pokud jste archiv otevřeli ve správci souborů, všimnete si, že HTML soubor je uložen jako `resource.bin`, protože jsme mu nedali přátelské jméno. To lze snadno vylepšit kontrolou `resourceInfo.ContentType` a při vhodné příležitosti přiřadit příponu `.html`. + +## Kompletní funkční příklad + +Níže je kompletní program připravený ke zkopírování a vložení, který zahrnuje všechny výše popsané kroky. Spusťte jej z konzolové aplikace a získáte připravený ZIP soubor k sdílení. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Spuštěním tohoto kódu** vygenerujete `result.zip` v pracovním adresáři programu. Otevřete jej a najdete `index.html` (naše původní stránka) plus `logo.png`, pokud tento obrázek existoval na disku nebo byl stažen z URL. + +## Běžné varianty a okrajové případy + +| Scénář + +{{< /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/generate-jpg-and-png-images/_index.md b/html/dutch/net/generate-jpg-and-png-images/_index.md index e05f0c0a7..77046112a 100644 --- a/html/dutch/net/generate-jpg-and-png-images/_index.md +++ b/html/dutch/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Leer hoe u Aspose.HTML voor .NET kunt gebruiken om HTML-documenten te bewerken, Leer hoe u antialiasing inschakelt bij het omzetten van DOCX-bestanden naar PNG- of JPG-afbeeldingen met Aspose.HTML. ### [docx naar png converteren – zip-archief maken C#-tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Leer hoe u een DOCX-bestand naar PNG converteert en de resultaten in een zip-archief opslaat met C# en Aspose.HTML. +### [PNG maken vanuit HTML – Stapsgewijze gids voor C#-ontwikkelaars](./create-png-from-html-step-by-step-guide-for-c-developers/) +Leer hoe u PNG-afbeeldingen genereert vanuit HTML met een stapsgewijze handleiding voor C#-ontwikkelaars. ## Conclusie diff --git a/html/dutch/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/dutch/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..12846a2b3 --- /dev/null +++ b/html/dutch/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Maak snel PNG's van HTML met Aspose.HTML. Leer hoe je HTML naar PNG rendert, + de canvasgrootte instelt, een achtergrondkleur toevoegt en de gerenderde afbeelding + binnen enkele minuten opslaat. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: nl +og_description: Maak PNG van HTML met Aspose.HTML. Deze gids laat zien hoe je HTML + naar PNG rendert, de canvasgrootte instelt, een achtergrondkleur toevoegt en de + gerenderde afbeelding opslaat. +og_title: Maak PNG van HTML – Complete C# Rendering Tutorial +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Maak PNG van HTML – Stapsgewijze gids voor C#‑ontwikkelaars +url: /nl/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak PNG van HTML – Complete C# Rendering Tutorial + +Heb je ooit **PNG van HTML maken** moeten, maar wist je niet welke bibliotheek je scherpe, anti‑aliased resultaten geeft? Je bent niet de enige. In veel web‑naar‑afbeelding pipelines is het grootste pijnpunt het krijgen van tekst en grafische elementen die net zo scherp zijn als in de browser. + +Het goede nieuws? Met Aspose.HTML kun je **HTML renderen naar PNG** in een handvol regels, de canvasgrootte regelen, een effen achtergrondkleur toevoegen, en uiteindelijk **de gerenderde afbeelding opslaan** op schijf — zonder een browser aan te raken. In deze tutorial lopen we het volledige proces door, leggen we uit waarom elke instelling belangrijk is, en laten we je een kant‑klaar voorbeeld zien. + +## Wat je zult leren + +- Hoe je HTML laadt vanuit een string, bestand of URL +- Hoe je **canvasgrootte instelt** en **achtergrondkleur toevoegt** voor voorspelbare output +- Antialiasing en sub‑pixel tekst hinting inschakelen voor haarscherpe koppen +- De exacte stappen om **de gerenderde afbeelding op te slaan** als een PNG‑bestand +- Veelvoorkomende valkuilen en optionele aanpassingen voor verschillende scenario's + +Ervaring met Aspose.HTML is niet vereist; alleen een basis C#‑setup en Visual Studio (of je favoriete IDE). + +--- + +## Stap 1: Installeer Aspose.HTML voor .NET + +Voordat we code schrijven, zorg ervoor dat het Aspose.HTML NuGet‑pakket in je project is opgenomen. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Gebruik de nieuwste stabiele versie (vanaf april 2026, 23.9.0) om de nieuwste rendering engine en bugfixes te krijgen. + +--- + +## Stap 2: Laad de HTML-bron – Maak PNG van HTML + +Je kunt de renderer een inline string, een lokaal bestand of een externe URL geven. Voor deze demo gebruiken we een eenvoudige inline string die een kop bevat met een aangepast lettertype. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Waarom dit belangrijk is:** Het laden van HTML in een `HTMLDocument` geeft de engine volledige controle over DOM‑parsing, CSS‑cascade en lay‑outberekeningen. Het isert ook de rendering van elke externe browser‑status, waardoor reproduceerbare resultaten worden gegarandeerd. + +--- + +## Stap 3: Configureer Rendering‑opties – Stel Canvasgrootte in & Voeg Achtergrondkleur toe + +De `ImageRenderingOptions`‑klasse laat je de uitvoerafbeelding fijn afstemmen. Hier schakelen we antialiasing in, stellen we een witte achtergrond in, en definiëren we expliciet een canvas van **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Waarom je deze waarden zou kunnen aanpassen:** +- **Canvasgrootte:** Als je een thumbnail nodig hebt, verklein je de afmetingen; voor hoge‑resolutie‑afdrukken vergroot je ze. +- **Achtergrondkleur:** Transparante PNG’s zijn mogelijk, maar veel downstream‑tools (bijv. PowerPoint) verwachten een ondoorzichtige achtergrond. + +--- + +## Stap 4: Render en **de gerenderde afbeelding opslaan** als PNG + +Nu gebeurt het zware werk. De `ImageRenderer` verwerkt het `HTMLDocument` en de opties die we zojuist hebben gedefinieerd, en schrijft vervolgens een PNG‑stroom naar schijf. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Wanneer je het programma uitvoert, vind je `result.png` op je bureaublad. Open het bestand en je zou een nette, antialiased kop moeten zien die gecentreerd staat op een wit canvas. + +> **Verwachte output:** Een 800 × 600 PNG met een witte achtergrond en de tekst “Antialiased Heading” gerenderd in Arial, net zo glad als in Chrome. + +--- + +## Stap 5: Verifieer het Resultaat – Snelle Controles + +1. **Bestand bestaat:** `File.Exists(outputPath)` moet `true` retourneren. +2. **Afmetingen:** Open de PNG in een beeldviewer; deze moet 800 × 600 px rapporteren. +3. **Visuele kwaliteit:** Zoom in tot 200 % – de tekstranden moeten glad blijven, niet gekarteld. + +Als er iets niet klopt, controleer dan of `UseAntialiasing` en `UseHinting` beide op `true` staan. Die twee vlaggen vormen de geheime saus voor hoogwaardige rendering. + +--- + +## Veelvoorkomende Variaties & Randgevallen + +| Scenario | Wat aan te passen | Waarom | +|----------|-------------------|--------| +| **Render een externe webpagina** | Vervang `new HTMLDocument(htmlContent)` door `new HTMLDocument("https://example.com")` | Hiermee kun je live sites vastleggen zonder HTML handmatig te kopiëren. | +| **Transparante achtergrond** | Stel `BackgroundColor = Color.Transparent` in en gebruik `ImageFormat.Png` | Handig om de PNG over andere grafische elementen te leggen. | +| **Ander afbeeldingsformaat** | Verander `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG kan kleiner zijn voor fotografische inhoud, maar verliest lossless kwaliteit. | +| **Dynamische canvasgrootte** | Gebruik `imgOptions.Width = htmlDoc.Body.ClientWidth;` na layout | Laat de afbeelding overeenkomen met de natuurlijke breedte van de HTML‑inhoud. | +| **High‑DPI output** | Vermenigvuldig `Width` en `Height` met een schaalfactor (bijv. 2) | Genereert retina‑klare assets voor moderne displays. | + +--- + +## Volledig Werkend Voorbeeld (Kopieer‑en‑Plak Klaar) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Voer het programma uit (`dotnet run` of druk op F5 in Visual Studio) en je hebt een perfect gerenderde PNG klaar voor gebruik in e‑mails, rapporten, of elke andere plek waar je een statische afbeelding van HTML nodig hebt. + +--- + +## Veelgestelde Vragen + +**V: Werkt dit met CSS 3‑functies zoals flexbox?** +A: Ja. Aspose.HTML ondersteunt de meeste moderne CSS, inclusief flexbox, grid en media queries. Zorg er alleen voor dat je de nieuwste bibliotheekversie gebruikt. + +**V: Wat als mijn HTML externe afbeeldingen verwijst?** +A: De renderer volgt relatieve URL’s op basis van de basis‑URI van het document. Als je HTML vanuit een string laadt, stel dan `doc.BaseUrl` in op de map die de assets bevat. + +**V: Kan ik meerdere pagina’s in één PNG renderen?** +A: Niet direct — elke `ImageRenderer`‑aanroep produceert één rasterafbeelding. Voor multi‑page output render je elke pagina apart en plak je ze vervolgens aan elkaar met een grafische bibliotheek (bijv. ImageSharp). + +--- + +## Conclusie + +Je hebt nu een solide, end‑to‑end oplossing om **PNG van HTML maken** te gebruiken met Aspose.HTML. Door **render html to png**‑opties te configureren — zoals **canvasgrootte instellen**, **achtergrondkleur toevoegen**, en antialiasing inschakelen — kun je professionele afbeeldingen genereren zonder een browser. + +Vanaf hier kun je experimenteren met hogere DPI, transparante achtergronden, of batch‑verwerking van tientallen HTML‑fragmenten. Hetzelfde patroon geldt of je nu een thumbnail‑service, een PDF‑generatie‑pipeline, of een statische site‑preview‑tool bouwt. + +Veel renderplezier, en laat gerust een reactie achter als je ergens tegenaan loopt! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/dutch/net/html-document-manipulation/_index.md index 0639685af..ae4a4fcb5 100644 --- a/html/dutch/net/html-document-manipulation/_index.md +++ b/html/dutch/net/html-document-manipulation/_index.md @@ -51,7 +51,7 @@ Aspose.HTML voor .NET valt op door zijn eenvoud en kracht. Het geeft u de volled ## Handleidingen voor het manipuleren van HTML-documenten ### [Laad HTML-documenten asynchroon in .NET met Aspose.HTML](./load-html-doc-asynchronously/) Leer hoe u Aspose.HTML voor .NET gebruikt om met HTML-documenten te werken. Stapsgewijze handleiding met voorbeelden en FAQ's voor ontwikkelaars. -### [Laad HTML-documenten met referenties in .NET met Aspose.HTML](./load-html-doc-with-credentials/) +### [Laad HTML-documenten met referenties in .NET met Aspose.HTML](./load-html-with-credentials/) Ontdek hoe u uw SEO een boost kunt geven met Aspose.HTML voor .NET. Verbeter rankings, analyseer webcontent en optimaliseer voor zoekmachines. ### [HTML laden met behulp van een externe server in .NET met Aspose.HTML](./load-html-using-remote-server/) Ontgrendel het potentieel van Aspose.HTML voor .NET met onze uitgebreide gids. Leer hoe u naamruimten importeert, externe HTML-documenten opent en meer. @@ -71,6 +71,8 @@ Leer dynamische en webinhoud te maken met Aspose.HTML voor .NET. Versterk uw onl Leer Aspose.HTML voor .NET gebruiken. Importeer namespace, voeg HTML samen met XML en verbeter uw webontwikkelingsvaardigheden met deze uitgebreide gids. ### [Genereer XPS-documenten door XpsDevice in .NET met Aspose.HTML](./generate-xps-documents-by-xpsdevice/) Ontgrendel het potentieel van webontwikkeling met Aspose.HTML voor .NET. Maak, converteer en manipuleer eenvoudig HTML-documenten. +### [Lettertype stijl toepassen via code – Snelle C#-gids](./apply-font-style-programmatically-quick-c-guide/) +Leer hoe u lettertype stijlen programmatically toepast in C# met Aspose.HTML, inclusief voorbeeldcode en stapsgewijze uitleg. ## Conclusie diff --git a/html/dutch/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/dutch/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..2eda0ae0b --- /dev/null +++ b/html/dutch/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Pas lettertype stijl programmatically toe en leer hoe je onderstreping + van tekst verwijdert, de tekststijl wijzigt en vetgedrukte tekst programmatically + instelt in een beknopte tutorial. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: nl +og_description: Pas lettertype stijl programmeerbaar toe en ontdek hoe je onderstreping + uit tekst verwijdert, tekststijl wijzigt en vetgedrukte tekst instelt in een korte, + praktische tutorial. +og_title: Lettertype stijl via code toepassen – Snelle C#‑gids +tags: +- csharp +- ui +- text-formatting +- programming +title: Lettertype stijl programmatically toepassen – Snelle C#-gids +url: /nl/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lettertype‑stijl programmatically toepassen – Snelle C#‑gids + +Heb je ooit **lettertype‑stijl** moeten toepassen op een UI‑element, maar wist je niet waar te beginnen? Je bent niet de enige—de meeste ontwikkelaars lopen tegen dit probleem aan wanneer ze voor het eerst met dynamische tekstopmaak spelen. Het goede nieuws? Over een paar minuten weet je precies hoe je het uiterlijk van een label wijzigt, onderstreping van tekst verwijdert en vetgedrukte tekst programmatically instelt zonder eindeloos door documentatie te zoeken. + +In deze **tekst‑opmaak‑tutorial** lopen we een volledig, uitvoerbaar voorbeeld door, leggen we het “waarom” achter elke regel uit, en strooien we praktische tips die je kunt copy‑pasten in elk WinForms‑ of WPF‑project. Geen poespas, alleen de zaken die het werk doen. + +--- + +## Wat je gaat leren + +- Hoe je **lettertype‑stijl** toepast met een kleine helper‑klasse. +- De precieze stappen om **onderstreping van tekst** te **verwijderen** terwijl andere stijlen behouden blijven. +- Manieren om **tekststijl** (vet, cursief, onderstrepen) on‑the‑fly te wijzigen. +- Een volledige, copy‑ready snippet die **vetgedrukte tekst programmatically** instelt. +- Veelvoorkomende valkuilen en edge‑case‑afhandeling zodat je later niet voor verrassingen komt te staan. + +**Prerequisites:** .NET 6+ (of een recente .NET Framework), basiskennis van C#, en een IDE naar keuze (Visual Studio, Rider, of VS Code). Dat is alles—geen extra NuGet‑pakketten nodig. + +--- + +## Stap 1 – Lettertype‑stijl toepassen op je controle + +De kern van elke **apply font style**‑operatie is een `FontStyle`‑enum gecombineerd met een `Font`‑object. Om de code overzichtelijk te houden, wikkelen we de enum‑logica in een kleine `WebFontStyle`‑klasse. Deze klasse spiegelt de eigenschappen die je in het oorspronkelijke fragment zag (`Bold`, `Italic`, `Underline`) en bouwt een `FontStyle`‑waarde die je aan `Font` kunt doorgeven. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Waarom dit belangrijk is:** +Door de flag‑bouwlogica te isoleren, vermijd je dat je bitwise `|`‑operaties door je UI‑code verspreidt. Het is makkelijker leesbaar, makkelijker te testen, en—het belangrijkste—maakt de **apply font style**‑intentie glashelder. + +--- + +## Stap 2 – Onderstreping van tekst verwijderen (en andere stijlen behouden) + +Stel, je hebt een label geërfd dat al onderstreept is, maar het ontwerp vraagt om gewone vetgedrukte tekst. Je wilt de vetgedruktheid niet verliezen terwijl je de onderstreping verwijdert. Hier komt de `WebFontStyle`‑klasse van pas. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Kernpunt:** Het expliciet instellen van `Underline = false` vertelt de helper om de onderstrepings‑flag *uit te sluiten*. Als je die regel weglaten, blijft de eerdere onderstreping bestaan, wat een veelvoorkomende bron van bugs is wanneer ontwikkelaars alleen de `Bold`‑eigenschap toggelen. + +--- + +## Stap 3 – Tekststijl wijzigen: Vet, Cursief en meer + +Je vraagt je misschien af: “Wat als ik ook cursief moet toggelen?” Hetzelfde object werkt voor elke combinatie. Hieronder vind je een snel overzicht dat je kunt raadplegen tijdens het coderen. + +| Gewenste stijl | `Bold` | `Italic` | `Underline` | +|----------------|--------|----------|-------------| +| **Alleen vet** | true | false | false | +| *Alleen cursief* | false | true | false | +| **Vet + Cursief** | true | true | false | +| **Vet + Onderstrepen** | true | false | true | + +Stel simpelweg de eigenschappen in die je nodig hebt en roep `ToFont` aan. De helper doet het zware werk voor je, zodat jij je kunt concentreren op de UI‑logica. + +--- + +## Volledig voorbeeld – Vetgedrukte tekst programmatically instellen + +Hieronder staat een **volledig, uitvoerbaar WinForms**‑voorbeeld dat alles laat zien wat we hebben behandeld. Plak het in een nieuw console‑style WinForms‑project en druk op **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Verwacht resultaat + +Wanneer je het programma uitvoert, verschijnt er een venster met de tekst **“Hello, world!”** weergegeven **vet**, **niet cursief**, en **zonder onderstreping**. Die visuele bevestiging laat zien dat de **apply font style**‑logica perfect heeft gewerkt. + +--- + +## Pro‑tips & Edge Cases + +- **Dynamische updates:** Als je de stijl moet wijzigen nadat het formulier is weergegeven (bijv. als reactie op een checkbox), maak dan gewoon een nieuwe `WebFontStyle`‑instantie of wijzig de eigenschappen en wijs `lbl.Font` opnieuw toe. De UI werkt direct bij. +- **High‑DPI‑overwegingen:** Wanneer je een `Font`‑object vervangt, schaalt Windows dit automatisch op basis van de huidige DPI. Geen extra code nodig tenzij je handmatig schaalbeheer doet. +- **WPF‑equivalent:** In WPF bind je `FontWeight`, `FontStyle` en `TextDecorations` in plaats van een `Font`‑object te verwisselen. Hetzelfde logische scheidingsprincipe geldt—houd stijl‑logica buiten de view‑laag. +- **Voorkomen van geheugenlekken:** Het opnieuw toewijzen van `Label.Font` maakt een nieuw `Font`‑object aan. Dispose het oude object als je vaak stijlen verwisselt: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Conclusie + +Je weet nu hoe je **lettertype‑stijl** toepast op elk .NET‑control, **onderstreping van tekst** verwijdert, en **tekststijl** on‑the‑fly wijzigt—en dat alles terwijl je code schoon en herbruikbaar blijft. De kleine `WebFontStyle`‑helper zet een handvol booleaanse vlaggen om in een solide, testbaar component, en het volledige voorbeeld bewijst dat je **vetgedrukte tekst programmatically** kunt instellen in slechts een paar regels. + +Wat nu? Probeer deze aanpak te combineren met door de gebruiker gedreven instellingen, of experimenteer met andere `FontStyle`‑flags zoals `Strikeout`. Je kunt zelfs een klein UI‑paneel exposen waarmee niet‑technische gebruikers vet, cursief of onderstrepen kunnen kiezen tijdens runtime—zonder opnieuw te compileren. + +Als je deze **tekst‑opmaak‑tutorial** nuttig vond, laat dan een reactie achter of deel je eigen variaties. Happy coding, en moge je UI er altijd precies uitzien zoals jij het wilt! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/dutch/net/html-extensions-and-conversions/_index.md index fd924a78c..8f5206c5b 100644 --- a/html/dutch/net/html-extensions-and-conversions/_index.md +++ b/html/dutch/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Leer hoe u HTML naar TIFF converteert met Aspose.HTML voor .NET. Volg onze staps Ontdek de kracht van Aspose.HTML voor .NET: Converteer HTML moeiteloos naar XPS. Vereisten, stapsgewijze handleiding en veelgestelde vragen inbegrepen. ### [HTML zippen in C# – HTML opslaan in zip](./how-to-zip-html-in-c-save-html-to-zip/) Leer hoe u HTML-bestanden comprimeert naar een zip‑archief met C# en Aspose.HTML voor .NET. +### [HTML zippen in C# – aangepaste resourcehandler gids](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Leer hoe u een aangepaste resourcehandler implementeert om HTML-bestanden te zippen met Aspose.HTML voor .NET. ### [Maak HTML-document met opgemaakte tekst en exporteer naar PDF – Volledige gids](./create-html-document-with-styled-text-and-export-to-pdf-full/) Leer hoe u een HTML-document met opgemaakte tekst maakt en deze volledig naar PDF exporteert met Aspose.HTML voor .NET. ### [Maak PDF van HTML – C# Stapsgewijze handleiding](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..0d50d87a0 --- /dev/null +++ b/html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Leer hoe je HTML kunt zippen in C# met een aangepaste resourcehandler + – stap‑voor‑stap gids om HTML op te slaan als zip, HTML naar zip te converteren + en een zip van HTML te maken. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: nl +og_description: 'hoe html zippen in C# uitgelegd: gebruik een aangepaste resourcehandler + om html op te slaan als zip, converteer html naar zip en maak zip van html in enkele + minuten.' +og_title: Hoe HTML zippen in C# – Gids voor aangepaste resourcehandler +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: hoe HTML te zippen in C# – gids voor aangepaste resourcehandler +url: /nl/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# html zippen in C# – handleiding voor aangepaste resource‑handler + +Heb je je ooit afgevraagd **hoe je html kunt zippen** rechtstreeks vanuit je C#‑code zonder eerst bestanden naar schijf te schrijven? Je bent niet de enige. Veel ontwikkelaars lopen tegen een muur wanneer ze een HTML‑pagina moeten bundelen met de bijbehorende CSS, afbeeldingen en lettertypen voor offline distributie, en ze eindigen met ad‑hoc bestands‑systeemcode die al snel een onderhoudsmine wordt. + +In deze tutorial lossen we dat probleem op door je een schone, herbruikbare aanpak te laten zien die **HTML opslaat als een ZIP‑archief** met behulp van Aspose.HTML’s `ResourceHandler`. We behandelen ook hoe je **HTML naar ZIP kunt converteren**, en demonstreren een patroon dat je kunt hergebruiken om **ZIP vanuit HTML te maken** in elk .NET‑project. Geen externe scripts, geen tijdelijke mappen – alleen pure C#. + +Aan het einde van de gids heb je een kant‑en‑klaar voorbeeld dat een `result.zip` produceert met alle gekoppelde resources, plus een reeks praktische tips die je in je eigen projecten kunt toepassen. + +## Prerequisites + +- .NET 6+ (de code werkt ook op .NET Framework 4.7.2, maar we raden de nieuwste SDK aan) +- Aspose.HTML for .NET NuGet‑package (`Aspose.HTML`) – installeer via `dotnet add package Aspose.HTML` +- Basiskennis van streams en de `System.IO.Compression`‑namespace +- Een IDE of editor naar keuze (Visual Studio, VS Code, Rider …) + +Als je deze onderdelen al hebt, prima—laten we direct in de code duiken. Zo niet, dan is de enige extra stap een eenregelige NuGet‑installatie; de rest is zelf‑voorzien. + +## Step 1: Create a Simple HTML Document in Memory + +First we need an `HTMLDocument` object that represents the page we want to zip. In a real‑world scenario you might load this from a URL or a file, but for clarity we’ll build a tiny document inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Why this matters:** +> By keeping the document in memory we avoid any intermediate file I/O, which makes the later **convert html to zip** step fast and thread‑safe. + +## Step 2: Prepare an In‑Memory ZIP Stream + +Instead of writing a temporary `.zip` file to disk, we’ll use a `MemoryStream`. This keeps everything in RAM, ideal for web services or background jobs that need to return the archive directly to a client. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** The `using` statement ensures the stream is disposed automatically, preventing memory leaks. + +## Step 3: Implement a Custom ResourceHandler + +Aspose.HTML calls a `ResourceHandler` for every external asset it discovers (CSS files, images, fonts, etc.). By subclassing `ResourceHandler` we can decide exactly where each resource ends up—in our case, as an entry inside the ZIP archive. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Why a Custom Handler? + +- **Control over naming** – you decide how each file appears in the archive. +- **No temporary files** – the handler writes straight into the in‑memory ZIP. +- **Reusability** – you can drop this class into any project that needs to **save html as zip**. + +## Step 4: Save the HTML Document Using the Handler + +Now we tie everything together. The `Save` method will invoke `HandleResource` for every linked asset, and the handler will stream those bytes into the ZIP archive we created earlier. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **What happens under the hood?** +> Aspose parses the HTML, discovers the `` reference, asks the handler for a stream, and the handler creates a `logo.png` entry inside the ZIP. The same flow repeats for CSS, fonts, or any other external resource. + +## Step 5: Persist the ZIP Archive to Disk (or Return It) + +Finally we write the in‑memory archive to a file. In a web API you could instead return `zipMemoryStream.ToArray()` as a byte array. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Expected Result + +Open `result.zip` and you should see: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +If you opened the archive in a file explorer you’d notice that the HTML file is stored as `resource.bin` because we didn’t give it a friendly name. You can easily improve that by checking `resourceInfo.ContentType` and assigning `.html` when appropriate. + +## Full Working Example + +Below is the complete, copy‑paste‑ready program that incorporates all the steps above. Run it from a console app, and you’ll get a ready‑to‑share ZIP file. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Running this code** will generate `result.zip` in the program’s working directory. Open it and you’ll find `index.html` (our original page) plus `logo.png` if that image existed on disk or was fetched from a URL. + +## Common Variations & Edge Cases + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/english/net/generate-jpg-and-png-images/_index.md index 3cc4b6acd..a37470639 100644 --- a/html/english/net/generate-jpg-and-png-images/_index.md +++ b/html/english/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Learn to use Aspose.HTML for .NET to manipulate HTML documents, convert HTML to Learn how to enable antialiasing for sharper PNG/JPG output when converting DOCX files using Aspose.HTML for .NET. ### [convert docx to png – create zip archive c# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Learn how to convert DOCX files to PNG images and package them into a ZIP archive using C# and Aspose.HTML. +### [Create PNG from HTML – Step‑by‑Step Guide for C# Developers](./create-png-from-html-step-by-step-guide-for-c-developers/) +Step-by-step guide for C# developers to generate PNG images from HTML using Aspose.HTML. ## Conclusion diff --git a/html/english/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/english/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..5b72f0579 --- /dev/null +++ b/html/english/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-04-23 +description: Create PNG from HTML quickly with Aspose.HTML. Learn how to render HTML + to PNG, set canvas size, add background color, and save rendered image in minutes. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: en +og_description: Create PNG from HTML with Aspose.HTML. This guide shows how to render + HTML to PNG, set canvas size, add background color, and save the rendered image. +og_title: Create PNG from HTML – Complete C# Rendering Tutorial +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Create PNG from HTML – Step‑by‑Step Guide for C# Developers +url: /net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create PNG from HTML – Complete C# Rendering Tutorial + +Ever needed to **create PNG from HTML** but weren’t sure which library would give you crisp, antialiased results? You’re not alone. In many web‑to‑image pipelines the biggest pain point is getting text and graphics to look as sharp as they do in the browser. + +The good news? With Aspose.HTML you can **render HTML to PNG** in a handful of lines, control the canvas size, add a solid background color, and finally **save rendered image** to disk—all without touching a browser. In this tutorial we’ll walk through the entire process, explain why each setting matters, and show you a ready‑to‑run example. + +## What You’ll Learn + +- How to load HTML from a string, file, or URL +- How to configure **set canvas size** and **add background color** for predictable output +- Enabling antialiasing and sub‑pixel text hinting for razor‑sharp headings +- The exact steps to **save rendered image** as a PNG file +- Common pitfalls and optional tweaks for different scenarios + +No prior experience with Aspose.HTML is required; just a basic C# setup and Visual Studio (or your favorite IDE). + +--- + +## Step 1: Install Aspose.HTML for .NET + +Before we write any code, make sure the Aspose.HTML NuGet package is referenced in your project. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Use the latest stable version (as of April 2026, 23.9.0) to get the newest rendering engine and bug fixes. + +--- + +## Step 2: Load the HTML Source – Create PNG from HTML + +You can feed the renderer an inline string, a local file, or a remote URL. For this demo we’ll use a simple inline string that contains a heading with a custom font. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Why this matters:** Loading HTML into an `HTMLDocument` gives the engine full control over DOM parsing, CSS cascade, and layout calculations. It also isolates the rendering from any external browser state, ensuring reproducible results. + +--- + +## Step 3: Configure Rendering Options – Set Canvas Size & Add Background Color + +The `ImageRenderingOptions` class lets you fine‑tune the output image. Here we’ll enable antialiasing, set a white background, and explicitly define a canvas of **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Why you might change these values:** +- **Canvas size:** If you need a thumbnail, shrink the dimensions; for high‑resolution prints, increase them. +- **Background color:** Transparent PNGs are possible, but many downstream tools (e.g., PowerPoint) expect an opaque background. + +--- + +## Step 4: Render and **Save Rendered Image** as PNG + +Now the heavy lifting happens. The `ImageRenderer` consumes the `HTMLDocument` and the options we just defined, then writes a PNG stream to disk. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +When you run the program, you’ll find `result.png` on your desktop. Open it, and you should see a clean, antialiased heading centered on a white canvas. + +> **Expected output:** A 800 × 600 PNG with a white background and the text “Antialiased Heading” rendered in Arial, looking as smooth as it does in Chrome. + +--- + +## Step 5: Verify the Result – Quick Checks + +1. **File existence:** `File.Exists(outputPath)` should return `true`. +2. **Dimensions:** Open the PNG in any image viewer; it should report 800 × 600 px. +3. **Visual quality:** Zoom in to 200 % – the text edges must remain smooth, not jagged. + +If anything looks off, double‑check that `UseAntialiasing` and `UseHinting` are both set to `true`. Those two flags are the secret sauce for high‑quality rendering. + +--- + +## Common Variations & Edge Cases + +| Scenario | What to Adjust | Why | +|----------|----------------|-----| +| **Render a remote web page** | Replace `new HTMLDocument(htmlContent)` with `new HTMLDocument("https://example.com")` | Allows you to capture live sites without copying HTML manually. | +| **Transparent background** | Set `BackgroundColor = Color.Transparent` and use `ImageFormat.Png` | Useful for overlaying the PNG on other graphics. | +| **Different image format** | Change `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG may be smaller for photographic content, but loses lossless quality. | +| **Dynamic canvas size** | Use `imgOptions.Width = htmlDoc.Body.ClientWidth;` after layout | Lets the image match the natural width of the HTML content. | +| **High‑DPI output** | Multiply `Width` and `Height` by a scale factor (e.g., 2) | Generates retina‑ready assets for modern displays. | + +--- + +## Full Working Example (Copy‑Paste Ready) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Run the program (`dotnet run` or press F5 in Visual Studio) and you’ll have a perfectly rendered PNG ready for use in emails, reports, or any other place you need a static image of HTML. + +--- + +## Frequently Asked Questions + +**Q: Does this work with CSS 3 features like flexbox?** +A: Yes. Aspose.HTML supports most modern CSS, including flexbox, grid, and media queries. Just ensure you’re on the latest library version. + +**Q: What if my HTML references external images?** +A: The renderer follows relative URLs based on the document’s base URI. If you load HTML from a string, set `doc.BaseUrl` to the folder containing the assets. + +**Q: Can I render multiple pages into one PNG?** +A: Not directly—each `ImageRenderer` call produces a single raster image. For multi‑page output, render each page separately and stitch them together with a graphics library (e.g., ImageSharp). + +--- + +## Conclusion + +You now have a solid, end‑to‑end solution to **create PNG from HTML** using Aspose.HTML. By configuring **render html to png** options—such as **set canvas size**, **add background color**, and enabling antialiasing—you can generate professional‑grade images without a browser. + +From this point you might experiment with higher DPI, transparent backgrounds, or batch‑processing dozens of HTML snippets. The same pattern applies whether you’re building a thumbnail service, a PDF generation pipeline, or a static site preview tool. + +Happy rendering, and feel free to drop a comment if you hit any snags! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/english/net/html-document-manipulation/_index.md index ba25012a0..2cb9a99d6 100644 --- a/html/english/net/html-document-manipulation/_index.md +++ b/html/english/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Learn to create dynamic and web content using Aspose.HTML for .NET. Empower your Learn to use Aspose.HTML for .NET. Import namespace, merge HTML with XML, and enhance your web development skills with this comprehensive guide. ### [Generate XPS Documents by XpsDevice in .NET with Aspose.HTML](./generate-xps-documents-by-xpsdevice/) Unlock the potential of web development with Aspose.HTML for .NET. Create, convert, and manipulate HTML documents easily. +### [Apply Font Style Programmatically – Quick C# Guide](./apply-font-style-programmatically-quick-c-guide/) +Learn how to apply font styles programmatically in HTML using Aspose.HTML for .NET with a quick C# guide. ## Conclusion diff --git a/html/english/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/english/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..6ba5b22a5 --- /dev/null +++ b/html/english/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Apply font style programmatically and learn how to remove underline from + text, change text style, and set bold text programmatically in a concise tutorial. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: en +og_description: Apply font style programmatically and discover how to remove underline + from text, change text style, and set bold text programmatically in a short, practical + tutorial. +og_title: Apply Font Style Programmatically – Quick C# Guide +tags: +- csharp +- ui +- text-formatting +- programming +title: Apply Font Style Programmatically – Quick C# Guide +url: /net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Apply Font Style Programmatically – Quick C# Guide + +Ever needed to **apply font style** to a UI element but weren’t sure where to start? You’re not the only one—most developers hit that snag when they first dabble with dynamic text formatting. The good news? In just a few minutes you’ll know exactly how to change a label’s appearance, remove underline from text, and set bold text programmatically without hunting through endless docs. + +In this **text formatting tutorial** we’ll walk through a complete, runnable example, explain the “why” behind each line, and sprinkle in practical tips you can copy‑paste into any WinForms or WPF project. No fluff, just the stuff that gets the job done. + +--- + +## What You’ll Learn + +- How to **apply font style** using a tiny helper class. +- The precise steps to **remove underline from text** while keeping other styles intact. +- Ways to **change text style** (bold, italic, underline) on the fly. +- A full, copy‑ready snippet that **sets bold text programmatically**. +- Common pitfalls and edge‑case handling so you don’t get surprised later. + +**Prerequisites:** .NET 6+ (or any recent .NET Framework), basic C# knowledge, and an IDE of your choice (Visual Studio, Rider, or VS Code). That’s it—no extra NuGet packages required. + +--- + +## Step 1 – Apply Font Style to Your Control + +The core of any **apply font style** operation is a `FontStyle` enum combined with a `Font` object. To keep the code tidy we’ll wrap the enum logic inside a small `WebFontStyle` class. This class mirrors the properties you saw in the original snippet (`Bold`, `Italic`, `Underline`) and builds a `FontStyle` value you can hand to `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Why this matters:** +By isolating the flag‑building logic, you avoid sprinkling bitwise `|` operations throughout your UI code. It’s easier to read, easier to test, and—most importantly—makes the **apply font style** intent crystal clear. + +--- + +## Step 2 – Remove Underline from Text (and Keep Other Styles Intact) + +Suppose you’ve inherited a label that’s already underlined, but the design calls for plain bold text. You don’t want to lose the boldness while stripping the underline. Here’s where the `WebFontStyle` class shines. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Key point:** Setting `Underline = false` explicitly tells the helper to *exclude* the underline flag. If you omitted the line altogether the previous underline would persist, which is a common source of bugs when developers only toggle the `Bold` property. + +--- + +## Step 3 – Change Text Style: Bold, Italic, and More + +You might wonder, “What if I need to toggle italic as well?” The same object works for any combination. Below is a quick matrix you can reference while coding. + +| Desired Style | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **Bold only** | true | false | false | +| *Italic only* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +Just set the properties you need and call `ToFont`. The helper does the heavy lifting for you, so you can focus on the UI logic. + +--- + +## Full Example – Set Bold Text Programmatically + +Below is a **complete, runnable WinForms** example that demonstrates everything we’ve covered. Paste it into a new console‑style WinForms project and hit **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Expected Result + +When you run the program, a window appears with the text **“Hello, world!”** rendered **bold**, **not italic**, and **without any underline**. That visual confirmation tells you the **apply font style** logic worked perfectly. + +--- + +## Pro Tips & Edge Cases + +- **Dynamic updates:** If you need to change the style after the form is shown (e.g., in response to a checkbox), just recreate the `WebFontStyle` instance or modify its properties and reassign `lbl.Font`. The UI updates instantly. +- **High‑DPI considerations:** When you replace a `Font` object, Windows automatically scales it based on the current DPI. No extra code needed unless you’re manually handling scaling. +- **WPF equivalent:** In WPF you’d bind `FontWeight`, `FontStyle`, and `TextDecorations` instead of swapping a `Font` object. The same logical separation applies—keep style logic out of the view layer. +- **Avoiding memory leaks:** Reassigning `Label.Font` creates a new `Font` object. Dispose of the old one if you’re swapping styles frequently: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Conclusion + +You now know how to **apply font style** to any .NET control, **remove underline from text**, and **change text style** on the fly—all while keeping your code clean and reusable. The tiny `WebFontStyle` helper turns a handful of boolean flags into a solid, testable component, and the full example proves you can **set bold text programmatically** in just a few lines. + +What’s next? Try combining this approach with user‑driven settings, or experiment with other `FontStyle` flags like `Strikeout`. You could even expose a tiny UI panel that lets non‑technical users pick bold, italic, or underline at runtime—no recompilation required. + +If you found this **text formatting tutorial** helpful, feel free to drop a comment or share your own variations. Happy coding, and may your UI always look exactly the way you intended! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/english/net/html-extensions-and-conversions/_index.md index a50bc9ccb..66f4a898b 100644 --- a/html/english/net/html-extensions-and-conversions/_index.md +++ b/html/english/net/html-extensions-and-conversions/_index.md @@ -67,6 +67,8 @@ Learn how to convert HTML to TIFF with Aspose.HTML for .NET. Follow our step-by- Discover the power of Aspose.HTML for .NET: Convert HTML to XPS effortlessly. Prerequisites, step-by-step guide, and FAQs included. ### [How to Zip HTML in C# – Save HTML to Zip](./how-to-zip-html-in-c-save-html-to-zip/) Learn how to zip HTML files in C# using Aspose.HTML, saving HTML content to a ZIP archive with step-by-step guidance. +### [how to zip html in C# – custom resource handler guide](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Learn how to zip HTML using a custom resource handler in C# with Aspose.HTML for .NET. ### [Create HTML Document with Styled Text and Export to PDF – Full Guide](./create-html-document-with-styled-text-and-export-to-pdf-full/) Learn how to create an HTML document with styled text and export it to PDF using Aspose.HTML for .NET in this comprehensive guide. ### [Save HTML as ZIP – Complete C# Tutorial](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..93f4a91b0 --- /dev/null +++ b/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-23 +description: Learn how to zip html in C# using a custom resource handler – step‑by‑step + guide to save html as zip, convert html to zip, and create zip from html. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: en +og_description: 'how to zip html in C# explained: use a custom resource handler to + save html as zip, convert html to zip, and create zip from html in minutes.' +og_title: how to zip html in C# – Custom Resource Handler Guide +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: how to zip html in C# – custom resource handler guide +url: /net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# how to zip html in C# – custom resource handler guide + +Ever wondered **how to zip html** directly from your C# code without pulling files onto disk first? You're not alone. Many developers hit a wall when they need to package an HTML page together with its CSS, images, and fonts for offline distribution, and they end up writing ad‑hoc file‑system code that quickly becomes a maintenance nightmare. + +In this tutorial we’ll solve that problem by showing you a clean, reusable approach that **saves HTML as a ZIP archive** using Aspose.HTML’s `ResourceHandler`. We'll also touch on how to **convert HTML to ZIP**, and even demonstrate a pattern you can reuse to **create ZIP from HTML** in any .NET project. No external scripts, no temporary folders—just pure C#. + +By the end of the guide you’ll have a ready‑to‑run sample that produces a `result.zip` containing every linked resource, plus a handful of practical tips you can apply to your own projects. + +## Prerequisites + +- .NET 6+ (the code also works on .NET Framework 4.7.2, but we recommend the latest SDK) +- Aspose.HTML for .NET NuGet package (`Aspose.HTML`) – install via `dotnet add package Aspose.HTML` +- Basic familiarity with streams and the `System.IO.Compression` namespace +- An IDE or editor of your choice (Visual Studio, VS Code, Rider…) + +If you already have these pieces in place, great—let’s jump straight into the code. If not, the only extra step is a one‑line NuGet install; everything else is self‑contained. + +## Step 1: Create a Simple HTML Document in Memory + +First we need an `HTMLDocument` object that represents the page we want to zip. In a real‑world scenario you might load this from a URL or a file, but for clarity we’ll build a tiny document inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Why this matters:** +> By keeping the document in memory we avoid any intermediate file I/O, which makes the later **convert html to zip** step fast and thread‑safe. + +## Step 2: Prepare an In‑Memory ZIP Stream + +Instead of writing a temporary `.zip` file to disk, we’ll use a `MemoryStream`. This keeps everything in RAM, ideal for web services or background jobs that need to return the archive directly to a client. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** The `using` statement ensures the stream is disposed automatically, preventing memory leaks. + +## Step 3: Implement a Custom ResourceHandler + +Aspose.HTML calls a `ResourceHandler` for every external asset it discovers (CSS files, images, fonts, etc.). By subclassing `ResourceHandler` we can decide exactly where each resource ends up—in our case, as an entry inside the ZIP archive. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Why a Custom Handler? + +- **Control over naming** – you decide how each file appears in the archive. +- **No temporary files** – the handler writes straight into the in‑memory ZIP. +- **Reusability** – you can drop this class into any project that needs to **save html as zip**. + +## Step 4: Save the HTML Document Using the Handler + +Now we tie everything together. The `Save` method will invoke `HandleResource` for every linked asset, and the handler will stream those bytes into the ZIP archive we created earlier. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **What happens under the hood?** +> Aspose parses the HTML, discovers the `` reference, asks the handler for a stream, and the handler creates a `logo.png` entry inside the ZIP. The same flow repeats for CSS, fonts, or any other external resource. + +## Step 5: Persist the ZIP Archive to Disk (or Return It) + +Finally we write the in‑memory archive to a file. In a web API you could instead return `zipMemoryStream.ToArray()` as a byte array. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Expected Result + +Open `result.zip` and you should see: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +If you opened the archive in a file explorer you’d notice that the HTML file is stored as `resource.bin` because we didn’t give it a friendly name. You can easily improve that by checking `resourceInfo.ContentType` and assigning `.html` when appropriate. + +## Full Working Example + +Below is the complete, copy‑paste‑ready program that incorporates all the steps above. Run it from a console app, and you’ll get a ready‑to‑share ZIP file. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Running this code** will generate `result.zip` in the program’s working directory. Open it and you’ll find `index.html` (our original page) plus `logo.png` if that image existed on disk or was fetched from a URL. + +## Common Variations & Edge Cases + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/french/net/generate-jpg-and-png-images/_index.md index 59ca2dad1..4e87bfe73 100644 --- a/html/french/net/generate-jpg-and-png-images/_index.md +++ b/html/french/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Apprenez à utiliser Aspose.HTML pour .NET pour manipuler des documents HTML, co Apprenez à activer l'anticrénelage pour améliorer la qualité des images PNG/JPG générées à partir de documents DOCX avec Aspose.HTML. ### [Convertir docx en png – créer une archive zip tutoriel C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) Apprenez à convertir des fichiers DOCX en images PNG et à les compresser dans une archive ZIP avec C#. +### [Créer un PNG à partir de HTML – Guide étape par étape pour les développeurs C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Apprenez à convertir du HTML en image PNG avec un guide détaillé pour les développeurs C#. ## Conclusion diff --git a/html/french/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/french/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..3022be4f0 --- /dev/null +++ b/html/french/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Créez un PNG à partir de HTML rapidement avec Aspose.HTML. Apprenez comment + rendre le HTML en PNG, définir la taille du canevas, ajouter une couleur d'arrière-plan + et enregistrer l'image rendue en quelques minutes. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: fr +og_description: Créer un PNG à partir de HTML avec Aspose.HTML. Ce guide montre comment + rendre le HTML en PNG, définir la taille du canevas, ajouter une couleur d'arrière-plan + et enregistrer l'image rendue. +og_title: Créer un PNG à partir de HTML – Tutoriel complet de rendu C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Créer un PNG à partir de HTML – Guide étape par étape pour les développeurs + C# +url: /fr/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un PNG à partir de HTML – Tutoriel complet de rendu C# + +Vous avez déjà eu besoin de **créer un PNG à partir de HTML** mais vous n'étiez pas sûr de la bibliothèque qui vous offrirait des résultats nets et antialiasés ? Vous n'êtes pas seul. Dans de nombreux pipelines web‑to‑image, le principal problème est d'obtenir du texte et des graphiques aussi nets qu'ils le sont dans le navigateur. + +Bonne nouvelle ? Avec Aspose.HTML, vous pouvez **rendre du HTML en PNG** en quelques lignes, contrôler la taille du canvas, ajouter une couleur d'arrière‑plan solide, et enfin **enregistrer l'image rendue** sur le disque—sans toucher à un navigateur. Dans ce tutoriel, nous parcourrons l'ensemble du processus, expliquerons pourquoi chaque paramètre est important, et vous montrerons un exemple prêt à l'emploi. + +## Ce que vous apprendrez + +- Comment charger du HTML depuis une chaîne, un fichier ou une URL +- Comment configurer **set canvas size** et **add background color** pour une sortie prévisible +- Activer l'antialiasing et le hinting de texte sous‑pixel pour des titres ultra‑nets +- Les étapes exactes pour **save rendered image** en tant que fichier PNG +- Pièges courants et ajustements optionnels pour différents scénarios + +Aucune expérience préalable avec Aspose.HTML n'est requise ; il suffit d'une configuration C# de base et de Visual Studio (ou de votre IDE préféré). + +--- + +## Étape 1 : Installer Aspose.HTML pour .NET + +Avant d'écrire du code, assurez-vous que le package NuGet Aspose.HTML est référencé dans votre projet. + +```bash +dotnet add package Aspose.HTML +``` + +> **Astuce :** Utilisez la dernière version stable (en date d'avril 2026, 23.9.0) pour obtenir le moteur de rendu le plus récent et les corrections de bugs. + +--- + +## Étape 2 : Charger la source HTML – Créer un PNG à partir de HTML + +Vous pouvez fournir au moteur de rendu une chaîne en ligne, un fichier local ou une URL distante. Pour cette démonstration, nous utiliserons une simple chaîne en ligne contenant un titre avec une police personnalisée. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Pourquoi c'est important :** Charger le HTML dans un `HTMLDocument` donne au moteur un contrôle complet sur l'analyse du DOM, la cascade CSS et les calculs de mise en page. Cela isole également le rendu de tout état de navigateur externe, garantissant des résultats reproductibles. + +--- + +## Étape 3 : Configurer les options de rendu – Définir la taille du canvas et ajouter une couleur d'arrière‑plan + +La classe `ImageRenderingOptions` vous permet d'ajuster finement l'image de sortie. Ici, nous activerons l'antialiasing, définirons un arrière‑plan blanc, et spécifierons explicitement un canvas de **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Pourquoi vous pourriez modifier ces valeurs :** +- **Canvas size :** Si vous avez besoin d'une miniature, réduisez les dimensions ; pour des impressions haute résolution, augmentez‑les. +- **Background color :** Les PNG transparents sont possibles, mais de nombreux outils en aval (par ex., PowerPoint) attendent un arrière‑plan opaque. + +--- + +## Étape 4 : Rendre et **enregistrer l'image rendue** en PNG + +C'est maintenant le moment du travail intensif. Le `ImageRenderer` consomme le `HTMLDocument` et les options que nous venons de définir, puis écrit un flux PNG sur le disque. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Lorsque vous exécutez le programme, vous trouverez `result.png` sur votre bureau. Ouvrez-le, et vous devriez voir un titre net et antialiasé centré sur un canvas blanc. + +> **Résultat attendu :** Un PNG de 800 × 600 avec un arrière‑plan blanc et le texte « Antialiased Heading » rendu en Arial, aussi lisse que dans Chrome. + +--- + +## Étape 5 : Vérifier le résultat – Vérifications rapides + +1. **Existence du fichier :** `File.Exists(outputPath)` doit renvoyer `true`. +2. **Dimensions :** Ouvrez le PNG dans n'importe quel visualiseur d'images ; il doit indiquer 800 × 600 px. +3. **Qualité visuelle :** Zoomez à 200 % – les bords du texte doivent rester lisses, pas crénelés. + +Si quelque chose semble incorrect, revérifiez que `UseAntialiasing` et `UseHinting` sont tous deux définis sur `true`. Ces deux indicateurs sont la sauce secrète pour un rendu de haute qualité. + +--- + +## Variations courantes et cas limites + +| Scenario | What to Adjust | Why | +|----------|----------------|-----| +| **Rendre une page web distante** | Remplacez `new HTMLDocument(htmlContent)` par `new HTMLDocument("https://example.com")` | Vous permet de capturer des sites en direct sans copier le HTML manuellement. | +| **Arrière‑plan transparent** | Définissez `BackgroundColor = Color.Transparent` et utilisez `ImageFormat.Png` | Utile pour superposer le PNG sur d'autres graphiques. | +| **Format d'image différent** | Modifiez `renderer.Save(pngStream, ImageFormat.Jpeg)` | Le JPEG peut être plus petit pour du contenu photographique, mais il perd la qualité sans perte. | +| **Taille de canvas dynamique** | Utilisez `imgOptions.Width = htmlDoc.Body.ClientWidth;` après la mise en page | Permet à l'image de correspondre à la largeur naturelle du contenu HTML. | +| **Sortie haute DPI** | Multipliez `Width` et `Height` par un facteur d'échelle (par ex., 2) | Génère des actifs prêts pour Retina pour les écrans modernes. | + +--- + +## Exemple complet fonctionnel (prêt à copier‑coller) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Exécutez le programme (`dotnet run` ou appuyez sur F5 dans Visual Studio) et vous obtiendrez un PNG parfaitement rendu, prêt à être utilisé dans les e‑mails, les rapports, ou tout autre endroit où vous avez besoin d'une image statique du HTML. + +--- + +## Questions fréquentes + +**Q : Cela fonctionne-t-il avec les fonctionnalités CSS 3 comme flexbox ?** +R : Oui. Aspose.HTML prend en charge la plupart des CSS modernes, y compris flexbox, grid et les media queries. Assurez‑vous simplement d'utiliser la dernière version de la bibliothèque. + +**Q : Et si mon HTML référence des images externes ?** +R : Le moteur suit les URL relatives basées sur l'URI de base du document. Si vous chargez le HTML depuis une chaîne, définissez `doc.BaseUrl` sur le dossier contenant les ressources. + +**Q : Puis‑je rendre plusieurs pages en un seul PNG ?** +R : Pas directement—chaque appel à `ImageRenderer` produit une seule image raster. Pour une sortie multi‑pages, rendez chaque page séparément et assemblez‑les avec une bibliothèque graphique (par ex., ImageSharp). + +--- + +## Conclusion + +Vous disposez maintenant d'une solution solide, de bout en bout, pour **créer un PNG à partir de HTML** en utilisant Aspose.HTML. En configurant les options **render html to png**—telles que **set canvas size**, **add background color**, et en activant l'antialiasing—vous pouvez générer des images de qualité professionnelle sans navigateur. + +À partir de maintenant, vous pouvez expérimenter avec un DPI plus élevé, des arrière‑plans transparents, ou le traitement par lots de dizaines d'extraits HTML. Le même schéma s'applique que vous construisiez un service de miniatures, un pipeline de génération de PDF, ou un outil d'aperçu de site statique. + +Bon rendu, et n'hésitez pas à laisser un commentaire si vous rencontrez des problèmes ! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/french/net/html-document-manipulation/_index.md index 134ab9f67..93b8d468a 100644 --- a/html/french/net/html-document-manipulation/_index.md +++ b/html/french/net/html-document-manipulation/_index.md @@ -73,6 +73,9 @@ Libérez le potentiel du développement Web avec Aspose.HTML pour .NET. Créez, ### [Créer du HTML à partir d'une chaîne en C# – Guide du gestionnaire de ressources personnalisé](./create-html-from-string-in-c-custom-resource-handler-guide/) Apprenez à générer du HTML à partir d'une chaîne C# en utilisant un gestionnaire de ressources personnalisé avec Aspose.HTML. +### [Appliquer le style de police par programme – Guide rapide C#](./apply-font-style-programmatically-quick-c-guide/) +Apprenez à appliquer des styles de police à vos documents HTML en C# de manière programmatique avec Aspose.HTML. + ## Conclusion En conclusion, si vous souhaitez maîtriser la manipulation de documents HTML à l'aide d'Aspose.HTML pour .NET, vous êtes au bon endroit. Nos tutoriels sont votre feuille de route vers le succès. Préparez-vous à explorer les possibilités, à libérer votre créativité et à rationaliser votre développement .NET. Commencez votre voyage dès aujourd'hui et regardez vos documents HTML se transformer sous vos yeux. Que vous soyez développeur ou passionné, Aspose.HTML pour .NET vous réserve quelque chose d'incroyable. Alors, qu'attendez-vous ? Embarquons ensemble dans cette aventure passionnante ! diff --git a/html/french/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/french/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..a2bb99e6b --- /dev/null +++ b/html/french/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Appliquez le style de police par programmation et apprenez à supprimer + le soulignement du texte, à modifier le style du texte et à mettre le texte en gras + par programmation dans un tutoriel concis. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: fr +og_description: Appliquez le style de police par programmation et découvrez comment + supprimer le soulignement du texte, modifier le style du texte et mettre le texte + en gras par programmation dans un court tutoriel pratique. +og_title: Appliquer le style de police par programmation – Guide rapide C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Appliquer le style de police par programmation – Guide rapide C# +url: /fr/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Appliquer le style de police par programme – Guide rapide C# + +Vous avez déjà eu besoin **d’appliquer un style de police** à un élément UI sans savoir par où commencer ? Vous n’êtes pas seul — la plupart des développeurs rencontrent ce problème lorsqu’ils s’aventurent pour la première fois dans le formatage dynamique du texte. La bonne nouvelle ? En quelques minutes, vous saurez exactement comment modifier l’apparence d’un label, supprimer le soulignement du texte et définir du texte en gras par programme sans fouiller dans une infinité de docs. + +Dans ce **tutoriel de formatage de texte** nous passerons en revue un exemple complet, exécutable, expliquerons le « pourquoi » de chaque ligne, et ajouterons des astuces pratiques que vous pourrez copier‑coller dans n’importe quel projet WinForms ou WPF. Pas de blabla, juste ce qui fait le travail. + +--- + +## Ce que vous allez apprendre + +- Comment **appliquer un style de police** à l’aide d’une petite classe d’assistance. +- Les étapes précises pour **supprimer le soulignement du texte** tout en conservant les autres styles. +- Les différentes manières de **modifier le style du texte** (gras, italique, souligné) à la volée. +- Un extrait complet, prêt à copier, qui **définit du texte en gras par programme**. +- Les pièges courants et la gestion des cas limites pour ne pas être surpris plus tard. + +**Prérequis :** .NET 6+ (ou tout .NET Framework récent), connaissances de base en C#, et un IDE de votre choix (Visual Studio, Rider ou VS Code). C’est tout — aucune dépendance NuGet supplémentaire requise. + +--- + +## Étape 1 – Appliquer le style de police à votre contrôle + +Le cœur de toute opération **appliquer un style de police** est une énumération `FontStyle` combinée à un objet `Font`. Pour garder le code propre, nous encapsulerons la logique d’énumération dans une petite classe `WebFontStyle`. Cette classe reflète les propriétés que vous avez vues dans l’extrait original (`Bold`, `Italic`, `Underline`) et construit une valeur `FontStyle` que vous pouvez transmettre à `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Pourquoi c’est important :** +En isolant la logique de construction des drapeaux, vous évitez de disperser des opérations bitwise `|` dans votre code UI. C’est plus lisible, plus testable, et—le plus important—cela rend l’intention **appliquer un style de police** parfaitement claire. + +--- + +## Étape 2 – Supprimer le soulignement du texte (et garder les autres styles intacts) + +Supposons que vous ayez hérité d’un label déjà souligné, mais que le design exige du texte simplement en gras. Vous ne voulez pas perdre le gras en supprimant le soulignement. C’est là que la classe `WebFontStyle` brille. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Point clé :** Définir `Underline = false` indique explicitement à l’assistant d’*exclure* le drapeau soulignement. Si vous omettez cette ligne, le soulignement précédent persistera, ce qui est une source fréquente de bugs lorsque les développeurs ne font que basculer la propriété `Bold`. + +--- + +## Étape 3 – Modifier le style du texte : gras, italique et plus + +Vous vous demandez peut‑être, « Et si je dois aussi basculer l’italique ? » Le même objet fonctionne pour n’importe quelle combinaison. Voici une petite matrice de référence que vous pouvez consulter pendant le codage. + +| Style souhaité | `Bold` | `Italic` | `Underline` | +|----------------|--------|----------|-------------| +| **Gras uniquement** | true | false | false | +| *Italique uniquement* | false | true | false | +| **Gras + Italique** | true | true | false | +| **Gras + Soulignement** | true | false | true | + +Il suffit de régler les propriétés dont vous avez besoin et d’appeler `ToFont`. L’assistant fait le travail lourd pour vous, vous permettant de vous concentrer sur la logique UI. + +--- + +## Exemple complet – Définir du texte en gras par programme + +Voici un exemple **complet, exécutable sous WinForms** qui illustre tout ce que nous avons vu. Copiez‑collez‑le dans un nouveau projet WinForms de type console et appuyez sur **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Résultat attendu + +Lorsque vous lancez le programme, une fenêtre apparaît avec le texte **« Hello, world! »** affiché en **gras**, **non italique**, et **sans aucun soulignement**. Cette confirmation visuelle indique que la logique **appliquer un style de police** a fonctionné parfaitement. + +--- + +## Astuces pro & cas limites + +- **Mises à jour dynamiques** : Si vous devez changer le style après l’affichage du formulaire (par ex. en réponse à une case à cocher), recréez simplement l’instance `WebFontStyle` ou modifiez ses propriétés puis réaffectez `lbl.Font`. L’UI se met à jour instantanément. +- **Considérations haute‑DPI** : Lorsque vous remplacez un objet `Font`, Windows le redimensionne automatiquement en fonction du DPI actuel. Aucun code supplémentaire n’est nécessaire sauf si vous gérez manuellement le scaling. +- **Équivalent WPF** : En WPF, vous lieriez `FontWeight`, `FontStyle` et `TextDecorations` au lieu d’échanger un objet `Font`. La même séparation logique s’applique — gardez la logique de style hors de la couche vue. +- **Éviter les fuites de mémoire** : Réassigner `Label.Font` crée un nouvel objet `Font`. Disposez de l’ancien si vous changez fréquemment de style : `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Conclusion + +Vous savez maintenant comment **appliquer un style de police** à n’importe quel contrôle .NET, **supprimer le soulignement du texte**, et **modifier le style du texte** à la volée — tout en gardant votre code propre et réutilisable. Le petit assistant `WebFontStyle` transforme quelques drapeaux booléens en un composant solide et testable, et l’exemple complet montre que vous pouvez **définir du texte en gras par programme** en quelques lignes seulement. + +Et après ? Essayez de combiner cette approche avec des paramètres définis par l’utilisateur, ou expérimentez d’autres drapeaux `FontStyle` comme `Strikeout`. Vous pourriez même exposer un petit panneau UI qui permet aux utilisateurs non techniques de choisir gras, italique ou soulignement à l’exécution — sans recompilation requise. + +Si ce **tutoriel de formatage de texte** vous a été utile, n’hésitez pas à laisser un commentaire ou à partager vos propres variantes. Bon codage, et que votre UI ressemble toujours exactement à ce que vous aviez imaginé ! + +--- + +![Capture d’écran montrant comment appliquer le style de police à un label en C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/french/net/html-extensions-and-conversions/_index.md index f4e02735c..9659d11bc 100644 --- a/html/french/net/html-extensions-and-conversions/_index.md +++ b/html/french/net/html-extensions-and-conversions/_index.md @@ -74,6 +74,8 @@ Apprenez à compresser du HTML en un fichier zip avec C# grâce à notre guide d Apprenez à enregistrer un document HTML dans un fichier ZIP en C# avec Aspose.HTML pour .NET. Guide complet étape par étape. ### [Enregistrer HTML en ZIP en C# – Exemple complet en mémoire](./save-html-to-zip-in-c-complete-in-memory-example/) Enregistrez du HTML dans un fichier ZIP en mémoire avec Aspose.HTML pour .NET. +### [Comment zipper du HTML en C# – guide du gestionnaire de ressources personnalisé](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Apprenez à compresser du HTML en utilisant un gestionnaire de ressources personnalisé en C# avec Aspose.HTML pour .NET. ## Conclusion diff --git a/html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..2c7a5a898 --- /dev/null +++ b/html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Apprenez à compresser du HTML en C# à l'aide d'un gestionnaire de ressources + personnalisé – guide étape par étape pour enregistrer le HTML en zip, convertir + le HTML en zip et créer un zip à partir du HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: fr +og_description: 'Comment zipper du HTML en C# expliqué : utilisez un gestionnaire + de ressources personnalisé pour enregistrer le HTML en zip, convertir le HTML en + zip et créer un zip à partir du HTML en quelques minutes.' +og_title: Comment compresser du HTML en C# – Guide du gestionnaire de ressources personnalisé +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: Comment zipper du HTML en C# – guide du gestionnaire de ressources personnalisé +url: /fr/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# comment zipper du HTML en C# – guide du gestionnaire de ressources personnalisé + +Vous vous êtes déjà demandé **comment zipper du HTML** directement depuis votre code C# sans d'abord copier les fichiers sur le disque ? Vous n'êtes pas seul. De nombreux développeurs se heurtent à un mur lorsqu'ils doivent empaqueter une page HTML avec son CSS, ses images et ses polices pour une distribution hors ligne, et ils finissent par écrire du code de système de fichiers ad‑hoc qui devient rapidement un cauchemar de maintenance. + +Dans ce tutoriel, nous résoudrons ce problème en vous montrant une approche propre et réutilisable qui **enregistre le HTML sous forme d'archive ZIP** à l'aide du `ResourceHandler` d'Aspose.HTML. Nous aborderons également comment **convertir du HTML en ZIP**, et même démontrerons un modèle que vous pouvez réutiliser pour **créer un ZIP à partir de HTML** dans n'importe quel projet .NET. Aucun script externe, aucun dossier temporaire—juste du pur C#. + +À la fin du guide, vous disposerez d'un exemple prêt à l'emploi qui génère un `result.zip` contenant chaque ressource liée, ainsi que d'une poignée de conseils pratiques que vous pourrez appliquer à vos propres projets. + +## Prérequis + +- .NET 6+ (le code fonctionne également sur .NET Framework 4.7.2, mais nous recommandons le dernier SDK) +- Package NuGet Aspose.HTML pour .NET (`Aspose.HTML`) – installer via `dotnet add package Aspose.HTML` +- Familiarité de base avec les flux et l'espace de noms `System.IO.Compression` +- Un IDE ou éditeur de votre choix (Visual Studio, VS Code, Rider…) + +Si vous avez déjà ces éléments en place, super—passons directement au code. Sinon, la seule étape supplémentaire est une installation NuGet en une ligne ; tout le reste est autonome. + +## Étape 1 : créer un document HTML simple en mémoire + +Tout d'abord, nous avons besoin d'un objet `HTMLDocument` qui représente la page que nous voulons zipper. Dans un scénario réel, vous pourriez le charger depuis une URL ou un fichier, mais pour plus de clarté, nous créerons un petit document en ligne. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Pourquoi c'est important :** +> En conservant le document en mémoire, nous évitons toute I/O de fichier intermédiaire, ce qui rend l'étape ultérieure de **convertir du HTML en ZIP** rapide et sûre pour les threads. + +## Étape 2 : préparer un flux ZIP en mémoire + +Au lieu d'écrire un fichier `.zip` temporaire sur le disque, nous utiliserons un `MemoryStream`. Cela garde tout en RAM, idéal pour les services web ou les tâches en arrière‑plan qui doivent renvoyer l'archive directement à un client. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Astuce :** L'instruction `using` garantit que le flux est automatiquement libéré, évitant les fuites de mémoire. + +## Étape 3 : implémenter un ResourceHandler personnalisé + +Aspose.HTML appelle un `ResourceHandler` pour chaque ressource externe qu'il découvre (fichiers CSS, images, polices, etc.). En sous‑classant `ResourceHandler`, nous pouvons décider exactement où chaque ressource se retrouve—dans notre cas, en tant qu'entrée dans l'archive ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Pourquoi un gestionnaire personnalisé ? + +- **Contrôle du nommage** – vous décidez comment chaque fichier apparaît dans l'archive. +- **Pas de fichiers temporaires** – le gestionnaire écrit directement dans le ZIP en mémoire. +- **Réutilisabilité** – vous pouvez intégrer cette classe dans n'importe quel projet qui a besoin de **enregistrer du HTML sous forme de ZIP**. + +## Étape 4 : enregistrer le document HTML en utilisant le gestionnaire + +Nous réunissons maintenant tous les éléments. La méthode `Save` invoquera `HandleResource` pour chaque ressource liée, et le gestionnaire transmettra ces octets dans l'archive ZIP que nous avons créée précédemment. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Ce qui se passe en coulisses :** +> Aspose analyse le HTML, découvre la référence ``, demande au gestionnaire un flux, et le gestionnaire crée une entrée `logo.png` dans le ZIP. Le même flux se répète pour le CSS, les polices ou toute autre ressource externe. + +## Étape 5 : persister l'archive ZIP sur le disque (ou la renvoyer) + +Enfin, nous écrivons l'archive en mémoire dans un fichier. Dans une API web, vous pourriez à la place renvoyer `zipMemoryStream.ToArray()` sous forme de tableau d'octets. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Résultat attendu + +Ouvrez `result.zip` et vous devriez voir : + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Si vous ouvrez l'archive dans un explorateur de fichiers, vous remarquerez que le fichier HTML est stocké sous le nom `resource.bin` parce que nous ne lui avons pas donné de nom convivial. Vous pouvez facilement améliorer cela en vérifiant `resourceInfo.ContentType` et en attribuant `.html` lorsque c'est approprié. + +## Exemple complet fonctionnel + +Ci-dessous se trouve le programme complet, prêt à copier‑coller, qui intègre toutes les étapes précédentes. Exécutez-le depuis une application console, et vous obtiendrez un fichier ZIP prêt à être partagé. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Exécuter ce code** générera `result.zip` dans le répertoire de travail du programme. Ouvrez-le et vous trouverez `index.html` (notre page originale) ainsi que `logo.png` si cette image existait sur le disque ou a été récupérée depuis une URL. + +## Variations courantes et cas limites + +| Scénario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/german/net/generate-jpg-and-png-images/_index.md index 8c24c4537..bdb94c753 100644 --- a/html/german/net/generate-jpg-and-png-images/_index.md +++ b/html/german/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML-Dokumente bearbeiten, HTML Erfahren Sie, wie Sie beim Konvertieren von DOCX-Dokumenten in PNG oder JPG Antialiasing aktivieren, um hochwertige Bilder zu erhalten. ### [DOCX in PNG konvertieren – ZIP-Archiv erstellen C#‑Tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Erfahren Sie, wie Sie DOCX‑Dateien in PNG‑Bilder umwandeln und diese in ein ZIP‑Archiv packen – Schritt‑für‑Schritt‑Anleitung in C#. +### [PNG aus HTML erstellen – Schritt‑für‑Schritt‑Anleitung für C#‑Entwickler](./create-png-from-html-step-by-step-guide-for-c-developers/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET PNG‑Bilder aus HTML generieren – detaillierte Schritt‑für‑Schritt‑Anleitung für C#‑Entwickler. ## Abschluss diff --git a/html/german/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/german/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..5a53fb607 --- /dev/null +++ b/html/german/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Erstellen Sie schnell PNGs aus HTML mit Aspose.HTML. Erfahren Sie, wie + Sie HTML in PNG rendern, die Canvas‑Größe festlegen, eine Hintergrundfarbe hinzufügen + und das gerenderte Bild in wenigen Minuten speichern. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: de +og_description: Erstellen Sie PNG aus HTML mit Aspose.HTML. Dieser Leitfaden zeigt, + wie man HTML in PNG rendert, die Canvas‑Größe festlegt, eine Hintergrundfarbe hinzufügt + und das gerenderte Bild speichert. +og_title: PNG aus HTML erstellen – Vollständiges C#‑Rendering‑Tutorial +tags: +- C# +- Aspose.HTML +- Image Rendering +title: PNG aus HTML erstellen – Schritt‑für‑Schritt‑Anleitung für C#‑Entwickler +url: /de/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PNG aus HTML erstellen – Vollständiges C# Rendering‑Tutorial + +Haben Sie jemals **PNG aus HTML erstellen** müssen, waren sich aber nicht sicher, welche Bibliothek Ihnen klare, antialiasierte Ergebnisse liefert? Sie sind nicht allein. In vielen Web‑zu‑Bild‑Pipelines ist der größte Schmerzpunkt, Text und Grafiken so scharf wie im Browser aussehen zu lassen. + +Die gute Nachricht? Mit Aspose.HTML können Sie **HTML zu PNG rendern** in wenigen Zeilen, die Canvas‑Größe steuern, eine einfarbige Hintergrundfarbe hinzufügen und schließlich **gerenderte Bilder** auf die Festplatte **speichern** – ganz ohne einen Browser zu benutzen. In diesem Tutorial führen wir Sie durch den gesamten Prozess, erklären, warum jede Einstellung wichtig ist, und zeigen Ihnen ein sofort ausführbares Beispiel. + +## Was Sie lernen werden + +- Wie man HTML aus einem String, einer Datei oder einer URL lädt +- Wie man **Canvas‑Größe festlegt** und **Hintergrundfarbe hinzufügt** für vorhersehbare Ausgaben konfiguriert +- Aktivieren von Antialiasing und Sub‑Pixel‑Text‑Hinting für messerscharfe Überschriften +- Die genauen Schritte, um **gerenderte Bilder** als PNG‑Datei **zu speichern** +- Häufige Fallstricke und optionale Anpassungen für verschiedene Szenarien + +Keine Vorkenntnisse mit Aspose.HTML sind erforderlich; nur ein einfaches C#‑Setup und Visual Studio (oder Ihre bevorzugte IDE). + +--- + +## Schritt 1: Aspose.HTML für .NET installieren + +Bevor wir Code schreiben, stellen Sie sicher, dass das Aspose.HTML‑NuGet‑Paket in Ihrem Projekt referenziert ist. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro Tipp:** Verwenden Sie die neueste stabile Version (Stand April 2026, 23.9.0), um die neueste Rendering‑Engine und Fehlerbehebungen zu erhalten. + +--- + +## Schritt 2: HTML‑Quelle laden – PNG aus HTML erstellen + +Sie können dem Renderer einen Inline‑String, eine lokale Datei oder eine Remote‑URL übergeben. Für diese Demo verwenden wir einen einfachen Inline‑String, der eine Überschrift mit einer benutzerdefinierten Schriftart enthält. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Warum das wichtig ist:** Das Laden von HTML in ein `HTMLDocument` gibt der Engine die volle Kontrolle über DOM‑Parsing, CSS‑Kaskade und Layout‑Berechnungen. Es isoliert das Rendering zudem von jeglichem externen Browser‑Zustand und sorgt für reproduzierbare Ergebnisse. + +--- + +## Schritt 3: Rendering‑Optionen konfigurieren – Canvas‑Größe festlegen & Hintergrundfarbe hinzufügen + +Die Klasse `ImageRenderingOptions` ermöglicht es Ihnen, das Ausgabe‑Bild fein abzustimmen. Hier aktivieren wir Antialiasing, setzen einen weißen Hintergrund und definieren explizit eine Canvas von **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Warum Sie diese Werte ändern könnten:** +- **Canvas‑Größe:** Wenn Sie ein Thumbnail benötigen, verkleinern Sie die Abmessungen; für hochauflösende Drucke erhöhen Sie sie. +- **Hintergrundfarbe:** Transparente PNGs sind möglich, aber viele nachgelagerte Werkzeuge (z. B. PowerPoint) erwarten einen undurchsichtigen Hintergrund. + +--- + +## Schritt 4: Rendern und **gerenderte Bilder** als PNG **speichern** + +Jetzt findet die eigentliche Arbeit statt. Der `ImageRenderer` verarbeitet das `HTMLDocument` und die gerade definierten Optionen und schreibt anschließend einen PNG‑Stream auf die Festplatte. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Wenn Sie das Programm ausführen, finden Sie `result.png` auf Ihrem Desktop. Öffnen Sie es, und Sie sollten eine klare, antialiasierte Überschrift sehen, die zentriert auf einer weißen Canvas liegt. + +> **Erwartete Ausgabe:** Ein 800 × 600 PNG mit weißem Hintergrund und dem Text „Antialiased Heading“, gerendert in Arial, der genauso glatt aussieht wie in Chrome. + +--- + +## Schritt 5: Ergebnis überprüfen – Schnell‑Checks + +1. **Dateiexistenz:** `File.Exists(outputPath)` sollte `true` zurückgeben. +2. **Abmessungen:** Öffnen Sie das PNG in einem beliebigen Bildbetrachter; es sollte 800 × 600 px anzeigen. +3. **Visuelle Qualität:** Zoomen Sie auf 200 % – die Textkanten müssen glatt bleiben, nicht gezackt. + +Wenn etwas nicht stimmt, überprüfen Sie, ob `UseAntialiasing` und `UseHinting` beide auf `true` gesetzt sind. Diese beiden Flags sind das Geheimrezept für Rendering von hoher Qualität. + +--- + +## Übliche Variationen & Randfälle + +| Szenario | Was anzupassen | Warum | +|----------|----------------|------| +| **Eine entfernte Webseite rendern** | Ersetzen Sie `new HTMLDocument(htmlContent)` durch `new HTMLDocument("https://example.com")` | Ermöglicht das Erfassen von Live‑Seiten, ohne HTML manuell zu kopieren. | +| **Transparenter Hintergrund** | Setzen Sie `BackgroundColor = Color.Transparent` und verwenden Sie `ImageFormat.Png` | Nützlich, um das PNG über andere Grafiken zu legen. | +| **Anderes Bildformat** | Ändern Sie `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG kann bei fotografischen Inhalten kleiner sein, verliert jedoch die verlustfreie Qualität. | +| **Dynamische Canvas‑Größe** | Verwenden Sie `imgOptions.Width = htmlDoc.Body.ClientWidth;` nach dem Layout | Lässt das Bild der natürlichen Breite des HTML‑Inhalts entsprechen. | +| **High‑DPI‑Ausgabe** | Multiplizieren Sie `Width` und `Height` mit einem Skalierungsfaktor (z. B. 2) | Erzeugt Retina‑fähige Assets für moderne Displays. | + +--- + +## Vollständiges funktionierendes Beispiel (Copy‑Paste‑bereit) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Führen Sie das Programm aus (`dotnet run` oder drücken Sie F5 in Visual Studio) und Sie erhalten ein perfekt gerendertes PNG, das Sie in E‑Mails, Berichten oder an jeder anderen Stelle, an der Sie ein statisches Bild von HTML benötigen, verwenden können. + +--- + +## Häufig gestellte Fragen + +**Q: Funktioniert das mit CSS 3‑Features wie Flexbox?** +A: Ja. Aspose.HTML unterstützt die meisten modernen CSS‑Features, einschließlich Flexbox, Grid und Media Queries. Stellen Sie einfach sicher, dass Sie die neueste Bibliotheksversion verwenden. + +**Q: Was ist, wenn mein HTML externe Bilder referenziert?** +A: Der Renderer folgt relativen URLs basierend auf der Basis‑URI des Dokuments. Wenn Sie HTML aus einem String laden, setzen Sie `doc.BaseUrl` auf den Ordner, der die Assets enthält. + +**Q: Kann ich mehrere Seiten in ein PNG rendern?** +A: Nicht direkt – jeder Aufruf von `ImageRenderer` erzeugt ein einzelnes Rasterbild. Für mehrseitige Ausgaben rendern Sie jede Seite separat und fügen sie mit einer Grafik‑Bibliothek (z. B. ImageSharp) zusammen. + +--- + +## Fazit + +Sie haben jetzt eine solide End‑zu‑End‑Lösung, um **PNG aus HTML zu erstellen** mit Aspose.HTML. Durch das Konfigurieren von **HTML zu PNG rendern**‑Optionen – wie **Canvas‑Größe festlegen**, **Hintergrundfarbe hinzufügen** und Antialiasing aktivieren – können Sie professionelle Bilder ohne einen Browser erzeugen. + +Ab jetzt können Sie mit höherer DPI, transparenten Hintergründen oder der Stapelverarbeitung von Dutzenden HTML‑Snippets experimentieren. Das gleiche Muster gilt, egal ob Sie einen Thumbnail‑Dienst, eine PDF‑Generierungspipeline oder ein Vorschau‑Tool für statische Websites bauen. + +Viel Spaß beim Rendern, und hinterlassen Sie gerne einen Kommentar, falls Sie auf Probleme stoßen! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/german/net/html-document-manipulation/_index.md index 1e5420dd7..f58d0b142 100644 --- a/html/german/net/html-document-manipulation/_index.md +++ b/html/german/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Erfahren Sie, wie Sie Aspose.HTML für .NET verwenden. Importieren Sie Namespace Schöpfen Sie das Potenzial der Webentwicklung mit Aspose.HTML für .NET. Erstellen, konvertieren und bearbeiten Sie HTML-Dokumente ganz einfach. ### [HTML aus String in C# erstellen – Leitfaden für benutzerdefinierten Ressourcen-Handler](./create-html-from-string-in-c-custom-resource-handler-guide/) Erfahren Sie, wie Sie mit einem benutzerdefinierten Ressourcen-Handler HTML aus einem String in C# generieren und rendern. +### [Schriftstil programmgesteuert anwenden – Schnellleitfaden für C#](./apply-font-style-programmatically-quick-c-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET Schriftstile programmgesteuert anwenden und HTML-Inhalte in C# formatieren. ## Abschluss diff --git a/html/german/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/german/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..215728d8d --- /dev/null +++ b/html/german/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Wenden Sie Schriftstil programmgesteuert an und lernen Sie, wie Sie Unterstreichungen + aus Text entfernen, den Textstil ändern und fettgedruckten Text programmgesteuert + festlegen – in einem kurzen Tutorial. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: de +og_description: Wende Schriftstile programmgesteuert an und erfahre, wie du Unterstreichungen + aus Text entfernst, den Textstil änderst und Text programmgesteuert fett formatierst + – in einem kurzen, praxisnahen Tutorial. +og_title: Schriftstil programmgesteuert anwenden – Kurzanleitung für C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Schriftstil programmgesteuert anwenden – Schnelle C#‑Anleitung +url: /de/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Schriftstil programmgesteuert anwenden – Schnell‑Guide für C# + +Haben Sie schon einmal **Schriftstil** auf ein UI‑Element anwenden müssen, wussten aber nicht, wo Sie anfangen sollten? Sie sind nicht allein – die meisten Entwickler stoßen darauf, wenn sie das erste Mal mit dynamischer Textformatierung experimentieren. Die gute Nachricht? In nur wenigen Minuten wissen Sie genau, wie Sie das Aussehen eines Labels ändern, Unterstreichungen entfernen und Text fett formatieren können, ohne endlos in der Dokumentation zu suchen. + +In diesem **Textformatierungs‑Tutorial** gehen wir ein komplettes, ausführbares Beispiel durch, erklären das „Warum“ hinter jeder Zeile und geben praktische Tipps, die Sie in jedes WinForms‑ oder WPF‑Projekt kopieren‑und‑einfügen können. Kein Schnickschnack, nur das, was die Arbeit erledigt. + +--- + +## Was Sie lernen werden + +- Wie man **Schriftstil** mit einer kleinen Hilfsklasse anwendet. +- Die genauen Schritte, um **Unterstreichung vom Text zu entfernen**, während andere Stile erhalten bleiben. +- Möglichkeiten, **Textstil** (fett, kursiv, unterstrichen) zur Laufzeit zu ändern. +- Ein vollständiges, kopier‑fertiges Snippet, das **fetten Text programmgesteuert** setzt. +- Häufige Stolperfallen und Edge‑Case‑Behandlungen, damit Sie später nicht überrascht werden. + +**Voraussetzungen:** .NET 6+ (oder ein aktuelles .NET Framework), Grundkenntnisse in C# und eine IDE Ihrer Wahl (Visual Studio, Rider oder VS Code). Das war’s – keine zusätzlichen NuGet‑Pakete nötig. + +--- + +## Schritt 1 – Schriftstil auf Ihr Steuerelement anwenden + +Der Kern jeder **apply font style**‑Operation ist ein `FontStyle`‑Enum kombiniert mit einem `Font`‑Objekt. Damit der Code übersichtlich bleibt, verpacken wir die Enum‑Logik in eine kleine `WebFontStyle`‑Klasse. Diese Klasse spiegelt die Eigenschaften des Original‑Snippets (`Bold`, `Italic`, `Underline`) wider und erzeugt einen `FontStyle`‑Wert, den Sie an `Font` übergeben können. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Warum das wichtig ist:** +Durch das Isolieren der Flag‑Erstellungs‑Logik vermeiden Sie das verstreute Setzen von bitweisen `|`‑Operationen im UI‑Code. Der Code ist leichter zu lesen, zu testen und – am wichtigsten – macht die **apply font style**‑Intention kristallklar. + +--- + +## Schritt 2 – Unterstreichung vom Text entfernen (und andere Stile erhalten) + +Angenommen, Sie haben ein Label übernommen, das bereits unterstrichen ist, das Design jedoch nur fetten Text verlangt. Sie wollen die Unterstreichung entfernen, ohne die Fett­formatierung zu verlieren. Hier kommt die `WebFontStyle`‑Klasse ins Spiel. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Wichtiger Punkt:** Das explizite Setzen von `Underline = false` weist den Helfer an, das Unterstreichungs‑Flag auszuschließen. Wenn Sie die Zeile weglassen, bleibt die vorherige Unterstreichung erhalten – eine häufige Fehlerquelle, wenn Entwickler nur die `Bold`‑Eigenschaft umschalten. + +--- + +## Schritt 3 – Textstil ändern: Fett, Kursiv und mehr + +Vielleicht fragen Sie sich: „Was, wenn ich auch Kursiv umschalten muss?“ Das gleiche Objekt funktioniert für jede Kombination. Unten finden Sie eine schnelle Matrix, die Sie beim Codieren als Referenz nutzen können. + +| Gewünschter Stil | `Bold` | `Italic` | `Underline` | +|------------------|--------|----------|-------------| +| **Nur fett** | true | false | false | +| *Nur kursiv* | false | true | false | +| **Fett + Kursiv** | true | true | false | +| **Fett + Unterstrichen** | true | false | true | + +Setzen Sie einfach die gewünschten Eigenschaften und rufen Sie `ToFont` auf. Der Helfer übernimmt die schwere Arbeit, sodass Sie sich auf die UI‑Logik konzentrieren können. + +--- + +## Vollständiges Beispiel – Fetten Text programmgesteuert setzen + +Im Folgenden ein **komplettes, ausführbares WinForms**‑Beispiel, das alles demonstriert, was wir besprochen haben. Fügen Sie es in ein neues WinForms‑Projekt ein und drücken Sie **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Erwartetes Ergebnis + +Beim Ausführen des Programms erscheint ein Fenster mit dem Text **„Hello, world!“**, der **fett**, **nicht kursiv** und **ohne Unterstreichung** dargestellt wird. Diese visuelle Bestätigung zeigt, dass die **apply font style**‑Logik perfekt funktioniert hat. + +--- + +## Pro‑Tipps & Edge Cases + +- **Dynamische Updates:** Wenn Sie den Stil nach dem Anzeigen des Formulars ändern müssen (z. B. als Reaktion auf ein Kontrollkästchen), erstellen Sie einfach die `WebFontStyle`‑Instanz neu oder ändern Sie deren Eigenschaften und weisen Sie `lbl.Font` erneut zu. Die UI aktualisiert sich sofort. +- **High‑DPI‑Überlegungen:** Beim Ersetzen eines `Font`‑Objekts skaliert Windows es automatisch basierend auf der aktuellen DPI. Kein zusätzlicher Code nötig, es sei denn, Sie handhaben das Skalieren manuell. +- **WPF‑Äquivalent:** In WPF binden Sie `FontWeight`, `FontStyle` und `TextDecorations`, anstatt ein `Font`‑Objekt zu tauschen. Die gleiche logische Trennung gilt – halten Sie Stil‑Logik außerhalb der View‑Schicht. +- **Speicherlecks vermeiden:** Das erneute Zuweisen von `Label.Font` erzeugt ein neues `Font`‑Objekt. Entsorgen Sie das alte, wenn Sie Stile häufig wechseln: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Fazit + +Sie wissen jetzt, wie Sie **Schriftstil** auf jedes .NET‑Steuerelement anwenden, **Unterstreichungen entfernen** und **Textstil** zur Laufzeit ändern – und das alles mit sauberem, wiederverwendbarem Code. Die kleine `WebFontStyle`‑Hilfsklasse verwandelt ein paar boolesche Flags in eine solide, testbare Komponente, und das vollständige Beispiel beweist, dass Sie **fetten Text programmgesteuert** in nur wenigen Zeilen setzen können. + +Was kommt als Nächstes? Kombinieren Sie diesen Ansatz mit benutzergesteuerten Einstellungen oder experimentieren Sie mit anderen `FontStyle`‑Flags wie `Strikeout`. Sie könnten sogar ein kleines UI‑Panel bereitstellen, das nicht‑technischen Anwendern erlaubt, fett, kursiv oder unterstrichen zur Laufzeit auszuwählen – ohne Neukompilierung. + +Wenn Ihnen dieses **text formatting tutorial** gefallen hat, hinterlassen Sie gern einen Kommentar oder teilen Sie Ihre eigenen Varianten. Viel Spaß beim Coden, und möge Ihre UI immer genau so aussehen, wie Sie es beabsichtigen! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/german/net/html-extensions-and-conversions/_index.md index 607896d28..71e47971d 100644 --- a/html/german/net/html-extensions-and-conversions/_index.md +++ b/html/german/net/html-extensions-and-conversions/_index.md @@ -38,41 +38,43 @@ Aspose.HTML für .NET ist nicht nur eine Bibliothek; es verändert die Welt der ## Tutorials zu HTML-Erweiterungen und -Konvertierungen ### [Konvertieren Sie HTML in .NET in PDF mit Aspose.HTML](./convert-html-to-pdf/) -Konvertieren Sie HTML mühelos in PDF mit Aspose.HTML für .NET. Folgen Sie unserer Schritt-für-Schritt-Anleitung und entfesseln Sie die Leistungsfähigkeit der HTML-zu-PDF-Konvertierung. +Konvertieren Sie HTML mühelos in PDF mit Aspose.HTML für .NET. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung und entfesseln Sie die Leistungsfähigkeit der HTML‑zu‑PDF‑Konvertierung. ### [Konvertieren Sie EPUB in .NET mit Aspose.HTML in ein Bild](./convert-epub-to-image/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in Bilder konvertieren. Schritt-für-Schritt-Anleitung mit Codebeispielen und anpassbaren Optionen. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in Bilder konvertieren. Schritt‑für‑Schritt‑Anleitung mit Codebeispielen und anpassbaren Optionen. ### [Konvertieren Sie EPUB in .NET mit Aspose.HTML in PDF](./convert-epub-to-pdf/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in PDF konvertieren. Diese Schritt-für-Schritt-Anleitung umfasst Anpassungsoptionen, FAQs und mehr für eine nahtlose Dokumentkonvertierung. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in PDF konvertieren. Diese Schritt‑für‑Schritt‑Anleitung umfasst Anpassungsoptionen, FAQs und mehr für eine nahtlose Dokumentkonvertierung. ### [Konvertieren Sie EPUB in XPS in .NET mit Aspose.HTML](./convert-epub-to-xps/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in XPS in .NET konvertieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung für mühelose Konvertierungen. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in XPS in .NET konvertieren. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung für mühelose Konvertierungen. ### [Konvertieren Sie HTML in BMP in .NET mit Aspose.HTML](./convert-html-to-bmp/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in BMP in .NET konvertieren. Umfassender Leitfaden für Webentwickler zur Nutzung von Aspose.HTML für .NET. ### [Konvertieren Sie HTML in .NET in DOC und DOCX mit Aspose.HTML](./convert-html-to-doc-docx/) -Erfahren Sie in dieser Schritt-für-Schritt-Anleitung, wie Sie die Leistung von Aspose.HTML für .NET nutzen. Konvertieren Sie HTML mühelos in DOCX und verbessern Sie Ihre .NET-Projekte. Legen Sie noch heute los! +Erfahren Sie in dieser Schritt‑für‑Schritt‑Anleitung, wie Sie die Leistung von Aspose.HTML für .NET nutzen. Konvertieren Sie HTML mühelos in DOCX und verbessern Sie Ihre .NET‑Projekte. Legen Sie noch heute los! ### [Konvertieren Sie HTML in GIF in .NET mit Aspose.HTML](./convert-html-to-gif/) -Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Eine Schritt-für-Schritt-Anleitung zur Konvertierung von HTML in GIF. Voraussetzungen, Codebeispiele, FAQs und mehr! Optimieren Sie Ihre HTML-Manipulation mit Aspose.HTML. +Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Eine Schritt‑für‑Schritt‑Anleitung zur Konvertierung von HTML in GIF. Voraussetzungen, Codebeispiele, FAQs und mehr! Optimieren Sie Ihre HTML‑Manipulation mit Aspose.HTML. ### [Konvertieren Sie HTML in JPEG in .NET mit Aspose.HTML](./convert-html-to-jpeg/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in JPEG in .NET konvertieren. Eine Schritt-für-Schritt-Anleitung zur Nutzung der Leistungsfähigkeit von Aspose.HTML für .NET. Optimieren Sie Ihre Webentwicklungsaufgaben mühelos. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in JPEG in .NET konvertieren. Eine Schritt‑für‑Schritt‑Anleitung zur Nutzung der Leistungsfähigkeit von Aspose.HTML für .NET. Optimieren Sie Ihre Webentwicklungsaufgaben mühelos. ### [Konvertieren Sie HTML in .NET in Markdown mit Aspose.HTML](./convert-html-to-markdown/) -Erfahren Sie, wie Sie HTML in .NET mit Aspose.HTML in Markdown konvertieren, um Inhalte effizient zu bearbeiten. Erhalten Sie eine Schritt-für-Schritt-Anleitung für einen nahtlosen Konvertierungsprozess. +Erfahren Sie, wie Sie HTML in .NET mit Aspose.HTML in Markdown konvertieren, um Inhalte effizient zu bearbeiten. Erhalten Sie eine Schritt‑für‑Schritt‑Anleitung für einen nahtlosen Konvertierungsprozess. ### [Konvertieren Sie HTML in MHTML in .NET mit Aspose.HTML](./convert-html-to-mhtml/) -Konvertieren Sie HTML in .NET in MHTML mit Aspose.HTML – Eine Schritt-für-Schritt-Anleitung zum effizienten Archivieren von Webinhalten. Erfahren Sie, wie Sie mit Aspose.HTML für .NET MHTML-Archive erstellen. +Konvertieren Sie HTML in .NET in MHTML mit Aspose.HTML – Eine Schritt‑für‑Schritt‑Anleitung zum effizienten Archivieren von Webinhalten. Erfahren Sie, wie Sie mit Aspose.HTML für .NET MHTML‑Archive erstellen. ### [Konvertieren Sie HTML in PNG in .NET mit Aspose.HTML](./convert-html-to-png/) -Entdecken Sie, wie Sie mit Aspose.HTML für .NET HTML-Dokumente bearbeiten und konvertieren. Schritt-für-Schritt-Anleitung für effektive .NET-Entwicklung. +Entdecken Sie, wie Sie mit Aspose.HTML für .NET HTML‑Dokumente bearbeiten und konvertieren. Schritt‑für‑Schritt‑Anleitung für effektive .NET‑Entwicklung. ### [Konvertieren Sie HTML in TIFF in .NET mit Aspose.HTML](./convert-html-to-tiff/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in TIFF konvertieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung zur effizienten Optimierung von Webinhalten. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in TIFF konvertieren. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung zur effizienten Optimierung von Webinhalten. ### [Konvertieren Sie HTML in XPS in .NET mit Aspose.HTML](./convert-html-to-xps/) -Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Konvertieren Sie HTML mühelos in XPS. Voraussetzungen, Schritt-für-Schritt-Anleitung und FAQs inklusive. +Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Konvertieren Sie HTML mühelos in XPS. Voraussetzungen, Schritt‑für‑Schritt‑Anleitung und FAQs inklusive. ### [HTML in C# zippen – HTML in Zip speichern](./how-to-zip-html-in-c-save-html-to-zip/) -Erfahren Sie, wie Sie HTML-Inhalte mit Aspose.HTML für .NET in eine ZIP-Datei komprimieren und speichern. -### [HTML-Dokument mit formatiertem Text erstellen und in PDF exportieren – Vollständige Anleitung](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Erfahren Sie, wie Sie ein HTML-Dokument mit formatiertem Text erstellen und es mit Aspose.HTML für .NET in ein PDF exportieren. +Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET in eine ZIP‑Datei komprimieren und speichern. +### [HTML in C# zippen – Leitfaden für benutzerdefinierten Ressourcen‑Handler](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET über einen benutzerdefinierten Ressourcen‑Handler zippen und speichern. +### [HTML‑Dokument mit formatiertem Text erstellen und in PDF exportieren – Vollständige Anleitung](./create-html-document-with-styled-text-and-export-to-pdf-full/) +Erfahren Sie, wie Sie ein HTML‑Dokument mit formatiertem Text erstellen und es mit Aspose.HTML für .NET in ein PDF exportieren. ### [PDF aus HTML erstellen – C# Schritt‑für‑Schritt‑Anleitung](./create-pdf-from-html-c-step-by-step-guide/) Erstellen Sie PDF aus HTML mit C# – eine detaillierte Schritt‑für‑Schritt‑Anleitung mit Aspose.HTML für .NET. ### [HTML als ZIP speichern – Komplettes C#‑Tutorial](./save-html-as-zip-complete-c-tutorial/) Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET in ein ZIP‑Archiv speichern – vollständige Schritt‑für‑Schritt‑Anleitung in C#. ### [HTML in ZIP speichern in C# – Komplettes In‑Memory‑Beispiel](./save-html-to-zip-in-c-complete-in-memory-example/) -Speichern Sie HTML-Inhalte in ein ZIP-Archiv komplett im Speicher mit Aspose.HTML für .NET. Schritt‑für‑Schritt‑Anleitung. +Speichern Sie HTML‑Inhalte in ein ZIP‑Archiv komplett im Speicher mit Aspose.HTML für .NET. Schritt‑für‑Schritt‑Anleitung. ## Abschluss diff --git a/html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..542280524 --- /dev/null +++ b/html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Erfahren Sie, wie Sie HTML in C# mit einem benutzerdefinierten Resource‑Handler + zippen – Schritt‑für‑Schritt‑Anleitung zum Speichern von HTML als ZIP, Konvertieren + von HTML zu ZIP und Erstellen eines ZIP aus HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: de +og_description: 'Wie man HTML in C# zippt erklärt: Verwenden Sie einen benutzerdefinierten + Ressourcen‑Handler, um HTML als ZIP zu speichern, HTML in ZIP zu konvertieren und + in Minuten ein ZIP aus HTML zu erstellen.' +og_title: Wie man HTML in C# zippt – Leitfaden für benutzerdefinierte Ressourcen-Handler +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: HTML in C# zippen – Leitfaden für benutzerdefinierten Ressourcen‑Handler +url: /de/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML in C# zippen – Leitfaden für benutzerdefinierten Resource Handler + +Haben Sie sich jemals gefragt, **wie man HTML zippt** direkt aus Ihrem C#‑Code, ohne vorher Dateien auf die Festplatte zu schreiben? Sie sind nicht allein. Viele Entwickler stoßen an ihre Grenzen, wenn sie eine HTML‑Seite zusammen mit CSS, Bildern und Schriftarten für die Offline‑Verteilung paketieren müssen, und sie enden damit, ad‑hoc‑Dateisystem‑Code zu schreiben, der schnell zu einem Wartungsalptraum wird. + +In diesem Tutorial lösen wir dieses Problem, indem wir Ihnen einen sauberen, wiederverwendbaren Ansatz zeigen, der **HTML als ZIP‑Archiv speichert** mithilfe von Aspose.HTML’s `ResourceHandler`. Wir gehen auch darauf ein, wie man **HTML zu ZIP konvertiert**, und demonstrieren ein Muster, das Sie wiederverwenden können, um **ZIP aus HTML zu erstellen** in jedem .NET‑Projekt. Keine externen Skripte, keine temporären Ordner – nur reines C#. + +Am Ende des Leitfadens haben Sie ein sofort ausführbares Beispiel, das ein `result.zip` erzeugt, das jede verknüpfte Ressource enthält, plus eine Handvoll praktischer Tipps, die Sie in Ihren eigenen Projekten anwenden können. + +## Voraussetzungen + +- .NET 6+ (der Code funktioniert auch auf .NET Framework 4.7.2, wir empfehlen jedoch das neueste SDK) +- Aspose.HTML for .NET NuGet‑Paket (`Aspose.HTML`) – Installation über `dotnet add package Aspose.HTML` +- Grundlegende Kenntnisse über Streams und den Namespace `System.IO.Compression` +- Eine IDE oder ein Editor Ihrer Wahl (Visual Studio, VS Code, Rider…) + +Wenn Sie diese Komponenten bereits haben, großartig – springen wir direkt zum Code. Wenn nicht, ist der einzige zusätzliche Schritt eine einzeilige NuGet‑Installation; alles andere ist in sich abgeschlossen. + +## Schritt 1: Erstellen eines einfachen HTML‑Dokuments im Speicher + +Zuerst benötigen wir ein `HTMLDocument`‑Objekt, das die Seite repräsentiert, die wir zippen wollen. In einem realen Szenario könnten Sie dieses von einer URL oder einer Datei laden, aber zur Übersicht erstellen wir ein kleines Dokument inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Warum das wichtig ist:** +> Durch das Halten des Dokuments im Speicher vermeiden wir jegliche Zwischenspeicherung auf dem Dateisystem, was den späteren **convert html to zip**‑Schritt schnell und thread‑sicher macht. + +## Schritt 2: Vorbereiten eines In‑Memory‑ZIP‑Streams + +Anstatt eine temporäre `.zip`‑Datei auf die Festplatte zu schreiben, verwenden wir einen `MemoryStream`. Dieser hält alles im RAM, ideal für Web‑Services oder Hintergrund‑Jobs, die das Archiv direkt an einen Client zurückgeben müssen. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tipp:** Die `using`‑Anweisung sorgt dafür, dass der Stream automatisch freigegeben wird, wodurch Speicherlecks vermieden werden. + +## Schritt 3: Implementieren eines benutzerdefinierten ResourceHandler + +Aspose.HTML ruft für jedes gefundene externe Asset (CSS‑Dateien, Bilder, Schriftarten usw.) einen `ResourceHandler` auf. Durch das Subclassing von `ResourceHandler` können wir genau bestimmen, wo jede Ressource landet – in unserem Fall als Eintrag im ZIP‑Archiv. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Warum ein benutzerdefinierter Handler? + +- **Kontrolle über die Benennung** – Sie entscheiden, wie jede Datei im Archiv erscheint. +- **Keine temporären Dateien** – Der Handler schreibt direkt in das In‑Memory‑ZIP. +- **Wiederverwendbarkeit** – Sie können diese Klasse in jedes Projekt einbinden, das **save html as zip** benötigt. + +## Schritt 4: Speichern des HTML‑Dokuments mit dem Handler + +Jetzt verbinden wir alles. Die `Save`‑Methode ruft `HandleResource` für jedes verknüpfte Asset auf, und der Handler streamt diese Bytes in das zuvor erstellte ZIP‑Archiv. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Was im Hintergrund passiert:** +> Aspose analysiert das HTML, entdeckt die Referenz ``, fordert den Handler zu einem Stream auf, und der Handler erstellt einen `logo.png`‑Eintrag im ZIP. Der gleiche Ablauf wiederholt sich für CSS, Schriftarten oder andere externe Ressourcen. + +## Schritt 5: Persistieren des ZIP‑Archivs auf die Festplatte (oder zurückgeben) + +Abschließend schreiben wir das In‑Memory‑Archiv in eine Datei. In einer Web‑API könnten Sie stattdessen `zipMemoryStream.ToArray()` als Byte‑Array zurückgeben. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Erwartetes Ergebnis + +Öffnen Sie `result.zip` und Sie sollten sehen: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Wenn Sie das Archiv im Datei‑Explorer öffnen, werden Sie bemerken, dass die HTML‑Datei als `resource.bin` gespeichert ist, weil wir keinen freundlichen Namen vergeben haben. Sie können das leicht verbessern, indem Sie `resourceInfo.ContentType` prüfen und bei Bedarf `.html` zuweisen. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das komplette, copy‑paste‑fertige Programm, das alle oben genannten Schritte integriert. Führen Sie es aus einer Konsolen‑App aus, und Sie erhalten eine sofort teilbare ZIP‑Datei. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Das Ausführen dieses Codes** erzeugt `result.zip` im Arbeitsverzeichnis des Programms. Öffnen Sie es und Sie finden `index.html` (unsere ursprüngliche Seite) plus `logo.png`, falls dieses Bild auf der Festplatte existierte oder von einer URL abgerufen wurde. + +## Häufige Variationen & Randfälle + +| Szenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/greek/net/generate-jpg-and-png-images/_index.md index 5fd47cce3..d1c14b323 100644 --- a/html/greek/net/generate-jpg-and-png-images/_index.md +++ b/html/greek/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ url: /el/net/generate-jpg-and-png-images/ Μάθετε πώς να βελτιώσετε την ποιότητα των εικόνων ενεργοποιώντας το antialiasing κατά τη μετατροπή αρχείων DOCX σε PNG ή JPG. ### [Μετατροπή docx σε png – δημιουργία αρχείου zip με C# σεμινάριο](./convert-docx-to-png-create-zip-archive-c-tutorial/) Μάθετε πώς να μετατρέψετε αρχεία DOCX σε PNG και να δημιουργήσετε αρχείο ZIP χρησιμοποιώντας C#. +### [Δημιουργία PNG από HTML – Οδηγός βήμα‑βήμα για προγραμματιστές C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Μάθετε πώς να μετατρέψετε HTML σε PNG με έναν πλήρη οδηγό βήμα‑βήμα για προγραμματιστές C#. ## Σύναψη diff --git a/html/greek/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/greek/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..fa3b80b27 --- /dev/null +++ b/html/greek/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-04-23 +description: Δημιουργήστε PNG από HTML γρήγορα με το Aspose.HTML. Μάθετε πώς να αποδίδετε + HTML σε PNG, να ορίζετε το μέγεθος του καμβά, να προσθέτετε χρώμα φόντου και να + αποθηκεύετε την αποδοθείσα εικόνα σε λίγα λεπτά. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: el +og_description: Δημιουργήστε PNG από HTML με το Aspose.HTML. Αυτός ο οδηγός δείχνει + πώς να αποδώσετε HTML σε PNG, να ορίσετε το μέγεθος του καμβά, να προσθέσετε χρώμα + φόντου και να αποθηκεύσετε την αποδοθείσα εικόνα. +og_title: Δημιουργία PNG από HTML – Πλήρες Μάθημα Rendering σε C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Δημιουργία PNG από HTML – Οδηγός βήμα‑βήμα για προγραμματιστές C# +url: /el/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία PNG από HTML – Πλήρης Οδηγός Rendering σε C# + +Έχετε χρειαστεί ποτέ να **δημιουργήσετε PNG από HTML** αλλά δεν ήσασταν σίγουροι ποια βιβλιοθήκη θα σας δώσει καθαρά, anti‑aliased αποτελέσματα; Δεν είστε μόνοι. Σε πολλές αλυσίδες web‑to‑image το μεγαλύτερο πρόβλημα είναι να κάνετε το κείμενο και τα γραφικά να φαίνονται τόσο οξυμένα όσο στο πρόγραμμα περιήγησης. + +Τα καλά νέα; Με το Aspose.HTML μπορείτε να **αποδώσετε HTML σε PNG** με λίγες γραμμές κώδικα, να ελέγξετε το μέγεθος του καμβά, να προσθέσετε ένα συμπαγές χρώμα φόντου και, τέλος, να **αποθηκεύσετε την αποδοθείσα εικόνα** στο δίσκο—όλα χωρίς να αγγίξετε κάποιο πρόγραμμα περιήγησης. Σε αυτό το tutorial θα περάσουμε από όλη τη διαδικασία, θα εξηγήσουμε γιατί κάθε ρύθμιση έχει σημασία και θα σας δείξουμε ένα έτοιμο παράδειγμα. + +## What You’ll Learn + +- Πώς να φορτώσετε HTML από συμβολοσειρά, αρχείο ή URL +- Πώς να ρυθμίσετε **set canvas size** και **add background color** για προβλέψιμο αποτέλεσμα +- Ενεργοποίηση antialiasing και sub‑pixel text hinting για εξαιρετικά καθαρούς τίτλους +- Τα ακριβή βήματα για **save rendered image** ως αρχείο PNG +- Συνηθισμένα λάθη και προαιρετικές προσαρμογές για διαφορετικά σενάρια + +Δεν απαιτείται προγενέστερη εμπειρία με το Aspose.HTML· αρκεί μια βασική ρύθμιση C# και το Visual Studio (ή το αγαπημένο σας IDE). + +--- + +## Step 1: Install Aspose.HTML for .NET + +Πριν γράψουμε κώδικα, βεβαιωθείτε ότι το πακέτο NuGet Aspose.HTML είναι αναφορά στο πρότζεκτ σας. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Χρησιμοποιήστε την πιο πρόσφατη σταθερή έκδοση (από Απρίλιο 2026, 23.9.0) για να έχετε τη νεότερη μηχανή rendering και τις τελευταίες διορθώσεις σφαλμάτων. + +--- + +## Step 2: Load the HTML Source – Create PNG from HTML + +Μπορείτε να δώσετε στον renderer μια ενσωματωμένη συμβολοσειρά, ένα τοπικό αρχείο ή ένα απομακρυσμένο URL. Για αυτή τη demo θα χρησιμοποιήσουμε μια απλή ενσωματωμένη συμβολοσειρά που περιέχει έναν τίτλο με προσαρμοσμένη γραμματοσειρά. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Why this matters:** Η φόρτωση του HTML σε ένα `HTMLDocument` δίνει στη μηχανή πλήρη έλεγχο της ανάλυσης DOM, της κατάρρευσης CSS και των υπολογισμών διάταξης. Επιπλέον απομονώνει το rendering από οποιαδήποτε εξωτερική κατάσταση προγράμματος περιήγησης, εξασφαλίζοντας επαναλήψιμα αποτελέσματα. + +--- + +## Step 3: Configure Rendering Options – Set Canvas Size & Add Background Color + +Η κλάση `ImageRenderingOptions` σας επιτρέπει να ρυθμίσετε λεπτομερώς την έξοδο εικόνας. Εδώ θα ενεργοποιήσουμε antialiasing, θα θέσουμε λευκό φόντο και θα ορίσουμε ρητά έναν καμβά **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Why you might change these values:** +- **Canvas size:** Αν χρειάζεστε μικρογραφία, μειώστε τις διαστάσεις· για εκτυπώσεις υψηλής ανάλυσης, αυξήστε τις. +- **Background color:** Τα διαφανή PNG είναι δυνατότητα, αλλά πολλά downstream εργαλεία (π.χ. PowerPoint) αναμένουν αδιαφανές φόντο. + +--- + +## Step 4: Render and **Save Rendered Image** as PNG + +Τώρα γίνεται η βαριά δουλειά. Ο `ImageRenderer` καταναλώνει το `HTMLDocument` και τις επιλογές που ορίσαμε, έπειτα γράφει ένα ρεύμα PNG στο δίσκο. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +> **Expected output:** Ένα PNG 800 × 600 με λευκό φόντο και το κείμενο “Antialiased Heading” αποδοθέν σε Arial, εξομαλυνμένο όπως στο Chrome. + +--- + +## Step 5: Verify the Result – Quick Checks + +1. **File existence:** `File.Exists(outputPath)` πρέπει να επιστρέφει `true`. +2. **Dimensions:** Ανοίξτε το PNG σε οποιονδήποτε προβολέα εικόνας· πρέπει να δείχνει 800 × 600 px. +3. **Visual quality:** Μεγαλώστε στο 200 % – οι άκρες του κειμένου πρέπει να παραμένουν ομαλές, όχι σκαλιστές. + +Αν κάτι φαίνεται λανθασμένο, ελέγξτε ξανά ότι τα `UseAntialiasing` και `UseHinting` είναι και τα δύο ορισμένα σε `true`. Αυτές οι δύο σημαίες είναι το μυστικό συστατικό για rendering υψηλής ποιότητας. + +--- + +## Common Variations & Edge Cases + +| Scenario | What to Adjust | Why | +|----------|----------------|-----| +| **Render a remote web page** | Replace `new HTMLDocument(htmlContent)` with `new HTMLDocument("https://example.com")` | Επιτρέπει τη λήψη ζωντανών ιστοσελίδων χωρίς χειροκίνητη αντιγραφή HTML. | +| **Transparent background** | Set `BackgroundColor = Color.Transparent` and use `ImageFormat.Png` | Χρήσιμο για επικάλυψη του PNG πάνω σε άλλα γραφικά. | +| **Different image format** | Change `renderer.Save(pngStream, ImageFormat.Jpeg)` | Το JPEG μπορεί να είναι μικρότερο για φωτογραφικό περιεχόμενο, αλλά χάνει την απώλεια‑απώλεια ποιότητα. | +| **Dynamic canvas size** | Use `imgOptions.Width = htmlDoc.Body.ClientWidth;` after layout | Κάνει την εικόνα να ταιριάζει στο φυσικό πλάτος του HTML περιεχομένου. | +| **High‑DPI output** | Multiply `Width` and `Height` by a scale factor (e.g., 2) | Δημιουργεί assets έτοιμα για retina‑οθόνες σύγχρονων οθονών. | + +--- + +## Full Working Example (Copy‑Paste Ready) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Τρέξτε το πρόγραμμα (`dotnet run` ή πατήστε F5 στο Visual Studio) και θα έχετε ένα τέλεια αποδοθέν PNG έτοιμο για χρήση σε email, αναφορές ή οπουδήποτε χρειάζεστε μια στατική εικόνα του HTML. + +--- + +## Frequently Asked Questions + +**Q: Does this work with CSS 3 features like flexbox?** +A: Yes. Aspose.HTML supports most modern CSS, including flexbox, grid, and media queries. Just ensure you’re on the latest library version. + +**Q: What if my HTML references external images?** +A: The renderer follows relative URLs based on the document’s base URI. If you load HTML from a string, set `doc.BaseUrl` to the folder containing the assets. + +**Q: Can I render multiple pages into one PNG?** +A: Not directly—each `ImageRenderer` call produces a single raster image. For multi‑page output, render each page separately and stitch them together with a graphics library (e.g., ImageSharp). + +--- + +## Conclusion + +Now you have a solid, end‑to‑end solution to **create PNG from HTML** using Aspose.HTML. By configuring **render html to png** options—such as **set canvas size**, **add background color**, and enabling antialiasing—you can generate professional‑grade images without a browser. + +From this point you might experiment with higher DPI, transparent backgrounds, or batch‑processing dozens of HTML snippets. The same pattern applies whether you’re building a thumbnail service, a PDF generation pipeline, or a static site preview tool. + +Happy rendering, and feel free to drop a comment if you hit any snags! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/greek/net/html-document-manipulation/_index.md index c0ee23857..6bc4badc4 100644 --- a/html/greek/net/html-document-manipulation/_index.md +++ b/html/greek/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ url: /el/net/html-document-manipulation/ Μάθετε να χρησιμοποιείτε το Aspose.HTML για .NET. Εισαγάγετε χώρο ονομάτων, συγχώνευση HTML με XML και βελτιώστε τις δεξιότητές σας στην ανάπτυξη ιστού με αυτόν τον περιεκτικό οδηγό. ### [Δημιουργήστε έγγραφα XPS από το XpsDevice σε .NET με Aspose.HTML](./generate-xps-documents-by-xpsdevice/) Ξεκλειδώστε τις δυνατότητες ανάπτυξης ιστού με το Aspose.HTML για .NET. Δημιουργήστε, μετατρέψτε και χειριστείτε εύκολα έγγραφα HTML. +### [Εφαρμογή στυλ γραμματοσειράς προγραμματιστικά – Γρήγορος οδηγός C#](./apply-font-style-programmatically-quick-c-guide/) +Μάθετε πώς να εφαρμόζετε στυλ γραμματοσειράς σε έγγραφα HTML προγραμματιστικά με C# χρησιμοποιώντας το Aspose.HTML. ## Σύναψη diff --git a/html/greek/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/greek/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..60393467a --- /dev/null +++ b/html/greek/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-04-23 +description: Εφαρμόστε το στυλ γραμματοσειράς προγραμματιστικά και μάθετε πώς να αφαιρέσετε + την υπογράμμιση από το κείμενο, να αλλάξετε το στυλ κειμένου και να ορίσετε έντονο + κείμενο προγραμματιστικά σε ένα σύντομο οδηγό. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: el +og_description: Εφαρμόστε το στυλ γραμματοσειράς προγραμματιστικά και ανακαλύψτε πώς + να αφαιρέσετε την υπογράμμιση από το κείμενο, να αλλάξετε το στυλ κειμένου και να + ορίσετε έντονο κείμενο προγραμματιστικά σε ένα σύντομο, πρακτικό οδηγό. +og_title: Εφαρμογή Στυλ Γραμματοσειράς Προγραμματιστικά – Γρήγορος Οδηγός C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Εφαρμογή Στυλ Γραμματοσειράς Προγραμματιστικά – Σύντομος Οδηγός C# +url: /el/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εφαρμογή Στυλ Γραμματοσειράς Προγραμματιστικά – Γρήγορος Οδηγός C# + +Έχετε ποτέ χρειαστεί να **εφαρμόσετε στυλ γραμματοσειράς** σε ένα στοιχείο UI αλλά δεν ήξερτε από πού να ξεκινήσετε; Δεν είστε οι μόνοι—οι περισσότεροι προγραμματιστές αντιμετωπίζουν αυτό το πρόβλημα όταν πειραματίζονται για πρώτη φορά με δυναμική μορφοποίηση κειμένου. Τα καλά νέα; Σε λίγα μόνο λεπτά θα ξέρετε ακριβώς πώς να αλλάξετε την εμφάνιση μιας ετικέτας, να αφαιρέσετε την υπογράμμιση από το κείμενο και να ορίσετε έντονο κείμενο προγραμματιστικά χωρίς να ψάχνετε σε ατελείωτη τεκμηρίωση. + +Σε αυτό το **μαθήμα μορφοποίησης κειμένου** θα περάσουμε από ένα πλήρες, εκτελέσιμο παράδειγμα, θα εξηγήσουμε το «γιατί» πίσω από κάθε γραμμή και θα προσθέσουμε πρακτικές συμβουλές που μπορείτε να αντιγράψετε‑επικολλήσετε σε οποιοδήποτε έργο WinForms ή WPF. Χωρίς περιττές πληροφορίες, μόνο ό,τι χρειάζεται για να ολοκληρωθεί η εργασία. + +--- + +## Τι Θα Μάθετε + +- Πώς να **εφαρμόσετε στυλ γραμματοσειράς** χρησιμοποιώντας μια μικρή βοηθητική κλάση. +- Τα ακριβή βήματα για **αφαίρεση υπογράμμισης από το κείμενο** διατηρώντας τα άλλα στυλ ανέπαφα. +- Τρόποι για **αλλαγή στυλ κειμένου** (έντονο, πλάγιο, υπογράμμιση) εν κινήσει. +- Ένα πλήρες, έτοιμο για αντιγραφή απόσπασμα που **ορίζει έντονο κείμενο προγραμματιστικά**. +- Κοινές παγίδες και διαχείριση ειδικών περιπτώσεων ώστε να μην εκπλαγείτε αργότερα. + +**Προαπαιτούμενα:** .NET 6+ (ή οποιοδήποτε πρόσφατο .NET Framework), βασικές γνώσεις C# και ένα IDE της επιλογής σας (Visual Studio, Rider ή VS Code). Αυτό είναι όλο—δεν απαιτούνται επιπλέον πακέτα NuGet. + +## Βήμα 1 – Εφαρμογή Στυλ Γραμματοσειράς στο Στοιχείο Σας + +Ο πυρήνας κάθε λειτουργίας **εφαρμογής στυλ γραμματοσειράς** είναι ένα enum `FontStyle` συνδυασμένο με ένα αντικείμενο `Font`. Για να διατηρήσουμε τον κώδικα καθαρό, θα τυλίξουμε τη λογική του enum μέσα σε μια μικρή κλάση `WebFontStyle`. Αυτή η κλάση αντικατοπτρίζει τις ιδιότητες που είδατε στο αρχικό απόσπασμα (`Bold`, `Italic`, `Underline`) και δημιουργεί μια τιμή `FontStyle` που μπορείτε να περάσετε στο `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Γιατί αυτό είναι σημαντικό:** +Απομονώνοντας τη λογική δημιουργίας σημαιών, αποφεύγετε τη διάσπαση των bitwise `|` λειτουργιών σε όλο τον κώδικα UI. Είναι πιο εύκολο στην ανάγνωση, πιο εύκολο στη δοκιμή, και—το πιο σημαντικό—κάνει την πρόθεση **εφαρμογής στυλ γραμματοσειράς** απόλυτα σαφή. + +## Βήμα 2 – Αφαίρεση Υπογράμμισης από το Κείμενο (και Διατήρηση των Άλλων Στυλ Ανεπηρέαστα) + +Ας υποθέσουμε ότι κληρονομείτε μια ετικέτα που είναι ήδη υπογραμμισμένη, αλλά το σχέδιο απαιτεί απλό έντονο κείμενο. Δεν θέλετε να χάσετε την έντονη γραφή ενώ αφαιρείτε την υπογράμμιση. Εδώ η κλάση `WebFontStyle` δείχνει την αξία της. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Κύριο σημείο:** Ορίζοντας `Underline = false` ρητά λέτε στο βοηθό να *εξαιρέσει* τη σημαία υπογράμμισης. Αν παραλείψετε τη γραμμή εντελώς, η προηγούμενη υπογράμμιση θα παραμείνει, κάτι που είναι κοινή πηγή σφαλμάτων όταν οι προγραμματιστές αλλάζουν μόνο την ιδιότητα `Bold`. + +## Βήμα 3 – Αλλαγή Στυλ Κειμένου: Έντονο, Πλάγιο και Περισσότερα + +Μπορεί να αναρωτιέστε, «Τι γίνεται αν χρειαστεί να εναλλάξω και το πλάγιο;» Το ίδιο αντικείμενο λειτουργεί για οποιονδήποτε συνδυασμό. Παρακάτω υπάρχει ένας γρήγορος πίνακας που μπορείτε να χρησιμοποιήσετε ως αναφορά κατά τον προγραμματισμό. + +| Επιθυμητό Στυλ | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **Μόνο Έντονο** | true | false | false | +| *Μόνο Πλάγιο* | false | true | false | +| **Έντονο + Πλάγιο** | true | true | false | +| **Έντονο + Underline** | true | false | true | + +Απλώς ορίστε τις ιδιότητες που χρειάζεστε και καλέστε το `ToFont`. Ο βοηθός κάνει το σκληρό έργο για εσάς, ώστε να μπορείτε να εστιάσετε στη λογική του UI. + +## Πλήρες Παράδειγμα – Ορισμός Έντονου Κειμένου Προγραμματιστικά + +Παρακάτω υπάρχει ένα **πλήρες, εκτελέσιμο παράδειγμα WinForms** που δείχνει όλα όσα καλύψαμε. Επικολλήστε το σε ένα νέο έργο WinForms τύπου console και πατήστε **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Αναμενόμενο Αποτέλεσμα + +Όταν εκτελέσετε το πρόγραμμα, εμφανίζεται ένα παράθυρο με το κείμενο **«Hello, world!»** εμφανιζόμενο **έντονα**, **μη πλάγια**, και **χωρίς καμία υπογράμμιση**. Αυτή η οπτική επιβεβαίωση σας δείχνει ότι η λογική **εφαρμογής στυλ γραμματοσειράς** λειτούργησε άψογα. + +## Επαγγελματικές Συμβουλές & Ειδικές Περιπτώσεις + +- **Δυναμικές ενημερώσεις:** Αν χρειαστεί να αλλάξετε το στυλ μετά την εμφάνιση της φόρμας (π.χ., ως απάντηση σε ένα checkbox), απλώς δημιουργήστε ξανά το στιγμιότυπο `WebFontStyle` ή τροποποιήστε τις ιδιότητές του και εκχωρήστε ξανά το `lbl.Font`. Το UI ενημερώνεται άμεσα. +- **Σκέψεις για High‑DPI:** Όταν αντικαθιστάτε ένα αντικείμενο `Font`, τα Windows το κλιμακώνουν αυτόματα βάσει του τρέχοντος DPI. Δεν απαιτείται επιπλέον κώδικας εκτός αν διαχειρίζεστε χειροκίνητα την κλιμάκωση. +- **Ισοδύναμο WPF:** Στο WPF θα δεσμεύετε `FontWeight`, `FontStyle` και `TextDecorations` αντί να ανταλλάσσετε ένα αντικείμενο `Font`. Η ίδια λογική διαχωρισμού ισχύει—κρατήστε τη λογική στυλ εκτός του επιπέδου προβολής. +- **Αποφυγή διαρροών μνήμης:** Η επαναανάθεση του `Label.Font` δημιουργεί ένα νέο αντικείμενο `Font`. Αποδεσμεύστε το παλιό αν αλλάζετε στυλ συχνά: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **εφαρμόσετε στυλ γραμματοσειράς** σε οποιοδήποτε στοιχείο .NET, **να αφαιρέσετε την υπογράμμιση από το κείμενο**, και **να αλλάξετε το στυλ κειμένου** εν κινήσει—όλα ενώ διατηρείτε τον κώδικά σας καθαρό και επαναχρησιμοποιήσιμο. Ο μικρός βοηθός `WebFontStyle` μετατρέπει μια σειρά boolean flags σε ένα σταθερό, δοκιμαστικό στοιχείο, και το πλήρες παράδειγμα αποδεικνύει ότι μπορείτε να **ορίσετε έντονο κείμενο προγραμματιστικά** σε λίγες μόνο γραμμές. + +Τι ακολουθεί; Δοκιμάστε να συνδυάσετε αυτή την προσέγγιση με ρυθμίσεις που ελέγχονται από τον χρήστη, ή πειραματιστείτε με άλλες σημαίες `FontStyle` όπως `Strikeout`. Μπορείτε ακόμη να εκθέσετε ένα μικρό πάνελ UI που επιτρέπει σε μη‑τεχνικούς χρήστες να επιλέγουν έντονο, πλάγιο ή υπογράμμιση σε χρόνο εκτέλεσης—χωρίς ανάγκη επαναμεταγλώττισης. + +Αν βρήκατε αυτό το **μαθήμα μορφοποίησης κειμένου** χρήσιμο, μη διστάσετε να αφήσετε ένα σχόλιο ή να μοιραστείτε τις δικές σας παραλλαγές. Καλή προγραμματιστική, και εύχομαι το UI σας να φαίνεται πάντα ακριβώς όπως το θέλετε! + +![Στιγμιότυπο οθόνης που δείχνει πώς να εφαρμόσετε στυλ γραμματοσειράς σε μια ετικέτα σε C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/greek/net/html-extensions-and-conversions/_index.md index 013b0ec4b..33c8f3346 100644 --- a/html/greek/net/html-extensions-and-conversions/_index.md +++ b/html/greek/net/html-extensions-and-conversions/_index.md @@ -73,7 +73,8 @@ url: /el/net/html-extensions-and-conversions/ Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# και Aspose.HTML. ### [Αποθήκευση HTML σε ZIP σε C# – Πλήρες Παράδειγμα Εντός Μνήμης](./save-html-to-zip-in-c-complete-in-memory-example/) Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας πλήρες παράδειγμα εντός μνήμης. - +### [Πώς να συμπιέσετε HTML σε C# – Οδηγός προσαρμοσμένου διαχειριστή πόρων](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Μάθετε πώς να συμπιέσετε HTML σε ZIP με προσαρμοσμένο διαχειριστή πόρων σε C# χρησιμοποιώντας το Aspose.HTML. ## Σύναψη Συμπερασματικά, οι επεκτάσεις και οι μετατροπές HTML είναι βασικά στοιχεία της σύγχρονης ανάπτυξης ιστού. Το Aspose.HTML για .NET απλοποιεί τη διαδικασία και το καθιστά προσβάσιμο σε προγραμματιστές όλων των επιπέδων. Ακολουθώντας τα σεμινάρια μας, θα είστε σε καλό δρόμο για να γίνετε ικανός προγραμματιστής ιστού με ευρύ σύνολο δεξιοτήτων. diff --git a/html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..fc360ea4d --- /dev/null +++ b/html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Μάθετε πώς να συμπιέζετε HTML σε C# χρησιμοποιώντας έναν προσαρμοσμένο + διαχειριστή πόρων – βήμα‑βήμα οδηγός για την αποθήκευση του HTML ως ZIP, τη μετατροπή + του HTML σε ZIP και τη δημιουργία ZIP από HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: el +og_description: 'πώς να συμπιέσετε html σε C# εξηγείται: χρησιμοποιήστε έναν προσαρμοσμένο + διαχειριστή πόρων για να αποθηκεύσετε το html ως zip, μετατρέψτε το html σε zip + και δημιουργήστε zip από html σε λίγα λεπτά.' +og_title: πώς να συμπιέσετε html σε C# – Οδηγός προσαρμοσμένου διαχειριστή πόρων +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: πώς να συμπιέσετε HTML σε C# – οδηγός προσαρμοσμένου διαχειριστή πόρων +url: /el/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# πώς να συμπιέσετε html σε C# – οδηγός προσαρμοσμένου διαχειριστή πόρων + +Έχετε ποτέ αναρωτηθεί **πώς να συμπιέσετε html** απευθείας από τον κώδικα C# χωρίς να δημιουργήσετε αρχεία στο δίσκο πρώτα; Δεν είστε μόνοι. Πολλοί προγραμματιστές αντιμετωπίζουν πρόβλημα όταν πρέπει να συσκευάσουν μια σελίδα HTML μαζί με το CSS, τις εικόνες και τις γραμματοσειρές της για διανομή εκτός σύνδεσης, και καταλήγουν να γράφουν ad‑hoc κώδικα αρχείου που γρήγορα γίνεται εφιάλτης συντήρησης. + +Σε αυτό το tutorial θα λύσουμε το πρόβλημα δείχνοντάς σας μια καθαρή, επαναχρησιμοποιήσιμη προσέγγιση που **αποθηκεύει HTML ως αρχείο ZIP** χρησιμοποιώντας το `ResourceHandler` του Aspose.HTML. Θα αναφερθούμε επίσης στο **πώς να μετατρέψετε HTML σε ZIP**, και θα παρουσιάσουμε ένα μοτίβο που μπορείτε να επαναχρησιμοποιήσετε για **δημιουργία ZIP από HTML** σε οποιοδήποτε έργο .NET. Χωρίς εξωτερικά scripts, χωρίς προσωρινά φακέλους—απλώς καθαρός C#. + +Στο τέλος του οδηγού θα έχετε ένα έτοιμο δείγμα που παράγει ένα `result.zip` που περιέχει όλους τους συνδεδεμένους πόρους, συν μια σειρά πρακτικών συμβουλών που μπορείτε να εφαρμόσετε στα δικά σας έργα. + +## Προαπαιτούμενα + +- .NET 6+ (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7.2, αλλά προτείνουμε το πιο πρόσφατο SDK) +- Πακέτο NuGet Aspose.HTML for .NET (`Aspose.HTML`) – εγκαταστήστε το με `dotnet add package Aspose.HTML` +- Βασική εξοικείωση με streams και το namespace `System.IO.Compression` +- Ένα IDE ή επεξεργαστή της επιλογής σας (Visual Studio, VS Code, Rider…) + +Αν έχετε ήδη όλα αυτά έτοιμα, τέλεια—ας περάσουμε κατευθείαν στον κώδικα. Αν όχι, το μόνο που λείπει είναι μια γραμμή εγκατάστασης NuGet· τα υπόλοιπα είναι ενσωματωμένα. + +## Βήμα 1: Δημιουργία ενός Απλού HTML Εγγράφου στη Μνήμη + +Πρώτα χρειάζεται ένα αντικείμενο `HTMLDocument` που να αντιπροσωπεύει τη σελίδα που θέλουμε να συμπιέσουμε. Σε πραγματικό σενάριο μπορεί να το φορτώσετε από URL ή αρχείο, αλλά για σαφήνεια θα δημιουργήσουμε ένα μικρό έγγραφο ενσωματωμένα. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Γιατί είναι σημαντικό:** +> Κρατώντας το έγγραφο στη μνήμη αποφεύγουμε οποιοδήποτε ενδιάμεσο I/O αρχείου, κάτι που κάνει το επόμενο βήμα **μετατροπή html σε zip** γρήγορο και ασφαλές για νήματα. + +## Βήμα 2: Προετοιμασία ενός In‑Memory ZIP Stream + +Αντί να γράψουμε ένα προσωρινό αρχείο `.zip` στο δίσκο, θα χρησιμοποιήσουμε ένα `MemoryStream`. Αυτό διατηρεί τα πάντα στη RAM, ιδανικό για web services ή background jobs που πρέπει να επιστρέψουν το αρχείο απευθείας στον πελάτη. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Συμβουλή:** Η δήλωση `using` διασφαλίζει ότι το stream απελευθερώνεται αυτόματα, αποτρέποντας διαρροές μνήμης. + +## Βήμα 3: Υλοποίηση Προσαρμοσμένου ResourceHandler + +Το Aspose.HTML καλεί ένα `ResourceHandler` για κάθε εξωτερικό πόρο που εντοπίζει (αρχεία CSS, εικόνες, γραμματοσειρές κ.λπ.). Κάνοντας subclass το `ResourceHandler` μπορούμε να αποφασίσουμε ακριβώς πού θα καταλήξει κάθε πόρος—στην περίπτωσή μας, ως καταχώρηση μέσα στο ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Γιατί ένας Προσαρμοσμένος Handler; + +- **Έλεγχος ονοματοδοσίας** – εσείς αποφασίζετε πώς θα εμφανίζεται κάθε αρχείο στο αρχείο. +- **Χωρίς προσωρινά αρχεία** – ο handler γράφει κατευθείαν στο in‑memory ZIP. +- **Επαναχρησιμοποίηση** – μπορείτε να ενσωματώσετε αυτήν την κλάση σε οποιοδήποτε έργο χρειάζεται **αποθήκευση html ως zip**. + +## Βήμα 4: Αποθήκευση του HTML Εγγράφου Χρησιμοποιώντας τον Handler + +Τώρα ενώνουμε όλα. Η μέθοδος `Save` θα καλέσει το `HandleResource` για κάθε συνδεδεμένο πόρο, και ο handler θα ρέει τα bytes μέσα στο ZIP που δημιουργήσαμε νωρίτερα. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Τι συμβαίνει στο παρασκήνιο;** +> Το Aspose αναλύει το HTML, εντοπίζει την αναφορά ``, ζητάει από τον handler ένα stream, και ο handler δημιουργεί μια καταχώρηση `logo.png` μέσα στο ZIP. Η ίδια ροή επαναλαμβάνεται για CSS, γραμματοσειρές ή οποιονδήποτε άλλο εξωτερικό πόρο. + +## Βήμα 5: Αποθήκευση του ZIP Αρχείου στο Δίσκο (ή Επιστροφή του) + +Τέλος, γράφουμε το in‑memory αρχείο σε δίσκο. Σε ένα web API μπορείτε αντί αυτού να επιστρέψετε `zipMemoryStream.ToArray()` ως πίνακα byte. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Αναμενόμενο Αποτέλεσμα + +Ανοίξτε το `result.zip` και θα δείτε: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Αν ανοίξετε το αρχείο σε εξερευνητή, θα παρατηρήσετε ότι το HTML αποθηκεύεται ως `resource.bin` επειδή δεν του δώσαμε φιλικό όνομα. Μπορείτε εύκολα να το βελτιώσετε ελέγχοντας το `resourceInfo.ContentType` και ορίζοντας `.html` όταν είναι κατάλληλο. + +## Πλήρες Παράδειγμα Εργασίας + +Παρακάτω βρίσκεται το πλήρες, έτοιμο για αντιγραφή πρόγραμμα που ενσωματώνει όλα τα παραπάνω βήματα. Εκτελέστε το από μια console εφαρμογή και θα λάβετε ένα έτοιμο προς διανομή αρχείο ZIP. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Εκτελώντας αυτόν τον κώδικα** θα δημιουργηθεί το `result.zip` στον τρέχοντα φάκελο εργασίας του προγράμματος. Ανοίξτε το και θα βρείτε το `index.html` (η αρχική μας σελίδα) καθώς και το `logo.png` αν αυτή η εικόνα υπήρχε στο δίσκο ή λήφθηκε από URL. + +## Κοινές Παραλλαγές & Ακραίες Περιπτώσεις + +| Σενάριο + +{{< /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/generate-jpg-and-png-images/_index.md b/html/hindi/net/generate-jpg-and-png-images/_index.md index b35cbb62e..1e6f67885 100644 --- a/html/hindi/net/generate-jpg-and-png-images/_index.md +++ b/html/hindi/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ HTML दस्तावेज़ों में हेरफेर करने DOCX फ़ाइलों को PNG या JPG में परिवर्तित करते समय एंटीएलियासिंग को सक्षम करने के चरणों को जानें। ### [DOCX को PNG में परिवर्तित करें – ZIP आर्काइव बनाएं C# ट्यूटोरियल](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# में DOCX फ़ाइलों को PNG छवियों में बदलें और उन्हें ZIP आर्काइव में संकलित करना सीखें। चरण-दर-चरण मार्गदर्शिका। +### [HTML से PNG बनाएं – C# डेवलपर्स के लिए चरण‑दर‑चरण गाइड](./create-png-from-html-step-by-step-guide-for-c-developers/) +C# में Aspose.HTML का उपयोग करके HTML को PNG में बदलने की पूरी प्रक्रिया सीखें। ## निष्कर्ष diff --git a/html/hindi/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/hindi/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..92c680f73 --- /dev/null +++ b/html/hindi/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Aspose.HTML के साथ HTML से जल्दी PNG बनाएं। जानें कि HTML को PNG में + कैसे रेंडर करें, कैनवास का आकार सेट करें, बैकग्राउंड रंग जोड़ें, और रेंडर की गई + छवि को मिनटों में सहेजें। +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: hi +og_description: Aspose.HTML के साथ HTML से PNG बनाएं। यह गाइड दिखाता है कि HTML को + PNG में कैसे रेंडर करें, कैनवास का आकार सेट करें, बैकग्राउंड रंग जोड़ें, और रेंडर + की गई छवि को सहेजें। +og_title: HTML से PNG बनाएं – पूर्ण C# रेंडरिंग ट्यूटोरियल +tags: +- C# +- Aspose.HTML +- Image Rendering +title: HTML से PNG बनाएं – C# डेवलपर्स के लिए चरण‑दर‑चरण गाइड +url: /hi/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML से PNG बनाएं – पूर्ण C# रेंडरिंग ट्यूटोरियल + +क्या आपको कभी **HTML से PNG बनाना** पड़ा है लेकिन आप सुनिश्चित नहीं थे कि कौन सी लाइब्रेरी आपको स्पष्ट, एंटीएलियास्ड परिणाम देगी? आप अकेले नहीं हैं। कई वेब‑टू‑इमेज पाइपलाइनों में सबसे बड़ी समस्या यह है कि टेक्स्ट और ग्राफिक्स को ब्राउज़र में जैसा दिखता है, वैसा ही तेज़ बनाना। + +अच्छी खबर? Aspose.HTML के साथ आप **HTML को PNG में रेंडर** कर सकते हैं कुछ ही लाइनों में, कैनवास आकार को नियंत्रित कर सकते हैं, ठोस बैकग्राउंड रंग जोड़ सकते हैं, और अंत में **रेंडर की गई इमेज** को डिस्क पर सहेज सकते हैं—बिना किसी ब्राउज़र को छुए। इस ट्यूटोरियल में हम पूरी प्रक्रिया को चरण‑दर‑चरण देखेंगे, समझाएंगे कि प्रत्येक सेटिंग क्यों महत्वपूर्ण है, और आपको एक तैयार‑चलाने‑योग्य उदाहरण दिखाएंगे। + +## आप क्या सीखेंगे + +- एक स्ट्रिंग, फ़ाइल, या URL से HTML लोड करने का तरीका +- पूर्वानुमेय आउटपुट के लिए **set canvas size** और **add background color** को कॉन्फ़िगर करने का तरीका +- रैज़र‑शार्प हेडिंग्स के लिए एंटीएलियासिंग और सब‑पिक्सेल टेक्स्ट हिन्टिंग को सक्षम करना +- **rendered image** को PNG फ़ाइल के रूप में **save** करने के सटीक चरण +- सामान्य समस्याएँ और विभिन्न परिदृश्यों के लिए वैकल्पिक ट्यूनिंग + +Aspose.HTML के साथ कोई पूर्व अनुभव आवश्यक नहीं है; बस एक बुनियादी C# सेटअप और Visual Studio (या आपका पसंदीदा IDE) चाहिए। + +--- + +## चरण 1: .NET के लिए Aspose.HTML स्थापित करें + +कोड लिखने से पहले, सुनिश्चित करें कि आपके प्रोजेक्ट में Aspose.HTML NuGet पैकेज रेफ़रेंस किया गया है। + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** नवीनतम स्थिर संस्करण (अप्रैल 2026, 23.9.0 तक) का उपयोग करें ताकि आपको नवीनतम रेंडरिंग इंजन और बग फ़िक्स मिलें। + +--- + +## चरण 2: HTML स्रोत लोड करें – HTML से PNG बनाएं + +आप रेंडरर को एक इनलाइन स्ट्रिंग, स्थानीय फ़ाइल, या रिमोट URL दे सकते हैं। इस डेमो के लिए हम एक सरल इनलाइन स्ट्रिंग का उपयोग करेंगे जिसमें कस्टम फ़ॉन्ट वाला हेडिंग होगा। + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Why this matters:** `HTMLDocument` में HTML लोड करने से इंजन को DOM पार्सिंग, CSS कैस्केड, और लेआउट गणनाओं पर पूर्ण नियंत्रण मिलता है। यह रेंडरिंग को किसी भी बाहरी ब्राउज़र स्थिति से अलग करता है, जिससे परिणाम पुनरुत्पादनीय होते हैं। + +--- + +## चरण 3: रेंडरिंग विकल्प कॉन्फ़िगर करें – कैनवास आकार सेट करें और बैकग्राउंड रंग जोड़ें + +`ImageRenderingOptions` क्लास आपको आउटपुट इमेज को बारीकी से ट्यून करने देता है। यहाँ हम एंटीएलियासिंग सक्षम करेंगे, सफ़ेद बैकग्राउंड सेट करेंगे, और स्पष्ट रूप से **800 × 600 px** का कैनवास परिभाषित करेंगे। + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Why you might change these values:** +- **Canvas size:** यदि आपको थंबनेल चाहिए, तो आयाम घटाएँ; उच्च‑रिज़ॉल्यूशन प्रिंट के लिए उन्हें बढ़ाएँ। +- **Background color:** ट्रांसपेरेंट PNG संभव हैं, लेकिन कई डाउनस्ट्रीम टूल्स (जैसे PowerPoint) एक अपारदर्शी बैकग्राउंड की अपेक्षा करते हैं। + +--- + +## चरण 4: रेंडर करें और **रेंडर की गई इमेज** को PNG के रूप में **Save** करें + +अब मुख्य कार्य यहाँ होता है। `ImageRenderer` `HTMLDocument` और हमने अभी परिभाषित विकल्पों को उपयोग करता है, फिर PNG स्ट्रीम को डिस्क पर लिखता है। + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +जब आप प्रोग्राम चलाएँगे, तो आपके डेस्कटॉप पर `result.png` मिलेगा। इसे खोलें, और आपको सफ़ेद कैनवास पर केंद्रित एक साफ़, एंटीएलियास्ड हेडिंग दिखेगी। + +> **Expected output:** सफ़ेद बैकग्राउंड और टेक्स्ट “Antialiased Heading” Arial में रेंडर किया हुआ 800 × 600 PNG, जो Chrome में जैसा स्मूद दिखता है वैसा ही दिखेगा। + +--- + +## चरण 5: परिणाम सत्यापित करें – त्वरित जांच + +1. **File existence:** `File.Exists(outputPath)` को `true` लौटाना चाहिए। +2. **Dimensions:** PNG को किसी भी इमेज व्यूअर में खोलें; यह 800 × 600 px दिखाएगा। +3. **Visual quality:** 200 % ज़ूम करें – टेक्स्ट किनारे स्मूद रहने चाहिए, न कि खुरदुरे। + +यदि कुछ भी गलत दिखे, तो दोबारा जांचें कि `UseAntialiasing` और `UseHinting` दोनों `true` पर सेट हैं। ये दो फ़्लैग उच्च‑गुणवत्ता वाले रेंडरिंग के लिए गुप्त मसाला हैं। + +--- + +## सामान्य विविधताएँ और किनारे के मामले + +| परिदृश्य | क्या बदलें | क्यों | +|----------|------------|------| +| **रिमोट वेब पेज रेंडर करें** | `new HTMLDocument(htmlContent)` को `new HTMLDocument("https://example.com")` से बदलें | HTML को मैन्युअली कॉपी किए बिना लाइव साइट को कैप्चर करने की अनुमति देता है। | +| **पारदर्शी बैकग्राउंड** | `BackgroundColor = Color.Transparent` सेट करें और `ImageFormat.Png` उपयोग करें | PNG को अन्य ग्राफिक्स पर ओवरले करने के लिए उपयोगी। | +| **विभिन्न इमेज फ़ॉर्मेट** | `renderer.Save(pngStream, ImageFormat.Jpeg)` बदलें | फ़ोटोग्राफिक कंटेंट के लिए JPEG छोटा हो सकता है, लेकिन लॉसलेस क्वालिटी खो देता है। | +| **डायनामिक कैनवास आकार** | लेआउट के बाद `imgOptions.Width = htmlDoc.Body.ClientWidth;` उपयोग करें | इमेज को HTML कंटेंट की प्राकृतिक चौड़ाई से मेल करने देता है। | +| **हाई‑DPI आउटपुट** | `Width` और `Height` को स्केल फ़ैक्टर (जैसे, 2) से गुणा करें | आधुनिक डिस्प्ले के लिए रेटिना‑रेडी एसेट बनाता है। | + +--- + +## पूर्ण कार्यशील उदाहरण (कॉपी‑पेस्ट तैयार) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +प्रोग्राम चलाएँ (`dotnet run` या Visual Studio में F5 दबाएँ) और आपके पास एक पूरी तरह से रेंडर किया हुआ PNG होगा, जिसे आप ईमेल, रिपोर्ट, या किसी भी जगह जहाँ आपको HTML की स्थिर इमेज चाहिए, उपयोग कर सकते हैं। + +--- + +## अक्सर पूछे जाने वाले प्रश्न + +**Q: क्या यह CSS 3 फीचर्स जैसे flexbox के साथ काम करता है?** +A: हाँ। Aspose.HTML अधिकांश आधुनिक CSS को सपोर्ट करता है, जिसमें flexbox, grid, और media queries शामिल हैं। बस यह सुनिश्चित करें कि आप नवीनतम लाइब्रेरी संस्करण पर हैं। + +**Q: अगर मेरा HTML बाहरी इमेजेज़ को रेफ़र करता है तो?** +A: रेंडरर डॉक्यूमेंट की बेस URI के आधार पर रिलेटिव URL को फॉलो करता है। यदि आप HTML को स्ट्रिंग से लोड करते हैं, तो `doc.BaseUrl` को उन एसेट्स वाले फ़ोल्डर पर सेट करें। + +**Q: क्या मैं कई पेज़ को एक PNG में रेंडर कर सकता हूँ?** +A: सीधे नहीं—प्रत्येक `ImageRenderer` कॉल एक सिंगल रास्टर इमेज बनाती है। मल्टी‑पेज आउटपुट के लिए, प्रत्येक पेज को अलग‑अलग रेंडर करें और उन्हें किसी ग्राफ़िक्स लाइब्रेरी (जैसे, ImageSharp) से जोड़ें। + +--- + +## निष्कर्ष + +अब आपके पास Aspose.HTML का उपयोग करके **HTML से PNG बनाना** का एक ठोस, एंड‑टू‑एंड समाधान है। **render html to png** विकल्पों को कॉन्फ़िगर करके—जैसे **set canvas size**, **add background color**, और एंटीएलियासिंग सक्षम करके—आप बिना ब्राउज़र के प्रोफेशनल‑ग्रेड इमेज बना सकते हैं। + +अब आप उच्च DPI, पारदर्शी बैकग्राउंड, या कई HTML स्निपेट्स को बैच‑प्रोसेस करने के साथ प्रयोग कर सकते हैं। वही पैटर्न थंबनेल सर्विस, PDF जेनरेशन पाइपलाइन, या स्टैटिक साइट प्रीव्यू टूल बनाने में लागू होता है। + +रेंडरिंग का आनंद लें, और यदि कोई समस्या आए तो टिप्पणी छोड़ने में संकोच न करें! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hindi/net/html-document-manipulation/_index.md b/html/hindi/net/html-document-manipulation/_index.md index 8f5af5f85..886450e46 100644 --- a/html/hindi/net/html-document-manipulation/_index.md +++ b/html/hindi/net/html-document-manipulation/_index.md @@ -58,11 +58,11 @@ HTML दस्तावेज़ों के साथ काम करने ### [Aspose.HTML के साथ .NET में URL का उपयोग करके HTML लोड करें](./load-html-using-url/) .NET के लिए Aspose.HTML की शक्ति का उपयोग करना सीखें। HTML मैनिपुलेशन और रेंडरिंग के साथ अपने वेब डेवलपमेंट को बढ़ावा दें। ### [Aspose.HTML के साथ .NET में दस्तावेज़ बनाना](./creating-a-document/) -.NET के लिए Aspose.HTML की शक्ति का लाभ उठाएँ। HTML और SVG दस्तावेज़ों को आसानी से बनाना, उनमें हेरफेर करना और उन्हें अनुकूलित करना सीखें। चरण-दर-चरण उदाहरण और अक्सर पूछे जाने वाले प्रश्न देखें। +.NET के लिए Aspose.HTML की शक्ति का लाभ उठाएँ। HTML और SVG दस्तावेज़ों को आसानी से बनाना, उनमें हेरफेर करना और उन्हें अनुकूलित करना सीखें। चरण-दर-स्टेप उदाहरण और अक्सर पूछे जाने वाले प्रश्न देखें। ### [Aspose.HTML के साथ .NET में दस्तावेज़ संपादित करना](./editing-a-document/) .NET के लिए Aspose.HTML के साथ आकर्षक वेब सामग्री बनाएँ। HTML, CSS, और अधिक में हेरफेर करना सीखें। ### [Aspose.HTML के साथ .NET में दस्तावेज़ सहेजना](./saving-a-document/) -हमारे चरण-दर-चरण गाइड के साथ .NET के लिए Aspose.HTML की शक्ति अनलॉक करें। HTML और SVG दस्तावेज़ बनाना, उनमें बदलाव करना और उन्हें परिवर्तित करना सीखें +हमारे चरण-दर-स्टेप गाइड के साथ .NET के लिए Aspose.HTML की शक्ति अनलॉक करें। HTML और SVG दस्तावेज़ बनाना, उनमें बदलाव करना और उन्हें परिवर्तित करना सीखें ### [Aspose.HTML के साथ .NET में HTML को Json के साथ मर्ज करें](./merge-html-with-json/) .NET के लिए Aspose.HTML का उपयोग करके गतिशील और वेब सामग्री बनाना सीखें। अपनी ऑनलाइन उपस्थिति को सशक्त बनाएँ और अपने दर्शकों को जोड़ें। ### [Aspose.HTML के साथ .NET में HTML को XML के साथ मर्ज करें](./merge-html-with-xml/) @@ -72,6 +72,9 @@ HTML दस्तावेज़ों के साथ काम करने ### [C# में स्ट्रिंग से HTML बनाएं – कस्टम रिसोर्स हैंडलर गाइड](./create-html-from-string-in-c-custom-resource-handler-guide/) C# में स्ट्रिंग से HTML उत्पन्न करने और कस्टम रिसोर्स हैंडलर का उपयोग करके इसे लोड करने की प्रक्रिया सीखें। +### [फ़ॉन्ट शैली को प्रोग्रामेटिक रूप से लागू करें – त्वरित C# गाइड](./apply-font-style-programmatically-quick-c-guide/) +C# में प्रोग्रामेटिक रूप से फ़ॉन्ट शैली लागू करने के चरण-दर-चरण निर्देश। + ## निष्कर्ष अंत में, यदि आप Aspose.HTML for .NET का उपयोग करके HTML दस्तावेज़ हेरफेर में महारत हासिल करना चाहते हैं, तो आप सही जगह पर हैं। हमारे ट्यूटोरियल आपकी सफलता के लिए रोडमैप हैं। संभावनाओं का पता लगाने, अपनी रचनात्मकता को अनलॉक करने और अपने .NET विकास को सुव्यवस्थित करने के लिए तैयार हो जाइए। आज ही अपनी यात्रा शुरू करें, और अपने HTML दस्तावेज़ों को अपनी आँखों के सामने बदलते हुए देखें। चाहे आप डेवलपर हों या उत्साही, Aspose.HTML for .NET में आपके लिए कुछ अविश्वसनीय है। तो, आप किसका इंतज़ार कर रहे हैं? आइए इस रोमांचक साहसिक कार्य को एक साथ शुरू करें! diff --git a/html/hindi/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/hindi/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..f90d7ec63 --- /dev/null +++ b/html/hindi/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: फ़ॉन्ट शैली को प्रोग्रामेटिकली लागू करें और संक्षिप्त ट्यूटोरियल में + टेक्स्ट से अंडरलाइन हटाना, टेक्स्ट शैली बदलना, और प्रोग्रामेटिकली बोल्ड टेक्स्ट + सेट करना सीखें। +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: hi +og_description: फ़ॉन्ट शैली को प्रोग्रामेटिकली लागू करें और जानें कि टेक्स्ट से अंडरलाइन + कैसे हटाएँ, टेक्स्ट शैली बदलें, और प्रोग्रामेटिकली बोल्ड टेक्स्ट कैसे सेट करें, + एक संक्षिप्त, व्यावहारिक ट्यूटोरियल में। +og_title: फ़ॉन्ट शैली को प्रोग्रामेटिक रूप से लागू करें – त्वरित C# गाइड +tags: +- csharp +- ui +- text-formatting +- programming +title: फ़ॉन्ट शैली को प्रोग्रामेटिकली लागू करें – त्वरित C# गाइड +url: /hi/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# प्रोग्रामेटिकली फ़ॉन्ट स्टाइल लागू करें – त्वरित C# गाइड + +क्या आपको कभी **फ़ॉन्ट स्टाइल लागू** करने की ज़रूरत पड़ी लेकिन शुरुआत नहीं पता थी? आप अकेले नहीं हैं—ज्यादातर डेवलपर्स को पहली बार डायनामिक टेक्स्ट फ़ॉर्मेटिंग करते समय यही समस्या आती है। अच्छी खबर? कुछ ही मिनटों में आप जान जाएंगे कि लेबल की उपस्थिति कैसे बदलें, टेक्स्ट से अंडरलाइन कैसे हटाएँ, और बॉल्ड टेक्स्ट प्रोग्रामेटिकली कैसे सेट करें बिना अनगिनत डॉक्यूमेंट्स के बीच खोजे। + +इस **टेक्स्ट फ़ॉर्मेटिंग ट्यूटोरियल** में हम एक पूर्ण, चलने योग्य उदाहरण पर चलते हैं, प्रत्येक लाइन के “क्यों” को समझाते हैं, और व्यावहारिक टिप्स देते हैं जिन्हें आप किसी भी WinForms या WPF प्रोजेक्ट में कॉपी‑पेस्ट कर सकते हैं। कोई फ़ज़ नहीं, सिर्फ वही चीज़ें जो काम करती हैं। + +--- + +## आप क्या सीखेंगे + +- एक छोटे हेल्पर क्लास का उपयोग करके **फ़ॉन्ट स्टाइल लागू** करना। +- **टेक्स्ट से अंडरलाइन हटाने** के सटीक कदम, जबकि अन्य स्टाइल्स बरकरार रहें। +- रन‑टाइम पर **टेक्स्ट स्टाइल बदलने** (बोल्ड, इटैलिक, अंडरलाइन) के तरीके। +- एक पूर्ण, कॉपी‑रेडी स्निपेट जो **प्रोग्रामेटिकली बॉल्ड टेक्स्ट सेट** करता है। +- सामान्य पिटफ़ॉल्स और एज‑केस हैंडलिंग ताकि बाद में आश्चर्य न हो। + +**पूर्वापेक्षाएँ:** .NET 6+ (या कोई भी हालिया .NET Framework), बुनियादी C# ज्ञान, और आपका पसंदीदा IDE (Visual Studio, Rider, या VS Code)। बस इतना ही—कोई अतिरिक्त NuGet पैकेज नहीं चाहिए। + +--- + +## चरण 1 – अपने कंट्रोल पर फ़ॉन्ट स्टाइल लागू करें + +किसी भी **फ़ॉन्ट स्टाइल लागू** ऑपरेशन का मूल `FontStyle` एनेम और `Font` ऑब्जेक्ट का संयोजन है। कोड को साफ़ रखने के लिए हम एनेम लॉजिक को एक छोटे `WebFontStyle` क्लास में रैप करेंगे। यह क्लास उन प्रॉपर्टीज़ को दर्शाता है जो आपने मूल स्निपेट में देखी थीं (`Bold`, `Italic`, `Underline`) और एक `FontStyle` वैल्यू बनाता है जिसे आप `Font` को पास कर सकते हैं। + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**यह क्यों महत्वपूर्ण है:** +फ़्लैग‑बिल्डिंग लॉजिक को अलग करके, आप बिटवाइज़ `|` ऑपरेशन्स को अपने UI कोड में बिखरने से बचते हैं। पढ़ने में आसान, टेस्ट करने में आसान, और—सबसे महत्वपूर्ण—**फ़ॉन्ट स्टाइल लागू** इरादा स्पष्ट बनाता है। + +--- + +## चरण 2 – टेक्स्ट से अंडरलाइन हटाएँ (और अन्य स्टाइल्स बरकरार रखें) + +मान लीजिए आपके पास एक लेबल है जो पहले से अंडरलाइन है, लेकिन डिज़ाइन में साधारण बॉल्ड टेक्स्ट चाहिए। आप बॉल्डनेस खोए बिना अंडरलाइन हटाना चाहते हैं। यहाँ `WebFontStyle` क्लास काम आती है। + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**मुख्य बिंदु:** `Underline = false` सेट करने से हेल्पर को *अंडरलाइन फ़्लैग को बाहर* करने को स्पष्ट रूप से बताया जाता है। यदि आप यह लाइन पूरी तरह छोड़ दें तो पिछली अंडरलाइन बनी रहेगी, जो अक्सर तब बग बन जाता है जब डेवलपर्स केवल `Bold` प्रॉपर्टी टॉगल करते हैं। + +--- + +## चरण 3 – टेक्स्ट स्टाइल बदलें: बॉल्ड, इटैलिक, और अधिक + +आप सोच सकते हैं, “अगर मुझे इटैलिक भी टॉगल करना हो तो?” वही ऑब्जेक्ट किसी भी संयोजन के लिए काम करता है। नीचे एक त्वरित मैट्रिक्स है जिसे आप कोडिंग के दौरान रेफ़रेंस कर सकते हैं। + +| इच्छित स्टाइल | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **केवल बॉल्ड** | true | false | false | +| *केवल इटैलिक* | false | true | false | +| **बॉल्ड + इटैलिक** | true | true | false | +| **बॉल्ड + अंडरलाइन** | true | false | true | + +सिर्फ वह प्रॉपर्टीज़ सेट करें जिनकी आपको ज़रूरत है और `ToFont` को कॉल करें। हेल्पर आपके लिए भारी काम कर लेगा, ताकि आप UI लॉजिक पर ध्यान दे सकें। + +--- + +## पूर्ण उदाहरण – प्रोग्रामेटिकली बॉल्ड टेक्स्ट सेट करें + +नीचे एक **पूर्ण, चलने योग्य WinForms** उदाहरण है जो हमने अब तक कवर किया है। इसे एक नए कंसोल‑स्टाइल WinForms प्रोजेक्ट में पेस्ट करें और **F5** दबाएँ। + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### अपेक्षित परिणाम + +जब आप प्रोग्राम चलाएँगे, एक विंडो खुलेगी जिसमें टेक्स्ट **“Hello, world!”** **बॉल्ड**, **इटैलिक नहीं**, और **बिना किसी अंडरलाइन** के दिखेगा। यह विज़ुअल कन्फर्मेशन बताता है कि **फ़ॉन्ट स्टाइल लागू** लॉजिक पूरी तरह काम कर रहा है। + +--- + +## प्रो टिप्स एवं एज केस + +- **डायनामिक अपडेट:** यदि आपको फॉर्म दिखाने के बाद स्टाइल बदलनी हो (जैसे चेकबॉक्स के जवाब में), बस `WebFontStyle` इंस्टेंस को फिर से बनाएँ या उसकी प्रॉपर्टीज़ बदलें और `lbl.Font` को पुनः असाइन करें। UI तुरंत अपडेट हो जाएगा। +- **हाई‑DPI विचार:** जब आप `Font` ऑब्जेक्ट बदलते हैं, विंडोज़ स्वचालित रूप से वर्तमान DPI के आधार पर स्केल करता है। अतिरिक्त कोड की ज़रूरत नहीं जब तक आप मैन्युअली स्केलिंग नहीं संभाल रहे हों। +- **WPF समकक्ष:** WPF में आप `FontWeight`, `FontStyle`, और `TextDecorations` को बाइंड करेंगे, न कि `Font` ऑब्जेक्ट को स्वैप करेंगे। वही लॉजिकल विभाजन लागू होता है—स्टाइल लॉजिक को व्यू लेयर से बाहर रखें। +- **मेमोरी लीक्स से बचें:** `Label.Font` को पुनः असाइन करने से नया `Font` ऑब्जेक्ट बनता है। यदि आप बार‑बार स्टाइल बदल रहे हैं तो पुराने को डिस्पोज़ करें: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## निष्कर्ष + +अब आप किसी भी .NET कंट्रोल पर **फ़ॉन्ट स्टाइल लागू**, **टेक्स्ट से अंडरलाइन हटाने**, और **रन‑टाइम पर टेक्स्ट स्टाइल बदलने** के तरीके जानते हैं—और वह भी कोड को साफ़ और पुन: उपयोग योग्य रखते हुए। छोटा `WebFontStyle` हेल्पर कुछ बूलियन फ़्लैग्स को एक ठोस, टेस्टेबल कंपोनेंट में बदल देता है, और पूर्ण उदाहरण सिद्ध करता है कि आप केवल कुछ लाइनों में **प्रोग्रामेटिकली बॉल्ड टेक्स्ट सेट** कर सकते हैं। + +अब क्या? इस एप्रोच को यूज़र‑ड्रिवन सेटिंग्स के साथ मिलाएँ, या अन्य `FontStyle` फ़्लैग्स जैसे `Strikeout` के साथ प्रयोग करें। आप एक छोटा UI पैनल भी बना सकते हैं जो नॉन‑टेक्निकल यूज़र्स को रन‑टाइम पर बॉल्ड, इटैलिक, या अंडरलाइन चुनने की अनुमति देता है—बिना री‑कम्पाइल के। + +यदि आपको यह **टेक्स्ट फ़ॉर्मेटिंग ट्यूटोरियल** उपयोगी लगा, तो टिप्पणी छोड़ें या अपनी खुद की वैरिएशन शेयर करें। कोडिंग का आनंद लें, और आपका UI हमेशा वही दिखे जैसा आप चाहते हैं! + +--- + +![फ़ॉन्ट स्टाइल को लेबल पर लागू करने का स्क्रीनशॉट C# में](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/hindi/net/html-extensions-and-conversions/_index.md index 45408d5a1..5f99bbab5 100644 --- a/html/hindi/net/html-extensions-and-conversions/_index.md +++ b/html/hindi/net/html-extensions-and-conversions/_index.md @@ -30,7 +30,7 @@ HTML एक्सटेंशन डेवलपर्स के लिए ए ## Aspose.HTML के साथ आरंभ करें -क्या आप शुरू करने के लिए तैयार हैं? .NET के लिए Aspose.HTML ट्यूटोरियल शुरुआती और अनुभवी डेवलपर्स दोनों के लिए हैं। चाहे आप HTML एक्सटेंशन और रूपांतरणों के लिए नए हों या उन्नत युक्तियों की तलाश कर रहे हों, हमारे चरण-दर-चरण मार्गदर्शिकाएँ आपकी आवश्यकताओं के अनुरूप डिज़ाइन की गई हैं। +क्या आप शुरू करने के लिए तैयार हैं? .NET के लिए Aspose.HTML ट्यूटोरियल शुरुआती और अनुभवी डेवलपर्स दोनों के लिए हैं। चाहे आप HTML एक्सटेंशन और रूपांतरणों के लिए नए हों या उन्नत युक्तियों की तलाश कर रहे हों, हमारे चरण-दर-स्टेप मार्गदर्शिकाएँ आपकी आवश्यकताओं के अनुरूप डिज़ाइन की गई हैं। ## .NET के लिए Aspose.HTML क्यों? @@ -90,6 +90,9 @@ Aspose.HTML for .NET का उपयोग करके स्टाइल् ### [C# में HTML को ZIP में सहेजें – पूर्ण इन‑मेमोरी उदाहरण](./save-html-to-zip-in-c-complete-in-memory-example/) C# में इन‑मेमोरी में HTML को ZIP फ़ाइल में सहेजने का पूरा उदाहरण देखें। +### [C# में HTML को ज़िप कैसे करें – कस्टम रिसोर्स हैंडलर गाइड](./how-to-zip-html-in-c-custom-resource-handler-guide/) +C# में कस्टम रिसोर्स हैंडलर का उपयोग करके HTML को ZIP फ़ाइल में सहेजने की चरण‑दर‑चरण मार्गदर्शिका। + ## निष्कर्ष निष्कर्ष में, HTML एक्सटेंशन और रूपांतरण आधुनिक वेब विकास के आवश्यक तत्व हैं। .NET के लिए Aspose.HTML प्रक्रिया को सरल बनाता है और इसे सभी स्तरों के डेवलपर्स के लिए सुलभ बनाता है। हमारे ट्यूटोरियल का पालन करके, आप एक व्यापक कौशल सेट के साथ एक कुशल वेब डेवलपर बनने के अपने रास्ते पर अच्छी तरह से आगे बढ़ेंगे। diff --git a/html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..ec328cd45 --- /dev/null +++ b/html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: कस्टम रिसोर्स हैंडलर का उपयोग करके C# में HTML को ज़िप करना सीखें – HTML + को ज़िप के रूप में सहेजने, HTML को ज़िप में बदलने, और HTML से ज़िप बनाने के लिए + चरण‑दर‑चरण गाइड। +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: hi +og_description: 'C# में HTML को ज़िप करने का तरीका समझाया गया: कस्टम रिसोर्स हैंडलर + का उपयोग करके HTML को ज़िप के रूप में सहेजें, HTML को ज़िप में बदलें, और मिनटों + में HTML से ज़िप बनाएं।' +og_title: C# में HTML को ज़िप कैसे करें – कस्टम संसाधन हैंडलर गाइड +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: C# में HTML को ज़िप कैसे करें – कस्टम रिसोर्स हैंडलर गाइड +url: /hi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में HTML को ज़िप कैसे करें – कस्टम रिसोर्स हैंडलर गाइड + +क्या आपने कभी **HTML को सीधे अपने C# कोड से ज़िप** करने के बारे में सोचा है बिना फ़ाइलों को डिस्क पर लिखे? आप अकेले नहीं हैं। कई डेवलपर्स को ऑफ़लाइन वितरण के लिए HTML पेज को उसके CSS, इमेजेज और फ़ॉन्ट्स के साथ पैकेज करने की ज़रूरत पड़ती है, और वे जल्दी ही रख‑रखाव में मुश्किल बन जाने वाले एड‑हॉक फ़ाइल‑सिस्टम कोड लिख देते हैं। + +इस ट्यूटोरियल में हम इस समस्या को हल करेंगे, एक साफ़, पुन: उपयोग योग्य तरीका दिखाते हुए जिससे **HTML को ZIP आर्काइव के रूप में सेव** किया जा सके Aspose.HTML के `ResourceHandler` का उपयोग करके। हम यह भी देखेंगे कि **HTML को ZIP में कैसे बदलें**, और एक पैटर्न प्रदर्शित करेंगे जिसे आप किसी भी .NET प्रोजेक्ट में **HTML से ZIP बनाने** के लिए पुन: उपयोग कर सकते हैं। कोई बाहरी स्क्रिप्ट नहीं, कोई टेम्पररी फ़ोल्डर नहीं—सिर्फ शुद्ध C#। + +गाइड के अंत तक आपके पास एक तैयार‑से‑चलाने वाला सैंपल होगा जो `result.zip` बनाता है, जिसमें हर लिंक्ड रिसोर्स शामिल होता है, साथ ही कुछ व्यावहारिक टिप्स भी मिलेंगे जिन्हें आप अपने प्रोजेक्ट्स में लागू कर सकते हैं। + +## Prerequisites + +- .NET 6+ (कोड .NET Framework 4.7.2 पर भी चलता है, लेकिन हम नवीनतम SDK की सलाह देते हैं) +- Aspose.HTML for .NET NuGet पैकेज (`Aspose.HTML`) – `dotnet add package Aspose.HTML` के द्वारा इंस्टॉल करें +- स्ट्रीम्स और `System.IO.Compression` नेमस्पेस की बुनियादी समझ +- आपका पसंदीदा IDE या एडिटर (Visual Studio, VS Code, Rider …) + +यदि आपके पास ये सब पहले से है, तो चलिए सीधे कोड की ओर बढ़ते हैं। यदि नहीं, तो केवल एक‑लाइन NuGet इंस्टॉल की ज़रूरत है; बाकी सब स्वयं‑समाहित है। + +## Step 1: Create a Simple HTML Document in Memory + +सबसे पहले हमें एक `HTMLDocument` ऑब्जेक्ट चाहिए जो उस पेज को दर्शाता है जिसे हम ज़िप करना चाहते हैं। वास्तविक दुनिया में आप इसे URL या फ़ाइल से लोड कर सकते हैं, लेकिन स्पष्टता के लिए हम यहाँ एक छोटा डॉक्यूमेंट इनलाइन बनाएँगे। + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Why this matters:** +> दस्तावेज़ को मेमोरी में रखकर हम किसी भी मध्यवर्ती फ़ाइल I/O से बचते हैं, जिससे बाद के **convert html to zip** चरण तेज़ और थ्रेड‑सेफ़ बनते हैं। + +## Step 2: Prepare an In‑Memory ZIP Stream + +टेम्पररी `.zip` फ़ाइल को डिस्क पर लिखने के बजाय, हम एक `MemoryStream` का उपयोग करेंगे। यह सब कुछ RAM में रखता है, जो वेब सर्विसेज या बैकग्राउंड जॉब्स के लिए आदर्श है जिन्हें आर्काइव सीधे क्लाइंट को लौटाना होता है। + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** `using` स्टेटमेंट यह सुनिश्चित करता है कि स्ट्रीम स्वतः डिस्पोज़ हो जाए, जिससे मेमोरी लीक नहीं होती। + +## Step 3: Implement a Custom ResourceHandler + +Aspose.HTML हर बाहरी एसेट (CSS फ़ाइलें, इमेजेज, फ़ॉन्ट्स आदि) के लिए एक `ResourceHandler` को कॉल करता है। `ResourceHandler` को सबक्लास करके हम तय कर सकते हैं कि प्रत्येक रिसोर्स कहाँ जाएगा—हमारे मामले में, ZIP आर्काइव के अंदर एक एंट्री के रूप में। + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Why a Custom Handler? + +- **Control over naming** – आप तय कर सकते हैं कि प्रत्येक फ़ाइल आर्काइव में कैसे दिखाई देगी। +- **No temporary files** – हैंडलर सीधे इन‑मेमोरी ZIP में लिखता है। +- **Reusability** – आप इस क्लास को किसी भी प्रोजेक्ट में डाल सकते हैं जिसे **save html as zip** की ज़रूरत है। + +## Step 4: Save the HTML Document Using the Handler + +अब सब कुछ जोड़ते हैं। `Save` मेथड हर लिंक्ड एसेट के लिए `HandleResource` को कॉल करेगा, और हैंडलर उन बाइट्स को पहले बनाए गए ZIP आर्काइव में स्ट्रीम करेगा। + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **What happens under the hood?** +> Aspose HTML को पार्स करता है, `` रेफ़रेंस खोजता है, हैंडलर से एक स्ट्रीम मांगता है, और हैंडलर ZIP के अंदर `logo.png` एंट्री बनाता है। वही प्रक्रिया CSS, फ़ॉन्ट्स या किसी भी अन्य बाहरी रिसोर्स के लिए दोहराई जाती है। + +## Step 5: Persist the ZIP Archive to Disk (or Return It) + +अंत में हम इन‑मेमोरी आर्काइव को फ़ाइल में लिखते हैं। वेब API में आप इसके बजाय `zipMemoryStream.ToArray()` को बाइट एरे के रूप में रिटर्न कर सकते हैं। + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Expected Result + +`result.zip` खोलें और आपको यह दिखेगा: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +यदि आप फ़ाइल एक्सप्लोरर में आर्काइव खोलते हैं तो आप देखेंगे कि HTML फ़ाइल `resource.bin` के रूप में स्टोर हुई है क्योंकि हमने उसे कोई दोस्ताना नाम नहीं दिया था। आप `resourceInfo.ContentType` की जाँच करके और उपयुक्त होने पर `.html` असाइन करके इसे आसानी से सुधार सकते हैं। + +## Full Working Example + +नीचे पूरा, कॉपी‑पेस्ट‑रेडी प्रोग्राम दिया गया है जिसमें ऊपर बताए गए सभी चरण शामिल हैं। इसे एक कंसोल ऐप से चलाएँ, और आपको एक तैयार‑से‑शेयर करने योग्य ZIP फ़ाइल मिल जाएगी। + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Running this code** आपके प्रोग्राम की वर्किंग डायरेक्टरी में `result.zip` जेनरेट करेगा। इसे खोलें और आपको `index.html` (हमारा मूल पेज) साथ में `logo.png` भी मिलेगा यदि वह इमेज डिस्क पर मौजूद थी या URL से फ़ेच हुई थी। + +## Common Variations & Edge Cases + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/hongkong/net/generate-jpg-and-png-images/_index.md index 33103bd04..454e67c1b 100644 --- a/html/hongkong/net/generate-jpg-and-png-images/_index.md +++ b/html/hongkong/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET 提供了一種將 HTML 轉換為映像的簡單方法。 了解如何在使用 Aspose.HTML for .NET 將 DOCX 轉換為 PNG 或 JPG 時啟用抗鋸齒,以提升圖像品質。 ### [使用 Aspose.HTML 在 .NET 中將 docx 轉換為 png 並建立 zip 壓縮檔 C# 教學](./convert-docx-to-png-create-zip-archive-c-tutorial/) 學習如何使用 Aspose.HTML for .NET 將 docx 轉換為 png,並將圖像打包成 zip 壓縮檔的完整步驟。 +### [C# 開發者逐步指南:從 HTML 建立 PNG](./create-png-from-html-step-by-step-guide-for-c-developers/) +學習如何使用 Aspose.HTML for .NET 在 C# 中將 HTML 轉換為 PNG 圖像的完整步驟。 ## 結論 diff --git a/html/hongkong/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/hongkong/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..4b153a2e7 --- /dev/null +++ b/html/hongkong/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-04-23 +description: 使用 Aspose.HTML 快速將 HTML 轉換為 PNG。了解如何將 HTML 渲染為 PNG、設定畫布大小、加入背景顏色,並在數分鐘內儲存渲染後的圖像。 +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: zh-hant +og_description: 使用 Aspose.HTML 從 HTML 生成 PNG。本指南說明如何將 HTML 轉換為 PNG、設定畫布大小、加入背景顏色,並儲存渲染後的圖像。 +og_title: 從 HTML 產生 PNG – 完整 C# 渲染教學 +tags: +- C# +- Aspose.HTML +- Image Rendering +title: 從 HTML 產生 PNG – C# 開發者逐步指南 +url: /zh-hant/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 從 HTML 建立 PNG – 完整 C# 呈現教學 + +有沒有曾經需要 **從 HTML 建立 PNG**,卻不確定哪個函式庫能提供清晰、抗鋸齒的效果?你並不孤單。在許多 web‑to‑image 工作流程中,最大的痛點是讓文字與圖形看起來和瀏覽器中一樣銳利。 + +好消息是?使用 Aspose.HTML,你可以在幾行程式碼內 **render HTML to PNG**,控制畫布大小、加入實心背景色,最後 **save rendered image** 到磁碟——完全不需要使用瀏覽器。在本教學中,我們將逐步說明整個流程,解釋每個設定的意義,並提供一個可直接執行的範例。 + +## 您將學會 + +- 如何從字串、檔案或 URL 載入 HTML +- 如何設定 **set canvas size** 與 **add background color** 以獲得可預測的輸出 +- 啟用抗鋸齒與次像素文字提示,以獲得銳利的標題 +- 將 **save rendered image** 以 PNG 檔案儲存的完整步驟 +- 常見陷阱與不同情境的可選調整 + +不需要事先了解 Aspose.HTML,只要有基本的 C# 環境與 Visual Studio(或你慣用的 IDE)即可。 + +--- + +## 步驟 1:安裝 Aspose.HTML for .NET + +在撰寫任何程式碼之前,先確保你的專案已參考 Aspose.HTML NuGet 套件。 + +```bash +dotnet add package Aspose.HTML +``` + +> **專業提示:** 使用最新的穩定版(截至 2026 年 4 月,23.9.0)以取得最新的渲染引擎與錯誤修正。 + +--- + +## 步驟 2:載入 HTML 來源 – 從 HTML 建立 PNG + +你可以將渲染器指向內嵌字串、本機檔案,或遠端 URL。此示範使用一段簡單的內嵌字串,內含自訂字型的標題。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**為什麼這很重要:** 將 HTML 載入 `HTMLDocument` 讓引擎能完整掌控 DOM 解析、CSS 繼承與版面計算。它也會將渲染與任何外部瀏覽器狀態隔離,確保結果可重現。 + +--- + +## 步驟 3:設定渲染選項 – 設定畫布大小與加入背景顏色 + +`ImageRenderingOptions` 類別讓你微調輸出影像。此處我們會啟用抗鋸齒、設定白色背景,並明確定義 **800 × 600 px** 的畫布。 + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**為什麼可能需要調整這些值:** +- **Canvas size(畫布大小):** 若需要縮圖,可縮小尺寸;若要高解析度列印,則增大尺寸。 +- **Background color(背景顏色):** 雖然可以產生透明 PNG,但許多下游工具(例如 PowerPoint)預期的是不透明背景。 + +--- + +## 步驟 4:渲染並 **Save Rendered Image** 為 PNG + +現在開始執行重量級工作。`ImageRenderer` 會使用先前的 `HTMLDocument` 與設定選項,然後將 PNG 資料流寫入磁碟。 + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +執行程式後,你會在桌面上看到 `result.png`。打開它,應該會看到一個置中於白色畫布上的乾淨、抗鋸齒標題。 + +> **預期輸出:** 一個 800 × 600 的 PNG,白色背景,文字為 “Antialiased Heading”,使用 Arial 字型,呈現效果與 Chrome 中相同平滑。 + +--- + +## 步驟 5:驗證結果 – 快速檢查 + +1. **檔案是否存在:** `File.Exists(outputPath)` 應回傳 `true`。 +2. **尺寸:** 在任何圖像檢視器中開啟 PNG,應顯示 800 × 600 px。 +3. **視覺品質:** 放大至 200 %——文字邊緣必須保持平滑,而非鋸齒狀。 + +如果有任何異常,請再次確認 `UseAntialiasing` 與 `UseHinting` 均設為 `true`。這兩個旗標是高品質渲染的關鍵。 + +--- + +## 常見變化與邊緣情況 + +| 情境 | 調整項目 | 原因 | +|----------|----------------|-----| +| **渲染遠端網頁** | 將 `new HTMLDocument(htmlContent)` 換成 `new HTMLDocument("https://example.com")` | 讓您在不手動複製 HTML 的情況下擷取即時網站。 | +| **透明背景** | 設定 `BackgroundColor = Color.Transparent` 並使用 `ImageFormat.Png` | 在其他圖形上疊加 PNG 時很有用。 | +| **不同的影像格式** | 將 `renderer.Save(pngStream, ImageFormat.Jpeg)` 改為其他格式 | 對於照片類內容 JPEG 可能較小,但會失去無損品質。 | +| **動態畫布大小** | 在版面配置後使用 `imgOptions.Width = htmlDoc.Body.ClientWidth;` | 讓影像符合 HTML 內容的自然寬度。 | +| **高 DPI 輸出** | 將 `Width` 與 `Height` 乘以比例因子(例如 2) | 為現代顯示器產生 Retina 準備的資產。 | + +--- + +## 完整可執行範例(直接複製貼上) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +執行程式(`dotnet run` 或在 Visual Studio 按 F5),即可得到一張完美渲染的 PNG,適用於電子郵件、報告或任何需要 HTML 靜態圖像的情境。 + +--- + +## 常見問答 + +**Q: 這能支援像 flexbox 之類的 CSS 3 功能嗎?** +A: 能。Aspose.HTML 支援大多數現代 CSS,包括 flexbox、grid 與 media queries。只要確保使用最新的函式庫版本即可。 + +**Q: 如果我的 HTML 參考了外部圖片怎麼辦?** +A: 渲染器會依據文件的 base URI 追蹤相對 URL。若你是從字串載入 HTML,請將 `doc.BaseUrl` 設為包含資源的資料夾路徑。 + +**Q: 能否將多頁渲染成同一個 PNG?** +A: 直接無法——每次呼叫 `ImageRenderer` 只會產生單一點陣圖。若需多頁輸出,請分別渲染每一頁,然後使用圖形函式庫(例如 ImageSharp)將它們拼接起來。 + +--- + +## 結論 + +現在你已掌握使用 Aspose.HTML **從 HTML 建立 PNG** 的完整端對端解決方案。透過設定 **render html to png** 選項——如 **set canvas size**、**add background color**,以及啟用抗鋸齒,你可以在不使用瀏覽器的情況下產生專業級影像。 + +接下來,你可以嘗試更高 DPI、透明背景,或批次處理大量 HTML 片段。無論是建立縮圖服務、PDF 產生管線,或是靜態網站預覽工具,這套模式都適用。 + +祝渲染順利,若有任何問題歡迎留言交流! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hongkong/net/html-document-manipulation/_index.md b/html/hongkong/net/html-document-manipulation/_index.md index 3cbe22369..96cac7496 100644 --- a/html/hongkong/net/html-document-manipulation/_index.md +++ b/html/hongkong/net/html-document-manipulation/_index.md @@ -51,27 +51,40 @@ Aspose.HTML for .NET 因其簡單性和強大功能而脫穎而出。它使您 ## HTML 文件操作教學課程 ### [使用 Aspose.HTML 在 .NET 中非同步載入 HTML 文檔](./load-html-doc-asynchronously/) 了解如何使用 Aspose.HTML for .NET 處理 HTML 文件。為開發人員提供包含範例和常見問題解答的逐步指南。 + ### [使用 Aspose.HTML 在 .NET 中載入帶有憑證的 HTML 文檔](./load-html-doc-with-credentials/) 了解如何使用 Aspose.HTML for .NET 來增強您的 SEO。提高排名、分析網路內容並針對搜尋引擎進行優化。 + ### [使用 Aspose.HTML 在 .NET 中使用遠端伺服器載入 HTML](./load-html-using-remote-server/) 透過我們的綜合指南釋放 Aspose.HTML for .NET 的潛力。了解如何匯入命名空間、存取遠端 HTML 文件等。 + ### [使用 .NET 中的 URL 和 Aspose.HTML 載入 HTML](./load-html-using-url/) 了解如何利用 Aspose.HTML for .NET 的強大功能。透過 HTML 操作和渲染來促進您的 Web 開發。 + ### [使用 Aspose.HTML 在 .NET 中建立文檔](./creating-a-document/) 釋放 Aspose.HTML for .NET 的強大功能。學習輕鬆建立、操作和優化 HTML 和 SVG 文件。探索逐步範例和常見問題。 + ### [使用 Aspose.HTML 在 .NET 中編輯文檔](./editing-a-document/) 使用 Aspose.HTML for .NET 建立引人入勝的 Web 內容。了解如何操作 HTML、CSS 等。 + ### [使用 Aspose.HTML 在 .NET 中儲存文檔](./saving-a-document/) 透過我們的逐步指南釋放 Aspose.HTML for .NET 的強大功能。學習建立、操作和轉換 HTML 和 SVG 文檔 + ### [使用 Aspose.HTML 將 .NET 中的 HTML 與 Json 合併](./merge-html-with-json/) 學習使用 Aspose.HTML for .NET 建立動態和 Web 內容。增強您的線上形象並吸引您的受眾。 + ### [使用 Aspose.HTML 將 .NET 中的 HTML 與 XML 合併](./merge-html-with-xml/) 學習使用 Aspose.HTML for .NET。透過此綜合指南匯入命名空間、將 HTML 與 XML 合併並增強您的 Web 開發技能。 + ### [使用 Aspose.HTML 在 .NET 中透過 XpsDevice 產生 XPS 文檔](./generate-xps-documents-by-xpsdevice/) 使用 Aspose.HTML for .NET 釋放 Web 開發的潛力。輕鬆建立、轉換和操作 HTML 文件。 + ### [在 C# 中從字串建立 HTML – 自訂資源處理程式指南](./create-html-from-string-in-c-custom-resource-handler-guide/) 了解如何使用 Aspose.HTML for .NET 從字串建立 HTML,並透過自訂資源處理程式進行管理。 +### [以程式方式套用字體樣式 – 快速 C# 指南](./apply-font-style-programmatically-quick-c-guide/) +了解如何在 C# 中以程式方式套用字體樣式,快速打造自訂化的 HTML 內容。 + ## 結論 總而言之,如果您想使用 Aspose.HTML for .NET 來掌握 HTML 文件操作,那麼您來對地方了。我們的教學是您成功的路線圖。準備好探索可能性、釋放您的創造力並簡化您的 .NET 開發。立即開始您的旅程,親眼目睹 HTML 文件的轉變。無論您是開發人員還是愛好者,Aspose.HTML for .NET 都為您提供了令人難以置信的東西。那麼,你還在等什麼?讓我們一起踏上這場令人興奮的冒險吧! diff --git a/html/hongkong/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/hongkong/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..f14a0bfcb --- /dev/null +++ b/html/hongkong/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-04-23 +description: 以程式方式套用字型樣式,並在簡明教學中學習如何移除文字底線、變更文字樣式以及設定粗體字。 +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: zh-hant +og_description: 以程式方式套用字型樣式,並在簡短實用的教學中了解如何移除文字底線、變更文字樣式,以及以程式方式設定粗體文字。 +og_title: 以程式方式套用字型樣式 – 快速 C# 指南 +tags: +- csharp +- ui +- text-formatting +- programming +title: 以程式方式套用字型樣式 – 快速 C# 指南 +url: /zh-hant/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 程式化套用字型樣式 – 快速 C# 指南 + +有沒有過想 **套用字型樣式** 到 UI 元件卻不知從何下手?你並不孤單——大多數開發者在首次玩轉動態文字格式時都會卡關。好消息是,只要幾分鐘,你就能精準地改變標籤外觀、移除文字底線,並以程式方式設定粗體,無需在文件中苦苦搜尋。 + +在本 **文字格式化教學** 中,我們會示範完整、可執行的範例,說明每一行背後的「為什麼」,並提供可直接 copy‑paste 到任何 WinForms 或 WPF 專案的實用技巧。沒有冗餘,只有讓你快速上手的重點。 + +--- + +## 你將學會什麼 + +- 如何使用小型輔助類別 **套用字型樣式**。 +- 在保留其他樣式的同時 **移除文字底線** 的精確步驟。 +- 即時 **變更文字樣式**(粗體、斜體、底線)的方式。 +- 一段完整、可直接使用的程式碼片段,**以程式方式設定粗體文字**。 +- 常見陷阱與邊緣案例處理,讓你不會在之後被嚇到。 + +**先備條件:** .NET 6+(或任何較新的 .NET Framework)、基礎 C# 知識,以及你慣用的 IDE(Visual Studio、Rider 或 VS Code)。僅此而已——不需要額外的 NuGet 套件。 + +--- + +## 步驟 1 – 為控制項套用字型樣式 + +任何 **套用字型樣式** 操作的核心都是 `FontStyle` 列舉搭配 `Font` 物件。為了讓程式碼保持整潔,我們會把列舉邏輯包在一個小型的 `WebFontStyle` 類別中。此類別對應原始片段中的屬性(`Bold`、`Italic`、`Underline`),並產生可傳遞給 `Font` 的 `FontStyle` 值。 + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**為什麼這麼做:** +透過將旗標組合邏輯抽離出來,你可以避免在 UI 程式碼中到處散布位元運算 `|`。這樣更易讀、更易測試,且最重要的是,讓 **套用字型樣式** 的意圖一目了然。 + +--- + +## 步驟 2 – 移除文字底線(同時保留其他樣式) + +假設你接手的標籤已經有底線,但設計要求改為純粹的粗體。你不想在去除底線的同時失去粗體。這時 `WebFontStyle` 類別就派上用場。 + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**重點說明:** 將 `Underline = false` 明確設為 `false`,會告訴輔助類別 *排除* 底線旗標。如果完全省略這行,先前的底線仍會保留,這是開發者只切換 `Bold` 屬性時常見的錯誤來源。 + +--- + +## 步驟 3 – 變更文字樣式:粗體、斜體與更多 + +你可能會想,「如果同時需要切換斜體怎麼辦?」同一個物件可以支援任意組合。以下是一個快速參考矩陣,供你在編寫程式時使用。 + +| Desired Style | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **Bold only** | true | false | false | +| *Italic only* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +只要設定你需要的屬性,然後呼叫 `ToFont` 即可。輔助類別會幫你完成繁重的運算,讓你專注於 UI 邏輯。 + +--- + +## 完整範例 – 以程式方式設定粗體文字 + +以下是一個 **完整、可執行的 WinForms** 範例,示範了前面所有內容。將它貼到新建的 WinForms 專案(使用 console‑style 模板)中,然後按 **F5** 執行。 + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### 預期結果 + +執行程式後,會出現一個視窗,文字 **「Hello, world!」** 以 **粗體**、**非斜體**、且 **沒有底線** 的方式呈現。這個視覺驗證說明 **套用字型樣式** 的邏輯已正確運作。 + +--- + +## 專業小技巧與邊緣案例 + +- **動態更新:** 若需在表單顯示後變更樣式(例如勾選核取方塊時),只要重新建立 `WebFontStyle` 實例或修改其屬性,然後重新指派 `lbl.Font`。UI 會即時更新。 +- **高 DPI 考量:** 替換 `Font` 物件時,Windows 會自動依目前 DPI 進行縮放。除非你自行處理縮放,否則不需要額外程式碼。 +- **WPF 等價寫法:** 在 WPF 中,你會綁定 `FontWeight`、`FontStyle` 與 `TextDecorations`,而不是交換 `Font` 物件。相同的邏輯分離原則仍然適用——將樣式邏輯置於視圖層之外。 +- **避免記憶體洩漏:** 重新指派 `Label.Font` 會產生新的 `Font` 物件。若頻繁切換樣式,請記得釋放舊的物件:`var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## 結論 + +現在你已掌握如何 **套用字型樣式** 到任何 .NET 控制項、**移除文字底線**,以及 **即時變更文字樣式**,同時保持程式碼的乾淨與可重用。小巧的 `WebFontStyle` 輔助類別將一堆布林旗標轉化為可測試的元件,而完整範例則證明你可以在短短幾行程式碼內 **以程式方式設定粗體文字**。 + +接下來可以嘗試將此方法與使用者設定結合,或實驗其他 `FontStyle` 旗標(如 `Strikeout`)。甚至可以打造一個小型 UI 面板,讓非技術人員在執行時即選擇粗體、斜體或底線——無需重新編譯。 + +如果你覺得這篇 **文字格式化教學** 有幫助,歡迎留下評論或分享你的變化版本。祝編程愉快,願你的 UI 永遠如你所願! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/hongkong/net/html-extensions-and-conversions/_index.md index 3d146ada2..23f7558d5 100644 --- a/html/hongkong/net/html-extensions-and-conversions/_index.md +++ b/html/hongkong/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 使用 Aspose.HTML for .NET 將 HTML 文件壓縮為 ZIP 檔案,提供完整的 C# 範例與步驟說明。 ### [在 C# 中將 HTML 儲存為 ZIP – 完整的記憶體內示例](./save-html-to-zip-in-c-complete-in-memory-example/) 示範如何在 C# 中使用 Aspose.HTML 將 HTML 內容直接壓縮成 ZIP 檔案,全部在記憶體中完成。 +### [如何在 C# 中壓縮 HTML – 自訂資源處理器指南](./how-to-zip-html-in-c-custom-resource-handler-guide/) +了解如何使用 Aspose.HTML for .NET 在 C# 中透過自訂資源處理器將 HTML 壓縮為 ZIP,提供完整範例與步驟說明。 ## 結論 diff --git a/html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..176ae6295 --- /dev/null +++ b/html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-23 +description: 學習如何在 C# 中使用自訂資源處理程式將 HTML 壓縮成 zip – 步驟教學,教你將 HTML 儲存為 zip、將 HTML 轉換為 + zip,以及從 HTML 建立 zip。 +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: zh-hant +og_description: 如何在 C# 中壓縮 HTML:使用自訂資源處理程式將 HTML 儲存為 ZIP、將 HTML 轉換為 ZIP,並在幾分鐘內從 HTML + 建立 ZIP。 +og_title: 如何在 C# 中壓縮 HTML – 自訂資源處理程式指南 +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: 如何在 C# 中壓縮 HTML – 自訂資源處理程式指南 +url: /zh-hant/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中壓縮 HTML – 自訂資源處理程式指南 + +有沒有想過 **如何直接在 C# 程式碼中壓縮 HTML**,而不必先把檔案寫到磁碟?你並不孤單。許多開發者在需要將 HTML 頁面與其 CSS、圖片、字型等資源一起打包成離線可用的檔案時,往往會卡在必須自行編寫臨時檔案系統程式碼,結果很快變成難以維護的惡夢。 + +在本教學中,我們將透過 Aspose.HTML 的 `ResourceHandler`,示範一種 **將 HTML 儲存為 ZIP 壓縮檔** 的乾淨、可重用做法。還會說明 **將 HTML 轉成 ZIP** 的概念,並示範一個可以在任何 .NET 專案中 **從 HTML 建立 ZIP** 的範本。無需外部腳本、無需暫存資料夾——純粹使用 C#。 + +閱讀完本指南後,你將擁有一個可直接執行的範例,會產生 `result.zip`,裡面包含所有連結的資源,並提供一系列實用技巧,讓你可以套用到自己的專案中。 + +## 前置條件 + +- .NET 6+(程式碼同樣支援 .NET Framework 4.7.2,但建議使用最新 SDK) +- Aspose.HTML for .NET NuGet 套件(`Aspose.HTML`)——透過 `dotnet add package Aspose.HTML` 安裝 +- 具備基本的 Stream 與 `System.IO.Compression` 命名空間概念 +- 你慣用的 IDE 或編輯器(Visual Studio、VS Code、Rider …) + +如果這些都已備妥,太好了——直接進入程式碼。如果還沒,只需要執行一行 NuGet 安裝指令,其他皆為自包含。 + +## 步驟 1:在記憶體中建立簡易 HTML 文件 + +首先,我們需要一個 `HTMLDocument` 物件,代表要壓縮的頁面。實務上可能會從 URL 或檔案載入,但為了說明,我們直接在程式內建構一個小文件。 + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **為什麼這很重要:** +> 把文件保留在記憶體中,可避免任何中間的檔案 I/O,讓之後的 **convert html to zip** 步驟更快且具備執行緒安全性。 + +## 步驟 2:準備記憶體中的 ZIP 串流 + +我們不會把暫存的 `.zip` 檔寫到磁碟,而是使用 `MemoryStream`。這樣所有資料都留在 RAM 中,非常適合需要直接回傳壓縮檔給客戶端的 Web 服務或背景工作。 + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **小技巧:** `using` 陳述式會自動釋放串流,避免記憶體泄漏。 + +## 步驟 3:實作自訂 ResourceHandler + +Aspose.HTML 會為每一個外部資產(CSS、圖片、字型等)呼叫 `ResourceHandler`。透過繼承 `ResourceHandler`,我們可以自行決定每個資源的最終去向——在本例中,就是寫入 ZIP 檔內的條目。 + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### 為什麼需要自訂處理程式? + +- **命名可控** – 你可以自行決定檔案在壓縮檔中的名稱。 +- **不產生暫存檔** – 處理程式直接寫入記憶體中的 ZIP。 +- **可重用** – 只要把這個類別加入任何需要 **save html as zip** 的專案,即可使用。 + +## 步驟 4:使用自訂處理程式儲存 HTML 文件 + +現在把所有部件串起來。`Save` 方法會為每個連結資產呼叫 `HandleResource`,而處理程式會把這些位元組寫入先前建立的 ZIP 串流。 + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **底層發生了什麼?** +> Aspose 解析 HTML,發現 `` 後,向處理程式請求串流,處理程式隨即在 ZIP 中建立 `logo.png` 條目。相同的流程會對 CSS、字型或其他外部資源重複執行。 + +## 步驟 5:將 ZIP 壓縮檔寫入磁碟(或回傳) + +最後,我們把記憶體中的壓縮檔寫成實體檔案。若是在 Web API 中,則可以改為回傳 `zipMemoryStream.ToArray()` 作為位元組陣列。 + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### 預期結果 + +開啟 `result.zip`,你應該會看到: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +如果你在檔案總管中檢視壓縮檔,會發現 HTML 檔被存成 `resource.bin`,因為我們沒有給它友善的名稱。只要檢查 `resourceInfo.ContentType`,在適當時候改為 `.html`,即可輕鬆改善。 + +## 完整範例程式 + +以下是可直接複製貼上的完整程式碼,包含上述所有步驟。將它放入 Console 應用程式執行,即可得到可分享的 ZIP 檔。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**執行此程式** 後,會在程式的工作目錄產生 `result.zip`。打開後,你會看到 `index.html`(原始頁面)以及 `logo.png`(若該圖片存在於磁碟或可從 URL 取得)。 + +## 常見變形與邊緣案例 + +| 情況 + +{{< /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/generate-jpg-and-png-images/_index.md b/html/hungarian/net/generate-jpg-and-png-images/_index.md index dc2c2b0ac..b53cda9bf 100644 --- a/html/hungarian/net/generate-jpg-and-png-images/_index.md +++ b/html/hungarian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,7 @@ Tanulja meg az Aspose.HTML for .NET használatát HTML-dokumentumok kezeléséhe Ismerje meg, hogyan állíthatja be az antialiasingot a DOCX dokumentumok PNG vagy JPG képekké konvertálásakor az Aspose.HTML for .NET használatával. ### [docx konvertálása png-re – zip archívum létrehozása C# oktatóanyag](./convert-docx-to-png-create-zip-archive-c-tutorial/) Ismerje meg, hogyan konvertálhat docx fájlokat png képekké, majd csomagolhatja őket zip archívumba C#-ban az Aspose.HTML segítségével. +### [PNG létrehozása HTML‑ből – Lépésről‑lépésre útmutató C# fejlesztőknek](./create-png-from-html-step-by-step-guide-for-c-developers/) ## Következtetés diff --git a/html/hungarian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/hungarian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..48d414d8a --- /dev/null +++ b/html/hungarian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Készíts PNG-t HTML-ből gyorsan az Aspose.HTML segítségével. Tanulja meg, + hogyan renderelhet HTML-t PNG-re, állíthatja be a vászon méretét, adhat hozzá háttérszínt, + és mentheti a renderelt képet percek alatt. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: hu +og_description: PNG létrehozása HTML-ből az Aspose.HTML használatával. Ez az útmutató + bemutatja, hogyan rendereljük a HTML-t PNG-re, állítsuk be a vászon méretét, adjunk + hozzá háttérszínt, és mentsük el a renderelt képet. +og_title: PNG létrehozása HTML‑ből – Teljes C# renderelési útmutató +tags: +- C# +- Aspose.HTML +- Image Rendering +title: PNG létrehozása HTML‑ből – Lépésről‑lépésre útmutató C# fejlesztőknek +url: /hu/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PNG létrehozása HTML‑ből – Teljes C# renderelési útmutató + +Valaha is szükséged volt **PNG létrehozására HTML‑ből**, de nem tudtad, melyik könyvtár adja a tiszta, antialiasolt eredményeket? Nem vagy egyedül. Sok web‑to‑image folyamatban a legnagyobb gond a szöveg és a grafika élességének megőrzése, ahogy a böngészőben látható. + +A jó hír? Az Aspose.HTML‑vel **HTML‑t PNG‑re renderelhetsz** néhány sor kóddal, szabályozhatod a vászon méretét, hozzáadhatsz egy egységes háttérszínt, és végül **elmentheted a renderelt képet** a lemezre – mindezt böngésző használata nélkül. Ebben az útmutatóban végigvezetünk a teljes folyamaton, elmagyarázzuk, miért fontos minden beállítás, és bemutatunk egy azonnal futtatható példát. + +## Mit fogsz megtanulni + +- Hogyan tölts be HTML‑t karakterláncból, fájlból vagy URL‑ről +- Hogyan konfiguráld a **canvas méret beállítását** és a **háttérszín hozzáadását** a kiszámítható kimenethez +- Az antialiasing és a sub‑pixel szövegtippek engedélyezése a szuperéles fejlécekhez +- A pontos lépések a **renderelt kép mentéséhez** PNG fájlként +- Gyakori buktatók és opcionális finomhangolások különböző helyzetekhez + +Az Aspose.HTML‑hez nincs szükség előzetes tapasztalatra; elegendő egy alap C# környezet és a Visual Studio (vagy a kedvenc IDE‑d). + +--- + +## 1. lépés: Aspose.HTML telepítése .NET‑hez + +Mielőtt kódot írnánk, győződj meg róla, hogy az Aspose.HTML NuGet csomag hivatkozásként szerepel a projektedben. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tipp:** Használd a legújabb stabil verziót (2026. április állapotában, 23.9.0), hogy megkapd a legújabb renderelő motor és hibajavítások. + +--- + +## 2. lépés: HTML forrás betöltése – PNG létrehozása HTML‑ből + +A renderelőnek átadhatsz egy beágyazott karakterláncot, egy helyi fájlt vagy egy távoli URL‑t. Ebben a bemutatóban egy egyszerű beágyazott karakterláncot használunk, amely egy egyedi betűtípussal ellátott címsort tartalmaz. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Miért fontos:** A HTML betöltése egy `HTMLDocument`‑be teljes irányítást ad a motor számára a DOM elemzés, a CSS kaszkád és a layout számítások felett. Emellett elkülöníti a renderelést bármilyen külső böngésző állapottól, biztosítva az újraalkotható eredményeket. + +--- + +## 3. lépés: Renderelési beállítások konfigurálása – Canvas méret beállítása és háttérszín hozzáadása + +Az `ImageRenderingOptions` osztály lehetővé teszi a kimeneti kép finomhangolását. Itt engedélyezzük az antialiasing‑et, fehér háttérszínt állítunk be, és kifejezetten meghatározunk egy **800 × 600 px** méretű vászont. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Miért módosíthatod ezeket az értékeket:** +- **Canvas méret:** Ha miniatűrre van szükséged, csökkentsd a méreteket; magas felbontású nyomtatáshoz növeld őket. +- **Háttérszín:** Átlátszó PNG-k lehetségesek, de sok downstream eszköz (pl. PowerPoint) átlátszatlan háttérre számít. + +--- + +## 4. lépés: Renderelés és **renderelt kép mentése** PNG‑ként + +Most jön a nehéz munka. Az `ImageRenderer` felhasználja a `HTMLDocument`‑et és a most definiált beállításokat, majd egy PNG adatfolyamot ír a lemezre. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +A program futtatásakor a `result.png` fájlt a asztalon fogod megtalálni. Nyisd meg, és egy tiszta, antialiasolt címsort kell látnod, amely a fehér vászon közepén helyezkedik el. + +> **Várható kimenet:** Egy 800 × 600 méretű PNG fehér háttérrel és az „Antialiased Heading” szöveggel, Arial betűtípussal renderelve, amely annyira sima, mint a Chrome‑ban. + +--- + +## 5. lépés: Az eredmény ellenőrzése – Gyors ellenőrzések + +1. **Fájl létezése:** A `File.Exists(outputPath)` `true`‑t kell, hogy adjon. +2. **Méretek:** Nyisd meg a PNG‑t bármely képnézőben; 800 × 600 px‑et kell jelentenie. +3. **Vizuális minőség:** Nagyíts 200 %-ra – a szöveg szélei továbbra is simának kell maradniuk, nem szaggatottnak. + +Ha valami nem megfelelő, ellenőrizd, hogy a `UseAntialiasing` és a `UseHinting` is `true`‑ra van állítva. Ezek a két jelző a titkos összetevő a magas minőségű rendereléshez. + +--- + +## Gyakori variációk és szélsőséges esetek + +| Szenárió | Mit kell módosítani | Miért | +|----------|---------------------|-------| +| **Távoli weboldal renderelése** | Cseréld le a `new HTMLDocument(htmlContent)`-t `new HTMLDocument("https://example.com")`-ra | Lehetővé teszi élő oldalak rögzítését HTML manuális másolása nélkül. | +| **Átlátszó háttér** | Állítsd `BackgroundColor = Color.Transparent`-re és használd az `ImageFormat.Png`-t | Hasznos, ha a PNG‑t más grafikákra szeretnéd átfedni. | +| **Különböző képformátum** | Módosítsd `renderer.Save(pngStream, ImageFormat.Jpeg)`-re | A JPEG kisebb lehet fotós tartalmaknál, de elveszíti a veszteségmentes minőséget. | +| **Dinamikus vászonméret** | Használd a `imgOptions.Width = htmlDoc.Body.ClientWidth;`-t a layout után | Lehetővé teszi, hogy a kép a HTML tartalom természetes szélességéhez igazodjon. | +| **Nagy DPI‑kimenet** | Szorozd meg a `Width` és `Height` értékeket egy skálázási tényezővel (pl. 2) | Retina‑kész eszközöket generál a modern kijelzőkhöz. | + +--- + +## Teljes működő példa (másolás-beillesztés kész) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Futtasd a programot (`dotnet run` vagy nyomd meg az F5‑öt a Visual Studio‑ban), és egy tökéletesen renderelt PNG‑t kapsz, amely készen áll az e‑mailekben, jelentésekben vagy bármely más helyen való használatra, ahol statikus HTML‑képre van szükség. + +--- + +## Gyakran ismételt kérdések + +**K: Működik ez CSS 3 funkciókkal, például flexbox‑szal?** +V: Igen. Az Aspose.HTML támogatja a legtöbb modern CSS‑t, beleértve a flexbox‑ot, a grid‑et és a media query‑ket. Csak győződj meg róla, hogy a legújabb könyvtárverziót használod. + +**K: Mi van, ha a HTML külső képekre hivatkozik?** +V: A renderelő a dokumentum alap‑URI‑ja alapján követi a relatív URL‑eket. Ha HTML‑t karakterláncból töltesz be, állítsd be a `doc.BaseUrl`‑t arra a mappára, amely a forrásokat tartalmazza. + +**K: Renderelhetek több oldalt egy PNG‑be?** +V: Nem közvetlenül – minden `ImageRenderer` hívás egyetlen raszteres képet eredményez. Többoldalas kimenethez renderelj minden oldalt külön, majd egy grafikai könyvtárral (pl. ImageSharp) illeszd össze őket. + +--- + +## Összegzés + +Most már egy stabil, vég‑től‑végig megoldással rendelkezel a **PNG létrehozására HTML‑ből** az Aspose.HTML használatával. A **render html to png** beállítások – például a **canvas méret beállítása**, a **háttérszín hozzáadása**, és az antialiasing engedélyezése – konfigurálásával böngésző nélkül generálhatsz professzionális minőségű képeket. + +Innen tovább kísérletezhetsz magasabb DPI‑vel, átlátszó háttérrel vagy több tucat HTML‑részlet kötegelt feldolgozásával. Ugyanez a minta alkalmazható, akár egy miniatűr szolgáltatást, PDF‑generáló folyamatot vagy statikus weboldal előnézeti eszközt építesz. + +Boldog renderelést, és nyugodtan hagyj megjegyzést, ha elakadsz! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/hungarian/net/html-document-manipulation/_index.md index 4f88cba20..04780e070 100644 --- a/html/hungarian/net/html-document-manipulation/_index.md +++ b/html/hungarian/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Tanulja meg az Aspose.HTML használatát .NET-hez. Importáljon névteret, egyes Használja ki a webfejlesztésben rejlő lehetőségeket az Aspose.HTML for .NET segítségével. Könnyen hozhat létre, konvertálhat és kezelhet HTML dokumentumokat. ### [HTML létrehozása karakterláncból C#-ban – Egyéni erőforráskezelő útmutató](./create-html-from-string-in-c-custom-resource-handler-guide/) Ismerje meg, hogyan hozhat létre HTML-t karakterláncból C#-ban egy egyéni erőforráskezelő segítségével. +### [Betűstílus alkalmazása programozottan – Gyors C# útmutató](./apply-font-style-programmatically-quick-c-guide/) +Ismerje meg, hogyan alkalmazhat betűstílusokat C#-ban programozottan az Aspose.HTML segítségével. ## Következtetés diff --git a/html/hungarian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/hungarian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..b973df580 --- /dev/null +++ b/html/hungarian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Alkalmazz betűstílust programozottan, és tanuld meg, hogyan távolítható + el a szöveg aláhúzása, hogyan változtatható a szöveg stílusa, valamint hogyan állítható + be a félkövér szöveg programozottan egy tömör útmutatóban. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: hu +og_description: Alkalmazd a betűstílust programozott módon, és fedezd fel, hogyan + távolítható el a szöveg aláhúzása, hogyan változtatható a szöveg stílusa, valamint + hogyan állítható be a félkövér szöveg programozottan egy rövid, gyakorlati útmutatóban. +og_title: Betűstílus alkalmazása programozott módon – Gyors C# útmutató +tags: +- csharp +- ui +- text-formatting +- programming +title: Betűstílus alkalmazása programozottan – Gyors C# útmutató +url: /hu/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Betűstílus alkalmazása programozottan – Gyors C# útmutató + +Valaha is szükséged volt **betűstílus alkalmazására** egy UI elemhez, de nem tudtad, hol kezdjed? Nem vagy egyedül – a legtöbb fejlesztő ebben a helyzetben van, amikor először foglalkozik a dinamikus szövegformázással. A jó hír? Néhány perc alatt pontosan tudni fogod, hogyan változtasd meg egy címke megjelenését, hogyan távolítsd el az aláhúzást a szövegből, és hogyan állíts be félkövér szöveget programozottan anélkül, hogy végtelen dokumentációk között keresgélnél. + +Ebben a **szövegformázási oktatóanyagban** végigvezetünk egy teljes, futtatható példán, elmagyarázzuk a „miért” minden sor mögött, és gyakorlati tippeket adunk, amelyeket egyszerűen be‑másolhatsz bármely WinForms vagy WPF projektbe. Felesleges szóhasználat nélkül, csak a lényeg, ami a feladatot megoldja. + +--- + +## Mit fogsz megtanulni + +- Hogyan **alkalmazz betűstílust** egy apró segédosztály segítségével. +- A pontos lépések a **szöveg aláhúzásának eltávolításához**, miközben a többi stílus érintetlen marad. +- Módszerek a **szövegstílus módosítására** (félkövér, dőlt, aláhúzott) futás közben. +- Egy teljes, másolásra kész kódrészlet, amely **programozottan állít be félkövér szöveget**. +- Gyakori hibák és szélhelyzet‑kezelés, hogy később ne érjenek meglepetések. + +**Előfeltételek:** .NET 6+ (vagy bármely friss .NET Framework), alap C# ismeretek, valamint a kedvenc IDE‑d (Visual Studio, Rider vagy VS Code). Ennyi – nincs szükség extra NuGet csomagokra. + +--- + +## 1. lépés – Betűstílus alkalmazása az irányításon + +Bármely **betűstílus alkalmazás** művelet középpontjában egy `FontStyle` enum és egy `Font` objektum áll. A kód tisztasága érdekében a enum logikát egy kis `WebFontStyle` osztályba csomagoljuk. Ez az osztály tükrözi az eredeti kódrészletben látható tulajdonságokat (`Bold`, `Italic`, `Underline`), és egy `FontStyle` értéket épít, amelyet átadhatsz a `Font`‑nak. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Miért fontos:** +A flag‑építő logika elkülönítésével elkerülöd a bitwise `|` műveletek szétszórását a UI kódban. Könnyebben olvasható, könnyebben tesztelhető, és – ami a legfontosabb – a **betűstílus alkalmazása** szándékát kristálytiszta módon közvetíti. + +--- + +## 2. lépés – Aláhúzás eltávolítása a szövegből (és a többi stílus megtartása) + +Tegyük fel, hogy egy már aláhúzott címkét örököltél, de a tervezés egyszerű félkövér szöveget igényel. Nem szeretnéd elveszíteni a félkövérséget, miközben eltávolítod az aláhúzást. Itt jön jól jövedelmező a `WebFontStyle` osztály. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Kulcspont:** Az `Underline = false` beállítása kifejezetten azt mondja a segítőnek, hogy *kizárja* az aláhúzás flag‑et. Ha ezt a sort teljesen elhagynád, az előző aláhúzás megmarad, ami gyakori hiba, amikor a fejlesztők csak a `Bold` tulajdonságot kapcsolgatják. + +--- + +## 3. lépés – Szövegstílus módosítása: félkövér, dőlt és egyebek + +Lehet, hogy felmerül a kérdés: „Mi van, ha az italic‑ot is ki kell kapcsolni?” Ugyanaz az objektum bármilyen kombinációra használható. Az alábbi gyors mátrix segít a kódolás során. + +| Kívánt stílus | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **Csak félkövér** | true | false | false | +| *Csak dőlt* | false | true | false | +| **Félkövér + Dőlt** | true | true | false | +| **Félkövér + Aláhúzott** | true | false | true | + +Állítsd be a szükséges tulajdonságokat, majd hívd meg a `ToFont`‑t. A segítő elvégzi a nehéz munkát helyetted, így a UI logikára koncentrálhatsz. + +--- + +## Teljes példa – Félkövér szöveg programozott beállítása + +Az alábbi **teljes, futtatható WinForms** példa mindent bemutat, amit eddig tárgyaltunk. Másold be egy új, konzol‑stílusú WinForms projektbe, és nyomd meg az **F5**‑öt. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Várt eredmény + +A program futtatásakor egy ablak jelenik meg a **„Hello, world!”** szöveggel, amely **félkövér**, **nem dőlt**, és **nincs aláhúzva**. Ez a vizuális visszajelzés bizonyítja, hogy a **betűstílus alkalmazása** logika tökéletesen működik. + +--- + +## Profi tippek és szélhelyzetek + +- **Dinamikus frissítések:** Ha a forma megjelenése után (például egy jelölőnégyzetre reagálva) kell a stílust módosítani, egyszerűen hozd létre újra a `WebFontStyle` példányt, vagy módosítsd a tulajdonságait, majd rendeld hozzá újra a `lbl.Font`‑ot. A UI azonnal frissül. +- **High‑DPI szempontok:** Amikor egy `Font` objektumot cserélsz, a Windows automatikusan méretezni fogja a jelenlegi DPI alapján. Extra kód csak akkor szükséges, ha saját magad kezeled a skálázást. +- **WPF ekvivalens:** WPF‑ben a `FontWeight`, `FontStyle` és `TextDecorations` kötéseit használod a `Font` objektum cseréje helyett. Ugyanaz a logikai szeparáció érvényes – tartsd a stíluslogikát a view rétegtől távol. +- **Memóriaszivárgás elkerülése:** A `Label.Font` újra‑rendelése új `Font` objektumot hoz létre. Ha gyakran váltogatod a stílusokat, a régi objektumot szabadítsd fel: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Összegzés + +Most már tudod, hogyan **alkalmazz betűstílust** bármely .NET vezérlőn, hogyan **távolítsd el az aláhúzást a szövegből**, és hogyan **változtasd meg a szövegstílust** futás közben – mindezt tiszta és újrahasználható kóddal. A kis `WebFontStyle` segítő néhány logikai flag‑et egy szilárd, tesztelhető komponenssé alakít, a teljes példa pedig bizonyítja, hogy **programozottan beállíthatsz félkövér szöveget** néhány sorban. + +Mi a következő lépés? Próbáld meg kombinálni ezt a megközelítést felhasználó‑vezérelt beállításokkal, vagy kísérletezz más `FontStyle` flag‑ekkel, például a `Strikeout`‑tal. Készíthetsz egy kis UI panelt is, amely lehetővé teszi a nem technikai felhasználók számára, hogy futásidőben válasszanak félkövér, dőlt vagy aláhúzott stílust – újrafordítás nélkül. + +Ha hasznosnak találtad ezt a **szövegformázási oktatóanyagot**, nyugodtan hagyj megjegyzést vagy oszd meg saját variációidat. Boldog kódolást, és legyen a UI‑d mindig úgy, ahogy elképzelted! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/hungarian/net/html-extensions-and-conversions/_index.md index 53dd8b575..e4a39fe48 100644 --- a/html/hungarian/net/html-extensions-and-conversions/_index.md +++ b/html/hungarian/net/html-extensions-and-conversions/_index.md @@ -53,6 +53,8 @@ Az Aspose.HTML for .NET nem csak egy könyvtár; ez egy változás a webfejleszt Fedezze fel az Aspose.HTML erejét .NET-hez: A HTML-t könnyedén konvertálja XPS-re. Előfeltételek, lépésenkénti útmutató és GYIK mellékelve. ### [HTML zip-elése C#-ban – HTML mentése zip-be](./how-to-zip-html-in-c-save-html-to-zip/) Ismerje meg, hogyan csomagolhatja be a HTML-fájlokat zip-archívumba C#-ban az Aspose.HTML for .NET segítségével. +### [HTML zip-elése C#-ban – egyéni erőforráskezelő útmutató](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Ismerje meg, hogyan használhat egyéni erőforráskezelőt HTML zip-archívumok létrehozásához C#-ban az Aspose.HTML for .NET segítségével. ### [HTML-dokumentum létrehozása formázott szöveggel és exportálása PDF-be – Teljes útmutató](./create-html-document-with-styled-text-and-export-to-pdf-full/) Hozzon létre HTML-dokumentumot formázott szöveggel, majd exportálja PDF-be az Aspose.HTML for .NET segítségével. Lépésről lépésre útmutató. ### [PDF létrehozása HTML-ből – C# lépésről‑lépésre útmutató](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..311ea3304 --- /dev/null +++ b/html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Tanulja meg, hogyan lehet HTML-t zip‑elni C#‑ban egy egyedi erőforráskezelő + használatával – lépésről‑lépésre útmutató a HTML zipként mentéséhez, a HTML zip‑be + konvertálásához és a HTML‑ből zip létrehozásához. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: hu +og_description: 'hogyan zipeljük a HTML-t C#-ban, magyarázat: használj egy egyedi + erőforráskezelőt a HTML zipként mentéséhez, konvertáld a HTML-t zip-re, és percek + alatt készíts zip-et a HTML-ből.' +og_title: Hogyan zipeljük a HTML-t C#-ban – Egyedi erőforráskezelő útmutató +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: Hogyan zipeljük a HTML-t C#-ban – egyedi erőforráskezelő útmutató +url: /hu/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# hogyan zip-eljük a HTML-t C#-ban – egyedi erőforráskezelő útmutató + +Valaha is elgondolkodtál **hogyan zip-elj HTML-t** közvetlenül a C# kódodból anélkül, hogy előbb lemezre írnád a fájlokat? Nem vagy egyedül. Sok fejlesztő akadályba ütközik, amikor egy HTML oldalt a hozzá tartozó CSS‑szel, képekkel és betűtípusokkal kell offline terjesztésre csomagolni, és ilyenkor ad‑hoc fájlrendszer‑kódot ír, ami gyorsan karbantartási rémtámasszá válik. + +Ebben a tutorialban megoldjuk ezt a problémát egy tiszta, újrahasználható megközelítéssel, amely **HTML‑t ZIP archívummá ment** az Aspose.HTML `ResourceHandler`‑e segítségével. Rámutatunk arra is, hogyan **konvertáljunk HTML‑t ZIP‑ra**, és bemutatunk egy mintát, amelyet bármely .NET projektben újra felhasználhatsz a **ZIP létrehozásához HTML‑ből**. Nincs külső script, nincs ideiglenes mappa – csak tiszta C#. + +A útmutató végére egy kész, futtatható példát kapsz, amely egy `result.zip` fájlt hoz létre, benne minden hivatkozott erőforrással, valamint néhány gyakorlati tippet, amelyet saját projektjeidben alkalmazhatsz. + +## Előfeltételek + +- .NET 6+ (a kód .NET Framework 4.7.2‑n is működik, de a legújabb SDK‑t ajánljuk) +- Aspose.HTML for .NET NuGet csomag (`Aspose.HTML`) – telepítés: `dotnet add package Aspose.HTML` +- Alapvető ismeretek a stream‑ekről és a `System.IO.Compression` névtéről +- Kedvenc IDE‑d vagy szerkesztőd (Visual Studio, VS Code, Rider…) + +Ha már mindezek megvannak, nagyszerű – ugorjunk egyenesen a kódra. Ha nem, az egyetlen extra lépés egy egy‑soros NuGet‑telepítés; minden más önmagában tartalmazott. + +## 1. lépés: Egyszerű HTML dokumentum létrehozása memóriában + +Először szükségünk van egy `HTMLDocument` objektumra, amely a zip‑elni kívánt oldalt képviseli. Valós környezetben ezt betöltheted egy URL‑ről vagy fájlból, de a tisztaság kedvéért itt egy apró dokumentumot építünk beágyazottan. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Miért fontos:** +> A dokumentum memóriában tartásával elkerüljük a köztes fájl‑I/O‑t, ami a későbbi **HTML‑t ZIP‑ra konvertálás** lépést gyorsabbá és szálbiztonságossá teszi. + +## 2. lépés: In‑memory ZIP stream előkészítése + +Ahelyett, hogy egy ideiglenes `.zip` fájlt írnánk a lemezre, egy `MemoryStream`‑et használunk. Így minden RAM‑ban marad, ami ideális webszolgáltatások vagy háttérfeladatok számára, amelyeknek közvetlenül a kliensnek kell visszaadniuk az archívumot. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tipp:** A `using` utasítás automatikusan felszabadítja a stream‑et, megakadályozva a memória‑szivárgásokat. + +## 3. lépés: Egyedi ResourceHandler megvalósítása + +Az Aspose.HTML minden külső erőforrásra (CSS‑fájlok, képek, betűtípusok stb.) meghív egy `ResourceHandler`‑t. A `ResourceHandler` alosztályozásával pontosan meghatározhatjuk, hová kerül minden erőforrás – ebben az esetben egy ZIP‑archívum bejegyzésébe. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Miért egyedi kezelő? + +- **Névadás feletti kontroll** – te döntöd el, hogyan jelenjen meg minden fájl az archívumban. +- **Nincs ideiglenes fájl** – a kezelő közvetlenül az in‑memory ZIP‑be ír. +- **Újrahasználhatóság** – ezt az osztályt belevetheted bármely projektbe, amelynek **HTML‑t ZIP‑ként kell menteni**. + +## 4. lépés: HTML dokumentum mentése a kezelővel + +Most összekapcsoljuk a részeket. A `Save` metódus minden hivatkozott erőforráshoz meghívja a `HandleResource`‑t, a kezelő pedig a byte‑okat a korábban létrehozott ZIP‑archívumba stream‑eli. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Mi történik a háttérben?** +> Az Aspose beolvassa a HTML‑t, felfedezi a `` hivatkozást, kéri a kezelőtől a stream‑et, és a kezelő egy `logo.png` bejegyzést hoz létre a ZIP‑ben. Ugyanez a folyamat ismétlődik a CSS‑hez, betűtípusokhoz vagy bármely más külső erőforráshoz. + +## 5. lépés: ZIP archívum mentése lemezre (vagy visszaadása) + +Végül az in‑memory archívumot egy fájlba írjuk. Web‑API‑ban helyette visszaadhatod a `zipMemoryStream.ToArray()`‑t byte‑tömbként. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Várt eredmény + +Nyisd meg a `result.zip` fájlt, és a következőket kell látnod: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Ha a fájlkezelőben nézed az archívumot, észre fogod venni, hogy a HTML fájl `resource.bin` néven van tárolva, mert nem adtunk neki barátságos nevet. Ezt könnyen javíthatod úgy, hogy ellenőrzöd a `resourceInfo.ContentType`‑t, és szükség esetén `.html`‑t rendelsz hozzá. + +## Teljes működő példa + +Az alábbi program teljes, másolás‑beillesztés‑kész kódot tartalmaz, amely a fentieket egyesíti. Futtasd egy konzol‑alkalmazásból, és kapsz egy kész, megosztható ZIP‑fájlt. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**A kód futtatása** `result.zip`‑et hoz létre a program munkakönyvtárában. Nyisd meg, és megtalálod az `index.html`‑t (az eredeti oldalunk) plusz a `logo.png`‑t, ha az a lemezen létezett vagy egy URL‑ről lett letöltve. + +## Gyakori variációk és szélhelyzetek + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/indonesian/net/generate-jpg-and-png-images/_index.md index 4e885ce32..dbadb38d1 100644 --- a/html/indonesian/net/generate-jpg-and-png-images/_index.md +++ b/html/indonesian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Pelajari cara menggunakan Aspose.HTML untuk .NET guna memanipulasi dokumen HTML, Pelajari cara mengaktifkan antialiasing untuk meningkatkan kualitas gambar PNG atau JPG saat mengonversi dokumen DOCX menggunakan Aspose.HTML. ### [Konversi DOCX ke PNG – Membuat Arsip ZIP dengan C# Tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Pelajari cara mengonversi file DOCX menjadi PNG dan mengemasnya ke dalam arsip ZIP menggunakan C# dengan Aspose.HTML. +### [Buat PNG dari HTML – Panduan Langkah‑per‑Langkah untuk Pengembang C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Pelajari cara mengonversi HTML menjadi gambar PNG dengan panduan langkah demi langkah untuk pengembang C# menggunakan Aspose.HTML. ## Kesimpulan diff --git a/html/indonesian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/indonesian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..a52f51c46 --- /dev/null +++ b/html/indonesian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Buat PNG dari HTML dengan cepat menggunakan Aspose.HTML. Pelajari cara + merender HTML ke PNG, mengatur ukuran kanvas, menambahkan warna latar belakang, + dan menyimpan gambar yang dirender dalam hitungan menit. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: id +og_description: Buat PNG dari HTML dengan Aspose.HTML. Panduan ini menunjukkan cara + merender HTML ke PNG, mengatur ukuran kanvas, menambahkan warna latar belakang, + dan menyimpan gambar yang dirender. +og_title: Buat PNG dari HTML – Tutorial Rendering C# Lengkap +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Buat PNG dari HTML – Panduan Langkah-demi-Langkah untuk Pengembang C# +url: /id/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat PNG dari HTML – Tutorial Rendering C# Lengkap + +Pernah membutuhkan untuk **create PNG from HTML** tetapi tidak yakin perpustakaan mana yang akan memberi Anda hasil yang tajam dan antialias? Anda tidak sendirian. Dalam banyak pipeline web‑to‑image, titik sakit terbesar adalah membuat teks dan grafik terlihat setajam di browser. + +Berita baiknya? Dengan Aspose.HTML Anda dapat **render HTML to PNG** dalam beberapa baris kode, mengontrol ukuran kanvas, menambahkan warna latar belakang solid, dan akhirnya **save rendered image** ke disk—semua tanpa menyentuh browser. Dalam tutorial ini kami akan membahas seluruh proses, menjelaskan mengapa setiap pengaturan penting, dan menunjukkan contoh yang siap‑jalan. + +## Apa yang Akan Anda Pelajari + +- Cara memuat HTML dari string, file, atau URL +- Cara mengonfigurasi **set canvas size** dan **add background color** untuk output yang dapat diprediksi +- Mengaktifkan antialiasing dan sub‑pixel text hinting untuk heading yang sangat tajam +- Langkah tepat untuk **save rendered image** sebagai file PNG +- Jebakan umum dan penyesuaian opsional untuk berbagai skenario + +Tidak diperlukan pengalaman sebelumnya dengan Aspose.HTML; hanya diperlukan setup C# dasar dan Visual Studio (atau IDE favorit Anda). + +--- + +## Langkah 1: Instal Aspose.HTML untuk .NET + +Sebelum menulis kode apa pun, pastikan paket NuGet Aspose.HTML sudah direferensikan dalam proyek Anda. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Gunakan versi stabil terbaru (per April 2026, 23.9.0) untuk mendapatkan mesin rendering terbaru dan perbaikan bug. + +--- + +## Langkah 2: Muat Sumber HTML – Create PNG from HTML + +Anda dapat memberi renderer sebuah string inline, file lokal, atau URL remote. Untuk demo ini kami akan menggunakan string inline sederhana yang berisi heading dengan font khusus. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Why this matters:** Memuat HTML ke dalam `HTMLDocument` memberi mesin kontrol penuh atas parsing DOM, cascade CSS, dan perhitungan layout. Ini juga mengisolasi rendering dari keadaan browser eksternal, memastikan hasil yang dapat direproduksi. + +--- + +## Langkah 3: Konfigurasikan Opsi Rendering – Set Canvas Size & Add Background Color + +Kelas `ImageRenderingOptions` memungkinkan Anda menyesuaikan output gambar secara detail. Di sini kami akan mengaktifkan antialiasing, mengatur latar belakang putih, dan secara eksplisit mendefinisikan kanvas **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Why you might change these values:** +- **Canvas size:** Jika Anda membutuhkan thumbnail, perkecil dimensi; untuk cetakan resolusi tinggi, tingkatkan ukuran. +- **Background color:** PNG transparan memungkinkan, tetapi banyak alat hilir (mis., PowerPoint) mengharapkan latar belakang opak. + +--- + +## Langkah 4: Render dan **Save Rendered Image** sebagai PNG + +Sekarang proses berat terjadi. `ImageRenderer` mengonsumsi `HTMLDocument` dan opsi yang baru saja kami definisikan, kemudian menulis aliran PNG ke disk. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Saat Anda menjalankan program, Anda akan menemukan `result.png` di desktop Anda. Buka file tersebut, dan Anda akan melihat heading bersih, antialias, terpusat pada kanvas putih. + +> **Expected output:** PNG 800 × 600 dengan latar belakang putih dan teks “Antialiased Heading” yang dirender dalam Arial, terlihat selancar di Chrome. + +--- + +## Langkah 5: Verifikasi Hasil – Pemeriksaan Cepat + +1. **File existence:** `File.Exists(outputPath)` harus mengembalikan `true`. +2. **Dimensions:** Buka PNG di penampil gambar apa pun; harus melaporkan 800 × 600 px. +3. **Visual quality:** Perbesar hingga 200 % – tepi teks harus tetap halus, tidak bergerigi. + +Jika ada yang terlihat tidak tepat, periksa kembali bahwa `UseAntialiasing` dan `UseHinting` keduanya disetel ke `true`. Kedua flag tersebut adalah rahasia utama untuk rendering berkualitas tinggi. + +--- + +## Variasi Umum & Kasus Tepi + +| Skenario | Apa yang Diubah | Mengapa | +|----------|----------------|-----| +| **Render halaman web remote** | Ganti `new HTMLDocument(htmlContent)` dengan `new HTMLDocument("https://example.com")` | Memungkinkan Anda menangkap situs live tanpa menyalin HTML secara manual. | +| **Latar belakang transparan** | Set `BackgroundColor = Color.Transparent` dan gunakan `ImageFormat.Png` | Berguna untuk menumpangkan PNG pada grafik lain. | +| **Format gambar berbeda** | Ubah `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG mungkin lebih kecil untuk konten fotografi, tetapi kehilangan kualitas lossless. | +| **Ukuran kanvas dinamis** | Gunakan `imgOptions.Width = htmlDoc.Body.ClientWidth;` setelah layout | Memungkinkan gambar menyesuaikan lebar alami konten HTML. | +| **Output High‑DPI** | Kalikan `Width` dan `Height` dengan faktor skala (mis., 2) | Menghasilkan aset siap retina untuk tampilan modern. | + +--- + +## Contoh Lengkap yang Berfungsi (Siap Salin‑Tempel) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Jalankan program (`dotnet run` atau tekan F5 di Visual Studio) dan Anda akan memiliki PNG yang dirender sempurna siap digunakan dalam email, laporan, atau tempat lain yang membutuhkan gambar statis dari HTML. + +--- + +## Pertanyaan yang Sering Diajukan + +**Q: Apakah ini bekerja dengan fitur CSS 3 seperti flexbox?** +A: Ya. Aspose.HTML mendukung sebagian besar CSS modern, termasuk flexbox, grid, dan media queries. Pastikan Anda menggunakan versi perpustakaan terbaru. + +**Q: Bagaimana jika HTML saya merujuk ke gambar eksternal?** +A: Renderer mengikuti URL relatif berdasarkan base URI dokumen. Jika Anda memuat HTML dari string, setel `doc.BaseUrl` ke folder yang berisi aset. + +**Q: Bisakah saya merender beberapa halaman menjadi satu PNG?** +A: Tidak secara langsung—setiap pemanggilan `ImageRenderer` menghasilkan satu gambar raster. Untuk output multi‑halaman, render tiap halaman secara terpisah dan gabungkan dengan perpustakaan grafis (mis., ImageSharp). + +--- + +## Kesimpulan + +Anda kini memiliki solusi menyeluruh, end‑to‑end untuk **create PNG from HTML** menggunakan Aspose.HTML. Dengan mengonfigurasi opsi **render html to png**—seperti **set canvas size**, **add background color**, dan mengaktifkan antialiasing—Anda dapat menghasilkan gambar kelas profesional tanpa browser. + +Dari titik ini Anda dapat bereksperimen dengan DPI lebih tinggi, latar belakang transparan, atau pemrosesan batch puluhan potongan HTML. Pola yang sama berlaku apakah Anda membangun layanan thumbnail, pipeline pembuatan PDF, atau alat pratinjau situs statis. + +Selamat merender, dan silakan tinggalkan komentar jika Anda mengalami kendala! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/indonesian/net/html-document-manipulation/_index.md index 6308bff33..052d4ea48 100644 --- a/html/indonesian/net/html-document-manipulation/_index.md +++ b/html/indonesian/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Pelajari cara menggunakan Aspose.HTML untuk .NET. Impor namespace, gabungkan HTM Manfaatkan potensi pengembangan web dengan Aspose.HTML untuk .NET. Buat, ubah, dan manipulasi dokumen HTML dengan mudah. ### [Buat HTML dari String di C# – Panduan Penangan Sumber Daya Kustom](./create-html-from-string-in-c-custom-resource-handler-guide/) Pelajari cara membuat dokumen HTML dari string menggunakan handler sumber daya kustom di C# dengan Aspose.HTML. +### [Terapkan Gaya Font Secara Programatis – Panduan Cepat C#](./apply-font-style-programmatically-quick-c-guide/) +Pelajari cara menerapkan gaya font secara programatis dalam C# dengan panduan singkat ini. ## Kesimpulan diff --git a/html/indonesian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/indonesian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..99c60cea2 --- /dev/null +++ b/html/indonesian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Terapkan gaya font secara programatis dan pelajari cara menghapus garis + bawah dari teks, mengubah gaya teks, serta mengatur teks tebal secara programatis + dalam tutorial singkat. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: id +og_description: Terapkan gaya font secara programatis dan temukan cara menghapus garis + bawah dari teks, mengubah gaya teks, serta mengatur teks tebal secara programatis + dalam tutorial singkat yang praktis. +og_title: Terapkan Gaya Font Secara Programatis – Panduan C# Cepat +tags: +- csharp +- ui +- text-formatting +- programming +title: Menerapkan Gaya Font Secara Programatis – Panduan Cepat C# +url: /id/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Menerapkan Gaya Font Secara Programatis – Panduan Cepat C# + +Pernahkah Anda perlu **apply font style** ke elemen UI tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian—banyak pengembang mengalami kendala itu saat pertama kali bermain dengan pemformatan teks dinamis. Kabar baik? Dalam beberapa menit saja Anda akan tahu persis cara mengubah tampilan label, menghapus underline dari teks, dan mengatur teks tebal secara programatis tanpa harus mencari melalui dokumentasi yang tak berujung. + +Dalam **text formatting tutorial** ini kami akan membahas contoh lengkap yang dapat dijalankan, menjelaskan “mengapa” di balik setiap baris, dan menambahkan tip praktis yang dapat Anda copy‑paste ke proyek WinForms atau WPF mana pun. Tanpa basa‑basi, hanya hal‑hal yang menyelesaikan pekerjaan. + +--- + +## Apa yang Akan Anda Pelajari + +- Cara **apply font style** menggunakan kelas pembantu kecil. +- Langkah tepat untuk **remove underline from text** sambil mempertahankan gaya lain tetap utuh. +- Cara **change text style** (bold, italic, underline) secara dinamis. +- Potongan kode lengkap yang siap disalin yang **sets bold text programmatically**. +- Jebakan umum dan penanganan edge‑case agar Anda tidak terkejut kemudian. + +**Prerequisites:** .NET 6+ (atau .NET Framework terbaru apa pun), pengetahuan dasar C#, dan IDE pilihan Anda (Visual Studio, Rider, atau VS Code). Itu saja—tidak diperlukan paket NuGet tambahan. + +--- + +## Langkah 1 – Apply Font Style ke Kontrol Anda + +Inti dari setiap operasi **apply font style** adalah enum `FontStyle` yang digabungkan dengan objek `Font`. Untuk menjaga kode tetap rapi, kami akan membungkus logika enum tersebut dalam kelas kecil `WebFontStyle`. Kelas ini mencerminkan properti yang Anda lihat di potongan kode asli (`Bold`, `Italic`, `Underline`) dan membangun nilai `FontStyle` yang dapat Anda berikan ke `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Why this matters:** +Dengan mengisolasi logika pembuatan flag, Anda menghindari penyebaran operasi bitwise `|` di seluruh kode UI Anda. Lebih mudah dibaca, lebih mudah diuji, dan—yang paling penting—menjadikan niat **apply font style** sangat jelas. + +--- + +## Langkah 2 – Remove Underline from Text (dan Pertahankan Gaya Lain Tetap Utuh) + +Misalkan Anda mewarisi label yang sudah bergaris bawah, tetapi desain mengharuskan teks tebal biasa. Anda tidak ingin kehilangan ketebalan saat menghapus garis bawah. Di sinilah kelas `WebFontStyle` bersinar. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Key point:** Menetapkan `Underline = false` secara eksplisit memberi tahu pembantu untuk *mengecualikan* flag underline. Jika Anda menghilangkan baris tersebut sepenuhnya, underline sebelumnya akan tetap ada, yang merupakan sumber bug umum ketika pengembang hanya men-toggle properti `Bold`. + +--- + +## Langkah 3 – Change Text Style: Bold, Italic, dan Lainnya + +Anda mungkin bertanya, “Bagaimana jika saya juga perlu men-toggle italic?” Objek yang sama bekerja untuk kombinasi apa pun. Di bawah ini adalah matriks cepat yang dapat Anda referensikan saat menulis kode. + +| Gaya yang Diinginkan | `Bold` | `Italic` | `Underline` | +|----------------------|--------|----------|-------------| +| **Hanya Bold** | true | false | false | +| *Hanya Italic* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +Cukup atur properti yang Anda butuhkan dan panggil `ToFont`. Pembantu melakukan pekerjaan berat untuk Anda, sehingga Anda dapat fokus pada logika UI. + +--- + +## Contoh Lengkap – Set Bold Text Programmatically + +Berikut adalah contoh **WinForms lengkap yang dapat dijalankan** yang menunjukkan semua yang telah kami bahas. Tempelkan ke dalam proyek WinForms gaya console baru dan tekan **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Hasil yang Diharapkan + +Saat Anda menjalankan program, sebuah jendela muncul dengan teks **“Hello, world!”** ditampilkan **bold**, **tidak italic**, dan **tanpa underline**. Konfirmasi visual ini memberi tahu Anda bahwa logika **apply font style** berhasil dengan sempurna. + +--- + +## Tips Pro & Edge Cases + +- **Dynamic updates:** Jika Anda perlu mengubah gaya setelah form ditampilkan (mis., sebagai respons terhadap checkbox), cukup buat ulang instance `WebFontStyle` atau modifikasi propertinya dan tetapkan kembali `lbl.Font`. UI akan diperbarui secara instan. +- **High‑DPI considerations:** Saat Anda mengganti objek `Font`, Windows secara otomatis menskalakan berdasarkan DPI saat ini. Tidak diperlukan kode tambahan kecuali Anda menangani skala secara manual. +- **WPF equivalent:** Di WPF Anda akan bind `FontWeight`, `FontStyle`, dan `TextDecorations` alih-alih menukar objek `Font`. Pemisahan logika yang sama tetap berlaku—jaga logika gaya di luar lapisan tampilan. +- **Avoiding memory leaks:** Menetapkan kembali `Label.Font` membuat objek `Font` baru. Buang (dispose) yang lama jika Anda sering menukar gaya: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Kesimpulan + +Anda sekarang tahu cara **apply font style** ke kontrol .NET apa pun, **remove underline from text**, dan **change text style** secara dinamis—semua sambil menjaga kode Anda bersih dan dapat digunakan kembali. Pembantu kecil `WebFontStyle` mengubah beberapa flag boolean menjadi komponen yang solid dan dapat diuji, dan contoh lengkap membuktikan Anda dapat **set bold text programmatically** dalam hanya beberapa baris. + +Apa selanjutnya? Cobalah menggabungkan pendekatan ini dengan pengaturan yang dipandu pengguna, atau bereksperimen dengan flag `FontStyle` lain seperti `Strikeout`. Anda bahkan dapat menampilkan panel UI kecil yang memungkinkan pengguna non‑teknis memilih bold, italic, atau underline saat runtime—tanpa perlu kompilasi ulang. + +Jika Anda menemukan **text formatting tutorial** ini berguna, silakan tinggalkan komentar atau bagikan variasi Anda sendiri. Selamat coding, dan semoga UI Anda selalu terlihat persis seperti yang Anda inginkan! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/indonesian/net/html-extensions-and-conversions/_index.md index 6ac5368ff..d5782f11e 100644 --- a/html/indonesian/net/html-extensions-and-conversions/_index.md +++ b/html/indonesian/net/html-extensions-and-conversions/_index.md @@ -56,7 +56,7 @@ Temukan kekuatan Aspose.HTML untuk .NET: Panduan langkah demi langkah untuk meng ### [Konversi HTML ke JPEG dalam .NET dengan Aspose.HTML](./convert-html-to-jpeg/) Pelajari cara mengonversi HTML ke JPEG dalam .NET dengan Aspose.HTML untuk .NET. Panduan langkah demi langkah untuk memanfaatkan kekuatan Aspose.HTML untuk .NET. Optimalkan tugas pengembangan web Anda dengan mudah. ### [Konversi HTML ke Markdown di .NET dengan Aspose.HTML](./convert-html-to-markdown/) -Pelajari cara mengonversi HTML ke Markdown dalam .NET menggunakan Aspose.HTML untuk manipulasi konten yang efisien. Dapatkan panduan langkah demi langkah untuk proses konversi yang lancar. +Pelajari cara mengonversi HTML ke Markdown dalam .NET menggunakan Aspose.HTML untuk .NET. Dapatkan panduan langkah demi langkah untuk proses konversi yang lancar. ### [Konversi HTML ke MHTML di .NET dengan Aspose.HTML](./convert-html-to-mhtml/) Konversi HTML ke MHTML dalam .NET dengan Aspose.HTML - Panduan langkah demi langkah untuk pengarsipan konten web yang efisien. Pelajari cara menggunakan Aspose.HTML untuk .NET guna membuat arsip MHTML. ### [Konversi HTML ke PNG dalam .NET dengan Aspose.HTML](./convert-html-to-png/) @@ -67,6 +67,8 @@ Pelajari cara mengonversi HTML ke TIFF dengan Aspose.HTML untuk .NET. Ikuti pand Temukan kekuatan Aspose.HTML untuk .NET: Ubah HTML menjadi XPS dengan mudah. Prasyarat, panduan langkah demi langkah, dan Tanya Jawab Umum disertakan. ### [Cara Mengompres HTML menjadi Zip di C# – Simpan HTML ke Zip](./how-to-zip-html-in-c-save-html-to-zip/) Pelajari cara mengompres file HTML menjadi arsip ZIP menggunakan C# dan Aspose.HTML. +### [Cara Mengompres HTML menjadi Zip di C# – Panduan Penangan Sumber Daya Kustom](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Pelajari cara mengompres HTML menjadi arsip ZIP menggunakan C# dengan penangan sumber daya kustom di Aspose.HTML. ### [Buat Dokumen HTML dengan Teks Bergaya dan Ekspor ke PDF – Panduan Lengkap](./create-html-document-with-styled-text-and-export-to-pdf-full/) Pelajari cara membuat dokumen HTML dengan teks berformat dan mengekspornya ke PDF menggunakan Aspose.HTML untuk .NET. ### [Simpan HTML sebagai ZIP – Tutorial Lengkap C#](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..b59cc0dee --- /dev/null +++ b/html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-04-23 +description: Pelajari cara mengompres HTML menjadi ZIP di C# menggunakan penangan + sumber daya khusus – panduan langkah demi langkah untuk menyimpan HTML sebagai ZIP, + mengonversi HTML ke ZIP, dan membuat ZIP dari HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: id +og_description: 'cara mengompres html menjadi zip di C# dijelaskan: gunakan penangan + sumber daya khusus untuk menyimpan html sebagai zip, konversi html ke zip, dan buat + zip dari html dalam hitungan menit.' +og_title: cara meng-zip html di C# – Panduan Penangan Sumber Daya Kustom +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: cara meng-zip html di C# – panduan custom resource handler +url: /id/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# cara meng‑zip html di C# – panduan custom resource handler + +Pernah bertanya‑tanya **cara meng‑zip html** langsung dari kode C# Anda tanpa harus menyalin file ke disk terlebih dahulu? Anda tidak sendirian. Banyak pengembang menemui kebuntuan ketika harus mengemas sebuah halaman HTML beserta CSS, gambar, dan font‑nya untuk distribusi offline, dan mereka berakhir menulis kode file‑system ad‑hoc yang dengan cepat menjadi mimpi buruk pemeliharaan. + +Dalam tutorial ini kami akan menyelesaikan masalah tersebut dengan menunjukkan pendekatan bersih dan dapat digunakan kembali yang **menyimpan HTML sebagai arsip ZIP** menggunakan `ResourceHandler` dari Aspose.HTML. Kami juga akan menyentuh cara **mengonversi HTML ke ZIP**, dan bahkan mendemonstrasikan pola yang dapat Anda gunakan kembali untuk **membuat ZIP dari HTML** di proyek .NET mana pun. Tanpa skrip eksternal, tanpa folder sementara—hanya C# murni. + +Pada akhir panduan Anda akan memiliki contoh siap‑jalankan yang menghasilkan `result.zip` berisi setiap sumber daya yang terhubung, plus sejumlah tip praktis yang dapat Anda terapkan pada proyek Anda sendiri. + +## Prasyarat + +- .NET 6+ (kode ini juga berfungsi pada .NET Framework 4.7.2, namun kami menyarankan SDK terbaru) +- Paket NuGet Aspose.HTML untuk .NET (`Aspose.HTML`) – instal via `dotnet add package Aspose.HTML` +- Familiaritas dasar dengan stream dan namespace `System.IO.Compression` +- IDE atau editor pilihan Anda (Visual Studio, VS Code, Rider…) + +Jika semua sudah siap, bagus—langsung saja ke kode. Jika belum, satu langkah ekstra saja yaitu instalasi NuGet satu baris; sisanya sudah lengkap. + +## Langkah 1: Buat Dokumen HTML Sederhana di Memori + +Pertama kita memerlukan objek `HTMLDocument` yang mewakili halaman yang ingin kita zip. Pada skenario dunia nyata Anda mungkin memuatnya dari URL atau file, tetapi demi kejelasan kami akan membangun dokumen kecil secara inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Mengapa ini penting:** +> Dengan menyimpan dokumen di memori kita menghindari I/O file menengah, yang membuat langkah **convert html to zip** selanjutnya menjadi cepat dan thread‑safe. + +## Langkah 2: Siapkan Stream ZIP di Memori + +Alih‑alih menulis file `.zip` sementara ke disk, kita akan menggunakan `MemoryStream`. Ini menyimpan semuanya di RAM, ideal untuk layanan web atau pekerjaan latar belakang yang perlu mengembalikan arsip langsung ke klien. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** Pernyataan `using` memastikan stream dibuang secara otomatis, mencegah kebocoran memori. + +## Langkah 3: Implementasikan Custom ResourceHandler + +Aspose.HTML memanggil sebuah `ResourceHandler` untuk setiap aset eksternal yang ditemukannya (file CSS, gambar, font, dll.). Dengan menurunkan (subclass) `ResourceHandler` kita dapat menentukan tepat di mana setiap sumber daya berakhir—dalam kasus kami, sebagai entri di dalam arsip ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Mengapa Handler Kustom? + +- **Kontrol atas penamaan** – Anda memutuskan bagaimana setiap file muncul di dalam arsip. +- **Tanpa file sementara** – handler menulis langsung ke ZIP di memori. +- **Dapat digunakan kembali** – Anda dapat menaruh kelas ini ke proyek mana pun yang perlu **save html as zip**. + +## Langkah 4: Simpan Dokumen HTML Menggunakan Handler + +Sekarang kita mengikat semuanya. Metode `Save` akan memanggil `HandleResource` untuk setiap aset yang terhubung, dan handler akan menyalurkan byte‑byte tersebut ke dalam arsip ZIP yang telah kita buat sebelumnya. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Apa yang terjadi di balik layar?** +> Aspose mem‑parse HTML, menemukan referensi ``, meminta stream ke handler, dan handler membuat entri `logo.png` di dalam ZIP. Alur yang sama berulang untuk CSS, font, atau sumber daya eksternal lainnya. + +## Langkah 5: Simpan Arsip ZIP ke Disk (atau Kembalikan) + +Akhirnya kita menuliskan arsip yang berada di memori ke sebuah file. Pada API web Anda bisa saja mengembalikan `zipMemoryStream.ToArray()` sebagai array byte. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Hasil yang Diharapkan + +Buka `result.zip` dan Anda akan melihat: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Jika Anda membuka arsip tersebut di penjelajah file, Anda akan memperhatikan bahwa file HTML disimpan sebagai `resource.bin` karena kami tidak memberi nama yang bersahabat. Anda dapat dengan mudah memperbaikinya dengan memeriksa `resourceInfo.ContentType` dan menetapkan ekstensi `.html` bila sesuai. + +## Contoh Lengkap yang Berfungsi + +Berikut adalah program lengkap, siap salin‑tempel, yang menggabungkan semua langkah di atas. Jalankan dari aplikasi konsol, dan Anda akan mendapatkan file ZIP siap dibagikan. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Menjalankan kode ini** akan menghasilkan `result.zip` di direktori kerja program. Buka dan Anda akan menemukan `index.html` (halaman asli kami) plus `logo.png` jika gambar tersebut ada di disk atau diambil dari URL. + +## Variasi Umum & Kasus Tepi + +| Scenario +{{< /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/generate-jpg-and-png-images/_index.md b/html/italian/net/generate-jpg-and-png-images/_index.md index f6e8b2d8a..b162d896f 100644 --- a/html/italian/net/generate-jpg-and-png-images/_index.md +++ b/html/italian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Impara a usare Aspose.HTML per .NET per manipolare documenti HTML, convertire HT Scopri come abilitare l'antialiasing durante la conversione di documenti DOCX in immagini PNG o JPG con Aspose.HTML per .NET. ### [Converti docx in PNG – crea archivio zip C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Impara a convertire documenti DOCX in PNG e a comprimerli in un archivio ZIP usando C# e Aspose.HTML. +### [Crea PNG da HTML – Guida passo‑passo per sviluppatori C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Impara a generare file PNG a partire da HTML con una guida dettagliata per sviluppatori C#. ## Conclusione diff --git a/html/italian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/italian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..b281a374c --- /dev/null +++ b/html/italian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Crea PNG da HTML rapidamente con Aspose.HTML. Scopri come rendere HTML + in PNG, impostare le dimensioni della tela, aggiungere il colore di sfondo e salvare + l'immagine renderizzata in pochi minuti. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: it +og_description: Crea PNG da HTML con Aspose.HTML. Questa guida mostra come rendere + HTML in PNG, impostare le dimensioni della tela, aggiungere il colore di sfondo + e salvare l'immagine renderizzata. +og_title: Crea PNG da HTML – Tutorial completo di rendering C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Crea PNG da HTML – Guida passo‑passo per sviluppatori C# +url: /it/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea PNG da HTML – Tutorial Completo di Rendering in C# + +Ti è mai capitato di **creare PNG da HTML** senza sapere quale libreria ti garantisse risultati nitidi e antialiasati? Non sei l’unico. In molte pipeline web‑to‑image il punto dolente più grande è ottenere testo e grafica così nitidi come nel browser. + +La buona notizia? Con Aspose.HTML puoi **renderizzare HTML in PNG** in poche righe, controllare le dimensioni della tela, aggiungere un colore di sfondo solido e infine **salvare l’immagine renderizzata** su disco — tutto senza aprire un browser. In questo tutorial percorreremo l’intero processo, spiegheremo perché ogni impostazione è importante e ti mostreremo un esempio pronto all’uso. + +## Cosa Imparerai + +- Come caricare HTML da una stringa, da un file o da un URL +- Come configurare **set canvas size** e **add background color** per un output prevedibile +- Abilitare antialiasing e hinting del testo sub‑pixel per intestazioni ultra‑nitide +- I passaggi esatti per **save rendered image** come file PNG +- Problemi comuni e ottimizzazioni opzionali per diversi scenari + +Non è necessaria alcuna esperienza pregressa con Aspose.HTML; basta una configurazione base di C# e Visual Studio (o il tuo IDE preferito). + +--- + +## Passo 1: Installa Aspose.HTML per .NET + +Prima di scrivere codice, assicurati che il pacchetto NuGet Aspose.HTML sia referenziato nel tuo progetto. + +```bash +dotnet add package Aspose.HTML +``` + +> **Consiglio:** Usa l’ultima versione stabile (a partire da aprile 2026, 23.9.0) per ottenere il motore di rendering più recente e le correzioni di bug. + +--- + +## Passo 2: Carica la Sorgente HTML – Crea PNG da HTML + +Puoi fornire al renderer una stringa inline, un file locale o un URL remoto. Per questa demo useremo una semplice stringa inline che contiene un’intestazione con un font personalizzato. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Perché è importante:** Caricare l’HTML in un `HTMLDocument` dà al motore il pieno controllo sul parsing del DOM, sulla cascata CSS e sui calcoli di layout. Isola inoltre il rendering da qualsiasi stato del browser esterno, garantendo risultati riproducibili. + +--- + +## Passo 3: Configura le Opzioni di Rendering – Imposta Dimensioni della Tela & Aggiungi Colore di Sfondo + +La classe `ImageRenderingOptions` ti permette di perfezionare l’immagine di output. Qui abiliteremo l’antialiasing, imposteremo uno sfondo bianco e definiremo esplicitamente una tela di **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Perché potresti modificare questi valori:** +- **Canvas size:** Se ti serve una miniatura, riduci le dimensioni; per stampe ad alta risoluzione, aumentale. +- **Background color:** I PNG trasparenti sono possibili, ma molti strumenti a valle (es. PowerPoint) si aspettano uno sfondo opaco. + +--- + +## Passo 4: Renderizza e **Save Rendered Image** come PNG + +Ora avviene il lavoro pesante. L’`ImageRenderer` consuma l’`HTMLDocument` e le opzioni appena definite, quindi scrive uno stream PNG su disco. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Quando esegui il programma, troverai `result.png` sul desktop. Aprilo e dovresti vedere un’intestazione pulita, antialiasata, centrata su una tela bianca. + +> **Output previsto:** Un PNG 800 × 600 con sfondo bianco e il testo “Antialiased Heading” renderizzato in Arial, con la stessa fluidità di Chrome. + +--- + +## Passo 5: Verifica il Risultato – Controlli Rapidi + +1. **Esistenza del file:** `File.Exists(outputPath)` dovrebbe restituire `true`. +2. **Dimensioni:** Apri il PNG in qualsiasi visualizzatore; dovrebbe indicare 800 × 600 px. +3. **Qualità visiva:** Zoom al 200 % – i bordi del testo devono rimanere lisci, non frastagliati. + +Se qualcosa non sembra corretto, ricontrolla che `UseAntialiasing` e `UseHinting` siano entrambi impostati a `true`. Quei due flag sono il “segreto” per un rendering di alta qualità. + +--- + +## Variazioni Comuni & Casi Limite + +| Scenario | Cosa Regolare | Perché | +|----------|----------------|-----| +| **Renderizzare una pagina remota** | Sostituisci `new HTMLDocument(htmlContent)` con `new HTMLDocument("https://example.com")` | Consente di catturare siti live senza copiare manualmente l’HTML. | +| **Sfondo trasparente** | Imposta `BackgroundColor = Color.Transparent` e usa `ImageFormat.Png` | Utile per sovrapporre il PNG ad altre grafiche. | +| **Formato immagine diverso** | Cambia `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG può essere più piccolo per contenuti fotografici, ma perde la qualità lossless. | +| **Dimensioni della tela dinamiche** | Usa `imgOptions.Width = htmlDoc.Body.ClientWidth;` dopo il layout | Fa sì che l’immagine corrisponda alla larghezza naturale del contenuto HTML. | +| **Output ad alta DPI** | Moltiplica `Width` e `Height` per un fattore di scala (es. 2) | Genera asset pronti per retina per display moderni. | + +--- + +## Esempio Completo (Pronto per Copia‑Incolla) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Esegui il programma (`dotnet run` o premi F5 in Visual Studio) e avrai un PNG perfettamente renderizzato pronto per email, report o qualsiasi altro contesto in cui ti serva un’immagine statica di HTML. + +--- + +## Domande Frequenti + +**D: Funziona con le funzionalità CSS 3 come flexbox?** +R: Sì. Aspose.HTML supporta la maggior parte dei CSS moderni, inclusi flexbox, grid e media queries. Basta assicurarsi di utilizzare l’ultima versione della libreria. + +**D: E se il mio HTML fa riferimento a immagini esterne?** +R: Il renderer segue gli URL relativi basandosi sul `BaseUrl` del documento. Se carichi l’HTML da una stringa, imposta `doc.BaseUrl` sulla cartella contenente le risorse. + +**D: Posso renderizzare più pagine in un unico PNG?** +R: Non direttamente — ogni chiamata a `ImageRenderer` produce una singola immagine raster. Per output multi‑pagina, renderizza ogni pagina separatamente e uniscile con una libreria grafica (es. ImageSharp). + +--- + +## Conclusione + +Ora disponi di una soluzione solida, end‑to‑end, per **create PNG from HTML** usando Aspose.HTML. Configurando le opzioni **render html to png** — come **set canvas size**, **add background color** e abilitando l’antialiasing — puoi generare immagini di qualità professionale senza un browser. + +Da qui potrai sperimentare DPI più alti, sfondi trasparenti o elaborazioni batch di decine di snippet HTML. Lo stesso schema vale per la creazione di servizi di thumbnail, pipeline di generazione PDF o strumenti di preview per siti statici. + +Buon rendering, e sentiti libero di lasciare un commento se incontri difficoltà! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/italian/net/html-document-manipulation/_index.md index 830312f0e..b54a807b9 100644 --- a/html/italian/net/html-document-manipulation/_index.md +++ b/html/italian/net/html-document-manipulation/_index.md @@ -51,7 +51,7 @@ Aspose.HTML per .NET si distingue per la sua semplicità e potenza. Ti consente ## Tutorial sulla manipolazione dei documenti HTML ### [Caricare documenti HTML in modo asincrono in .NET con Aspose.HTML](./load-html-doc-asynchronously/) Scopri come usare Aspose.HTML per .NET per lavorare con documenti HTML. Guida passo passo con esempi e FAQ per sviluppatori. -### [Caricare documenti HTML con credenziali in .NET con Aspose.HTML](./load-html-doc-with-credentials/) +### [Caricare documenti HTML con credenziali in .NET con Aspose.HTML](./load-html-with-credentials/) Scopri come potenziare la tua SEO con Aspose.HTML per .NET. Aumenta le classifiche, analizza i contenuti web e ottimizzali per i motori di ricerca. ### [Carica HTML utilizzando un server remoto in .NET con Aspose.HTML](./load-html-using-remote-server/) Sblocca il potenziale di Aspose.HTML per .NET con la nostra guida completa. Scopri come importare namespace, accedere a documenti HTML remoti e altro ancora. @@ -71,6 +71,8 @@ Impara a usare Aspose.HTML per .NET. Importa namespace, unisci HTML con XML e mi Sfrutta il potenziale dello sviluppo web con Aspose.HTML per .NET. Crea, converti e manipola documenti HTML con facilità. ### [Creare HTML da stringa in C# – Guida al gestore di risorse personalizzato](./create-html-from-string-in-c-custom-resource-handler-guide/) Impara a generare documenti HTML da stringhe C# usando un gestore di risorse personalizzato con Aspose.HTML. +### [Applicare lo stile del carattere programmaticamente – Guida rapida C#](./apply-font-style-programmatically-quick-c-guide/) +Scopri come applicare stili di font a documenti HTML in C# con Aspose.HTML in pochi passaggi. ## Conclusione diff --git a/html/italian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/italian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..7584243d8 --- /dev/null +++ b/html/italian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Applica lo stile del carattere programmaticamente e scopri come rimuovere + la sottolineatura dal testo, modificare lo stile del testo e impostare il testo + in grassetto programmaticamente in un tutorial conciso. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: it +og_description: Applica lo stile del carattere programmaticamente e scopri come rimuovere + la sottolineatura dal testo, cambiare lo stile del testo e impostare il testo in + grassetto programmaticamente in un breve tutorial pratico. +og_title: Applica lo stile del font programmaticamente – Guida rapida C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Applicare lo stile del carattere programmaticamente – Guida rapida C# +url: /it/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Applica lo stile del font programmaticamente – Guida rapida C# + +Ti è mai capitato di dover **applicare lo stile del font** a un elemento UI ma non sapevi da dove cominciare? Non sei l'unico—la maggior parte degli sviluppatori incappa in questo ostacolo quando si avvicina per la prima volta alla formattazione dinamica del testo. La buona notizia? In pochi minuti saprai esattamente come modificare l'aspetto di un'etichetta, rimuovere la sottolineatura dal testo e impostare il testo in grassetto programmaticamente senza dover cercare tra infinite documentazioni. + +In questo **tutorial di formattazione del testo** ti guideremo attraverso un esempio completo e eseguibile, spiegheremo il “perché” dietro ogni riga e inseriremo consigli pratici che potrai copiare‑incollare in qualsiasi progetto WinForms o WPF. Niente fronzoli, solo ciò che serve a portare a termine il lavoro. + +--- + +## Cosa Imparerai + +- Come **applicare lo stile del font** usando una piccola classe helper. +- I passaggi precisi per **rimuovere la sottolineatura dal testo** mantenendo intatti gli altri stili. +- Modi per **cambiare lo stile del testo** (grassetto, corsivo, sottolineato) al volo. +- Uno snippet completo, pronto per il copia‑incolla, che **imposta il testo in grassetto programmaticamente**. +- Trappole comuni e gestione dei casi limite così non sarai sorpreso in seguito. + +**Prerequisiti:** .NET 6+ (o qualsiasi versione recente del .NET Framework), conoscenza base di C# e un IDE a tua scelta (Visual Studio, Rider o VS Code). Tutto qui—non sono necessari pacchetti NuGet aggiuntivi. + +--- + +## Passo 1 – Applica lo Stile del Font al Tuo Controllo + +Il nucleo di qualsiasi operazione di **applicare lo stile del font** è un enum `FontStyle` combinato con un oggetto `Font`. Per mantenere il codice ordinato avvolgeremo la logica dell'enum all'interno di una piccola classe `WebFontStyle`. Questa classe rispecchia le proprietà viste nello snippet originale (`Bold`, `Italic`, `Underline`) e costruisce un valore `FontStyle` che puoi passare a `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Perché è importante:** +Isolando la logica di costruzione dei flag, eviti di spargere operazioni bitwise `|` in tutto il codice UI. È più leggibile, più facile da testare e—soprattutto—rende l'intento di **applicare lo stile del font** cristallino. + +--- + +## Passo 2 – Rimuovi la Sottolineatura dal Testo (e Mantieni Intatti gli Altri Stili) + +Supponi di aver ereditato un'etichetta già sottolineata, ma il design richiede un semplice testo in grassetto. Non vuoi perdere il grassetto mentre rimuovi la sottolineatura. È qui che la classe `WebFontStyle` brilla. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Punto chiave:** Impostare `Underline = false` indica esplicitamente all'helper di *escludere* il flag della sottolineatura. Se ometti la riga del tutto, la sottolineatura precedente persisterà, il che è una fonte comune di bug quando gli sviluppatori attivano solo la proprietà `Bold`. + +--- + +## Passo 3 – Cambia lo Stile del Testo: Grassetto, Corsivo e Altro + +Potresti chiederti, “E se avessi bisogno di attivare anche il corsivo?” Lo stesso oggetto funziona per qualsiasi combinazione. Di seguito trovi una rapida matrice di riferimento durante la codifica. + +| Stile desiderato | `Bold` | `Italic` | `Underline` | +|------------------|--------|----------|-------------| +| **Solo grassetto** | true | false | false | +| *Solo corsivo* | false | true | false | +| **Grassetto + Corsivo** | true | true | false | +| **Grassetto + Sottolineato** | true | false | true | + +Imposta semplicemente le proprietà di cui hai bisogno e chiama `ToFont`. L'helper fa il lavoro pesante per te, così puoi concentrarti sulla logica UI. + +--- + +## Esempio Completo – Imposta il Testo in Grassetto Programmaticamente + +Di seguito trovi un esempio **completo e eseguibile WinForms** che dimostra tutto ciò che abbiamo trattato. Incollalo in un nuovo progetto WinForms in stile console e premi **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Risultato Atteso + +Quando esegui il programma, appare una finestra con il testo **“Hello, world!”** visualizzato **in grassetto**, **non in corsivo**, e **senza alcuna sottolineatura**. Questa conferma visiva ti indica che la logica di **applicare lo stile del font** ha funzionato perfettamente. + +--- + +## Consigli Pro & Casi Limite + +- **Aggiornamenti dinamici:** Se devi cambiare lo stile dopo che il form è stato mostrato (ad esempio in risposta a una checkbox), ricrea l'istanza `WebFontStyle` o modifica le sue proprietà e riassegna `lbl.Font`. L'interfaccia si aggiorna istantaneamente. +- **Considerazioni High‑DPI:** Quando sostituisci un oggetto `Font`, Windows lo scala automaticamente in base al DPI corrente. Nessun codice aggiuntivo necessario a meno che tu non gestisca manualmente lo scaling. +- **Equivalente WPF:** In WPF collegheresti `FontWeight`, `FontStyle` e `TextDecorations` invece di scambiare un oggetto `Font`. La stessa separazione logica si applica—mantieni la logica di stile fuori dal layer di visualizzazione. +- **Evitare perdite di memoria:** Riassegnare `Label.Font` crea un nuovo oggetto `Font`. Disporre quello vecchio se scambi gli stili frequentemente: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Conclusione + +Ora sai come **applicare lo stile del font** a qualsiasi controllo .NET, **rimuovere la sottolineatura dal testo** e **cambiare lo stile del testo** al volo—tutto mantenendo il tuo codice pulito e riutilizzabile. Il piccolo helper `WebFontStyle` trasforma una manciata di flag booleani in un componente solido e testabile, e l'esempio completo dimostra che puoi **impostare il testo in grassetto programmaticamente** in poche righe. + +Cosa fare dopo? Prova a combinare questo approccio con impostazioni guidate dall'utente, o sperimenta altri flag `FontStyle` come `Strikeout`. Potresti anche esporre un piccolo pannello UI che permette agli utenti non tecnici di scegliere grassetto, corsivo o sottolineatura a runtime—senza necessità di ricompilare. + +Se hai trovato utile questo **tutorial di formattazione del testo**, sentiti libero di lasciare un commento o condividere le tue varianti. Buona programmazione, e che la tua UI abbia sempre l'aspetto esattamente come lo desideri! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/italian/net/html-extensions-and-conversions/_index.md index fcf4daa30..00a2eae18 100644 --- a/html/italian/net/html-extensions-and-conversions/_index.md +++ b/html/italian/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Crea un PDF da HTML in C# con Aspose.HTML per .NET. Segui la nostra guida passo Salva HTML come archivio ZIP con Aspose.HTML per .NET. Guida passo passo per creare file ZIP contenenti HTML in C#. ### [Salva HTML in ZIP in C# – Esempio completo in memoria](./save-html-to-zip-in-c-complete-in-memory-example/) Scopri come salvare un documento HTML in un archivio ZIP interamente in memoria usando Aspose.HTML per .NET. +### [Come comprimere HTML in C# – guida al gestore di risorse personalizzato](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Scopri come comprimere HTML in un archivio ZIP usando un gestore di risorse personalizzato con Aspose.HTML per .NET in C#. ## Conclusione diff --git a/html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..a515fb085 --- /dev/null +++ b/html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-04-23 +description: Impara a comprimere HTML in C# usando un gestore di risorse personalizzato + – guida passo passo per salvare HTML come zip, convertire HTML in zip e creare zip + da HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: it +og_description: 'come comprimere html in C# spiegato: usa un gestore di risorse personalizzato + per salvare html come zip, converti html in zip e crea zip da html in pochi minuti.' +og_title: come comprimere HTML in C# – Guida al gestore di risorse personalizzato +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: come comprimere html in C# – guida al gestore di risorse personalizzato +url: /it/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# come comprimere html in C# – guida al gestore di risorse personalizzato + +Ti sei mai chiesto **come comprimere html** direttamente dal tuo codice C# senza prima scrivere i file su disco? Non sei l'unico. Molti sviluppatori si trovano in difficoltà quando devono impacchettare una pagina HTML insieme a CSS, immagini e font per la distribuzione offline, e finiscono per scrivere codice ad‑hoc per il file‑system che rapidamente diventa un incubo di manutenzione. + +In questo tutorial risolveremo il problema mostrandoti un approccio pulito e riutilizzabile che **salva HTML come archivio ZIP** usando il `ResourceHandler` di Aspose.HTML. Tratteremo anche come **convertire HTML in ZIP**, e dimostreremo un pattern che puoi riutilizzare per **creare ZIP da HTML** in qualsiasi progetto .NET. Nessuno script esterno, nessuna cartella temporanea—solo puro C#. + +Al termine della guida avrai un esempio pronto all'uso che produce un `result.zip` contenente tutte le risorse collegate, più una serie di consigli pratici da applicare ai tuoi progetti. + +## Prerequisiti + +- .NET 6+ (il codice funziona anche su .NET Framework 4.7.2, ma consigliamo l'ultima SDK) +- Pacchetto NuGet Aspose.HTML for .NET (`Aspose.HTML`) – installalo con `dotnet add package Aspose.HTML` +- Familiarità di base con gli stream e lo spazio dei nomi `System.IO.Compression` +- Un IDE o editor a tua scelta (Visual Studio, VS Code, Rider…) + +Se hai già tutto pronto, ottimo—passiamo subito al codice. Altrimenti, l'unico passo aggiuntivo è un'installazione NuGet su una riga; tutto il resto è autonomo. + +## Passo 1: Creare un Documento HTML Semplice in Memoria + +Per prima cosa ci serve un oggetto `HTMLDocument` che rappresenti la pagina che vogliamo comprimere. In uno scenario reale potresti caricarlo da un URL o da un file, ma per chiarezza costruiremo un piccolo documento inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Perché è importante:** +> Tenendo il documento in memoria evitiamo qualsiasi I/O intermedio su file, il che rende il successivo passo **convert html to zip** veloce e thread‑safe. + +## Passo 2: Preparare uno Stream ZIP in Memoria + +Invece di scrivere un file `.zip` temporaneo su disco, useremo un `MemoryStream`. Questo mantiene tutto in RAM, ideale per servizi web o job in background che devono restituire l'archivio direttamente al client. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Suggerimento:** L'istruzione `using` garantisce che lo stream venga smaltito automaticamente, prevenendo perdite di memoria. + +## Passo 3: Implementare un ResourceHandler Personalizzato + +Aspose.HTML chiama un `ResourceHandler` per ogni risorsa esterna che scopre (file CSS, immagini, font, ecc.). Sottoclassando `ResourceHandler` possiamo decidere esattamente dove finisce ogni risorsa—in questo caso, come voce all'interno dell'archivio ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Perché un Handler Personalizzato? + +- **Controllo sul naming** – decidi come ogni file appare nell'archivio. +- **Nessun file temporaneo** – l'handler scrive direttamente nello ZIP in‑memoria. +- **Riutilizzabilità** – puoi inserire questa classe in qualsiasi progetto che deve **save html as zip**. + +## Passo 4: Salvare il Documento HTML Usando l'Handler + +Ora uniamo tutto. Il metodo `Save` invocherà `HandleResource` per ogni asset collegato, e l'handler trasmetterà quei byte nello ZIP che abbiamo creato prima. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Cosa succede dietro le quinte?** +> Aspose analizza l'HTML, scopre il riferimento ``, chiede allo handler uno stream, e l'handler crea una voce `logo.png` dentro lo ZIP. Lo stesso flusso si ripete per CSS, font o qualsiasi altra risorsa esterna. + +## Passo 5: Persistire l'Archivio ZIP su Disco (o Restituirlo) + +Infine scriviamo l'archivio in‑memoria su un file. In una Web API potresti invece restituire `zipMemoryStream.ToArray()` come array di byte. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Risultato Atteso + +Apri `result.zip` e dovresti vedere: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Se apri l'archivio in un file explorer noterai che il file HTML è salvato come `resource.bin` perché non gli abbiamo assegnato un nome amichevole. Puoi migliorare facilmente controllando `resourceInfo.ContentType` e assegnando l'estensione `.html` quando opportuno. + +## Esempio Completo Funzionante + +Di seguito trovi il programma completo, pronto per il copia‑incolla, che incorpora tutti i passaggi descritti. Eseguilo da una console app e otterrai un file ZIP pronto da condividere. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Eseguendo questo codice** verrà generato `result.zip` nella directory di lavoro del programma. Aprilo e troverai `index.html` (la nostra pagina originale) più `logo.png` se quell'immagine esisteva su disco o è stata recuperata da un URL. + +## Variazioni Comuni & Casi Limite + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/japanese/net/generate-jpg-and-png-images/_index.md index 57de57175..2b865dbcb 100644 --- a/html/japanese/net/generate-jpg-and-png-images/_index.md +++ b/html/japanese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET を使用して HTML ドキュメントを操作したり DOCX 文書を PNG または JPG 画像に変換する際に、アンチエイリアシングを有効にして高品質な出力を得る手順を解説します。 ### [DOCX を PNG に変換 – ZIP アーカイブを作成する C# チュートリアル](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# で DOCX を PNG に変換し、ZIP アーカイブを作成する方法を学びます。 +### [C# 開発者向けステップバイステップ ガイド:HTML から PNG を作成する](./create-png-from-html-step-by-step-guide-for-c-developers/) +C# で HTML を PNG 画像に変換する手順を詳しく解説します。 ## 結論 diff --git a/html/japanese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/japanese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..a71d0feed --- /dev/null +++ b/html/japanese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-04-23 +description: Aspose.HTML を使用して HTML から PNG をすばやく作成します。HTML を PNG にレンダリングする方法、キャンバスサイズの設定、背景色の追加、そして数分でレンダリングされた画像を保存する方法を学びましょう。 +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: ja +og_description: Aspose.HTML を使用して HTML から PNG を作成します。このガイドでは、HTML を PNG にレンダリングする方法、キャンバスサイズの設定、背景色の追加、そしてレンダリングされた画像の保存方法を示します。 +og_title: HTMLからPNGを作成 – 完全なC#レンダリングチュートリアル +tags: +- C# +- Aspose.HTML +- Image Rendering +title: HTMLからPNGを作成する – C#開発者向けステップバイステップガイド +url: /ja/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTMLからPNGを作成 – 完全なC#レンダリングチュートリアル + +HTMLからPNGを作成する必要があったが、どのライブラリが鮮明でアンチエイリアスされた結果を提供するか分からなかったことはありませんか? あなたは一人ではありません。多くのWebから画像へのパイプラインで最大の課題は、テキストやグラフィックをブラウザ上と同じようにシャープに見せることです。 + +良いニュースです。Aspose.HTMLを使用すれば、数行のコードで**HTMLをPNGにレンダリング**し、キャンバスサイズを制御し、単色の背景色を追加し、最後に**レンダリングされた画像を**ディスクに保存できます—ブラウザに触れることなく。この記事では、全工程を順に解説し、各設定がなぜ重要かを説明し、すぐに実行できるサンプルを示します。 + +## 学べること + +- 文字列、ファイル、またはURLからHTMLをロードする方法 +- 予測可能な出力のために**set canvas size**と**add background color**を設定する方法 +- 鋭い見出しのためにアンチエイリアスとサブピクセルテキストヒンティングを有効にすること +- **save rendered image**をPNGファイルとして保存する正確な手順 +- 一般的な落とし穴とシナリオ別のオプション調整 + +Aspose.HTMLの事前経験は不要です。基本的なC#環境とVisual Studio(またはお好みのIDE)があれば始められます。 + +--- + +## 手順 1: Aspose.HTML for .NET をインストール + +コードを書く前に、プロジェクトでAspose.HTML NuGetパッケージが参照されていることを確認してください。 + +```bash +dotnet add package Aspose.HTML +``` + +> **プロのコツ:** 最新の安定版(2026年4月時点、23.9.0)を使用すると、最新のレンダリングエンジンとバグ修正が得られます。 + +--- + +## 手順 2: HTMLソースをロード – HTMLからPNGを作成 + +レンダラにインライン文字列、ローカルファイル、またはリモートURLのいずれかを渡すことができます。このデモでは、カスタムフォントの見出しを含むシンプルなインライン文字列を使用します。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**なぜ重要か:** HTMLを`HTMLDocument`にロードすると、エンジンはDOM解析、CSSカスケード、レイアウト計算を完全に制御できます。また、外部ブラウザの状態からレンダリングを分離するため、再現性のある結果が得られます。 + +--- + +## 手順 3: レンダリングオプションを設定 – キャンバスサイズの設定と背景色の追加 + +`ImageRenderingOptions`クラスを使用すると、出力画像を細かく調整できます。ここではアンチエイリアスを有効にし、白い背景を設定し、**800 × 600 px**のキャンバスを明示的に定義します。 + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**これらの値を変更する理由:** +- **Canvas size:** サムネイルが必要な場合はサイズを縮小し、高解像度印刷の場合は拡大します。 +- **Background color:** 透明なPNGも可能ですが、多くの下流ツール(例: PowerPoint)は不透明な背景を期待します。 + +--- + +## 手順 4: レンダリングして**レンダリングされた画像を**PNGとして保存 + +ここで本格的な処理が行われます。`ImageRenderer`は先ほど定義した`HTMLDocument`とオプションを使用し、PNGストリームをディスクに書き込みます。 + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +プログラムを実行すると、デスクトップに`result.png`が作成されます。開くと、白いキャンバスの中央にクリーンでアンチエイリアスされた見出しが表示されます。 + +> **期待される出力:** 白い背景にArialでレンダリングされた「Antialiased Heading」テキストが表示された、800 × 600のPNGです。Chromeでの表示と同様に滑らかです。 + +--- + +## 手順 5: 結果を検証 – クイックチェック + +1. **ファイルの存在:** `File.Exists(outputPath)` は `true` を返すはずです。 +2. **寸法:** 任意の画像ビューアでPNGを開くと、800 × 600 px と表示されます。 +3. **視覚品質:** 200 % にズームインすると、テキストのエッジが滑らかで、ギザギザしないことを確認してください。 + +何かが期待と異なる場合は、`UseAntialiasing` と `UseHinting` が両方とも `true` に設定されているか再確認してください。この2つのフラグが高品質レンダリングの秘訣です。 + +--- + +## 一般的なバリエーションとエッジケース + +| シナリオ | 調整内容 | 理由 | +|----------|----------------|-----| +| **リモートウェブページをレンダリング** | Replace `new HTMLDocument(htmlContent)` with `new HTMLDocument("https://example.com")` | HTMLを手動でコピーせずに、ライブサイトを取得できます。 | +| **透明な背景** | Set `BackgroundColor = Color.Transparent` and use `ImageFormat.Png` | 他のグラフィックにPNGをオーバーレイする際に便利です。 | +| **別の画像形式** | Change `renderer.Save(pngStream, ImageFormat.Jpeg)` | 写真コンテンツではJPEGの方がサイズが小さくなることがありますが、ロスレス品質は失われます。 | +| **動的キャンバスサイズ** | Use `imgOptions.Width = htmlDoc.Body.ClientWidth;` after layout | 画像がHTMLコンテンツの自然な幅に合わせられます。 | +| **高DPI出力** | Multiply `Width` and `Height` by a scale factor (e.g., 2) | 最新ディスプレイ向けのRetina対応アセットを生成します。 | + +--- + +## 完全動作サンプル(コピー&ペースト可能) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +プログラムを実行してください(`dotnet run` または Visual Studio で F5)。すると、メールやレポート、HTMLの静的画像が必要なあらゆる場所で使用できる完璧にレンダリングされたPNGが得られます。 + +--- + +## よくある質問 + +**Q: CSS 3 の flexbox などの機能はサポートされていますか?** +A: はい。Aspose.HTMLはflexbox、grid、メディアクエリなど、ほとんどの最新CSSをサポートしています。最新のライブラリバージョンを使用してください。 + +**Q: HTMLが外部画像を参照している場合はどうなりますか?** +A: レンダラはドキュメントのベースURIに基づく相対URLをたどります。文字列からHTMLをロードする場合は、`doc.BaseUrl` をアセットがあるフォルダーに設定してください。 + +**Q: 複数ページを1つのPNGにレンダリングできますか?** +A: 直接はできません—各 `ImageRenderer` 呼び出しは単一のラスタ画像を生成します。マルチページ出力の場合は、各ページを個別にレンダリングし、Graphicsライブラリ(例: ImageSharp)で結合してください。 + +--- + +## 結論 + +これで、Aspose.HTMLを使用して**HTMLからPNGを作成**するための堅実なエンドツーエンドソリューションが手に入りました。**render html to png**オプション(**set canvas size**、**add background color**、アンチエイリアスの有効化など)を設定することで、ブラウザなしでプロフェッショナル品質の画像を生成できます。 + +ここからは、より高いDPIや透明背景、数十のHTMLスニペットをバッチ処理するなどを試してみても良いでしょう。同じパターンは、サムネイルサービス、PDF生成パイプライン、静的サイトプレビュー工具を構築する際にも適用できます。 + +レンダリングを楽しんで、問題があれば遠慮なくコメントしてください! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/japanese/net/html-document-manipulation/_index.md b/html/japanese/net/html-document-manipulation/_index.md index 38a8521fa..e1e8d1cf7 100644 --- a/html/japanese/net/html-document-manipulation/_index.md +++ b/html/japanese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML for .NET の使い方を学びます。この包括的なガイド Aspose.HTML for .NET で Web 開発の可能性を最大限に引き出します。HTML ドキュメントを簡単に作成、変換、操作できます。 ### [C# の文字列から HTML を作成 – カスタム リソース ハンドラ ガイド](./create-html-from-string-in-c-custom-resource-handler-guide/) C# の文字列から HTML を生成し、カスタム リソース ハンドラで処理する方法をステップバイステップで解説します。 +### [プログラムでフォント スタイルを適用 – クイック C# ガイド](./apply-font-style-programmatically-quick-c-guide/) +C# でフォント スタイルをプログラム的に適用する方法を簡潔に解説します。 ## 結論 diff --git a/html/japanese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/japanese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..c27639f76 --- /dev/null +++ b/html/japanese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-04-23 +description: フォントスタイルをプログラムで適用し、テキストの下線を削除する方法、テキストスタイルを変更する方法、太字テキストをプログラムで設定する方法を簡潔なチュートリアルで学びましょう。 +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: ja +og_description: フォントスタイルをプログラムで適用し、テキストの下線を削除する方法、テキストスタイルを変更する方法、太字テキストをプログラムで設定する方法を、短く実用的なチュートリアルで紹介します。 +og_title: プログラムでフォントスタイルを適用する – 簡単C#ガイド +tags: +- csharp +- ui +- text-formatting +- programming +title: フォントスタイルをプログラムで適用する – 簡単C#ガイド +url: /ja/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# フォントスタイルをプログラムで適用する – クイック C# ガイド + +UI 要素に **apply font style** を適用したいけど、どこから始めればいいか分からないことはありませんか? あなただけではありません—多くの開発者が動的テキストフォーマットに手を出したときに同じ壁にぶつかります。良いニュースは、数分でラベルの外観を変更したり、テキストの下線を削除したり、プログラムで太字テキストを設定したりする方法が正確に分かるようになることです。 + +この **text formatting tutorial** では、完全に実行可能なサンプルを順に解説し、各行の「なぜ」を説明し、WinForms や WPF プロジェクトにそのままコピペできる実用的なヒントを提供します。余計な説明は省き、仕事を完了させるために必要なことだけをお伝えします。 + +--- + +## 学べること + +- 小さなヘルパークラスを使って **apply font style** を行う方法。 +- 他のスタイルはそのままに **remove underline from text** する正確な手順。 +- 実行時にテキストスタイル(太字、斜体、下線)を変更する方法。 +- **sets bold text programmatically** できる、コピー可能な完全スニペット。 +- 後で驚かないための一般的な落とし穴とエッジケースの対処法。 + +**前提条件:** .NET 6+(または最近の .NET Framework)、基本的な C# の知識、そしてお好みの IDE(Visual Studio、Rider、または VS Code)。これだけで完了です—追加の NuGet パッケージは不要です。 + +--- + +## ステップ 1 – コントロールにフォントスタイルを適用する + +任意の **apply font style** 操作の核心は、`FontStyle` 列挙体と `Font` オブジェクトの組み合わせです。コードをすっきりさせるために、列挙体ロジックを小さな `WebFontStyle` クラスでラップします。このクラスは元のスニペットで見たプロパティ(`Bold`、`Italic`、`Underline`)を鏡写しにし、`Font` に渡せる `FontStyle` 値を構築します。 + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**なぜ重要か:** +フラグ構築ロジックを分離することで、ビット単位の `|` 演算子を UI コード全体に散らばらせる必要がなくなります。読みやすく、テストしやすく、そして最も重要なのは **apply font style** の意図が明確になる点です。 + +--- + +## ステップ 2 – テキストの下線を削除し、他のスタイルは保持する + +既に下線が付いたラベルを受け継いだが、デザイン上は普通の太字テキストが必要なケースを想定してください。下線を除去する際に太字は失いたくありません。ここで `WebFontStyle` クラスの真価が発揮されます。 + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**重要ポイント:** `Underline = false` を明示的に設定すると、ヘルパーは下線フラグを除外します。この行を省略すると、以前の下線が残り続け、開発者が `Bold` プロパティだけを切り替えるときに起こりがちなバグの原因になります。 + +--- + +## ステップ 3 – テキストスタイルの変更: 太字、斜体、その他 + +「斜体も切り替えたい場合はどうすれば?」と考えるかもしれません。同じオブジェクトが任意の組み合わせに対応します。以下のマトリクスをコーディング時のリファレンスとして活用してください。 + +| Desired Style | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **Bold only** | true | false | false | +| *Italic only* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +必要なプロパティを設定し `ToFont` を呼び出すだけです。ヘルパーが重い処理を代行してくれるので、UI ロジックに集中できます。 + +--- + +## 完全例 – プログラムで太字テキストを設定する + +以下は **complete, runnable WinForms** の例です。新しいコンソールスタイルの WinForms プロジェクトに貼り付けて **F5** を押すだけで動作します。 + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### 期待される結果 + +プログラムを実行すると、ウィンドウに **“Hello, world!”** が **太字**、**斜体ではなく**、**下線なし**で表示されます。このビジュアル確認により、**apply font style** ロジックが正しく機能したことが分かります。 + +--- + +## プロのコツ & エッジケース + +- **動的更新:** フォーム表示後にスタイルを変更したい場合(例: チェックボックスの応答)、`WebFontStyle` インスタンスを再作成するかプロパティを変更して `lbl.Font` に再割り当てすれば UI が即座に更新されます。 +- **高 DPI 対応:** `Font` オブジェクトを置き換えると、Windows が現在の DPI に基づいて自動的にスケーリングします。手動でスケーリングを行う場合を除き、追加コードは不要です。 +- **WPF 相当:** WPF では `FontWeight`、`FontStyle`、`TextDecorations` をバインドし、`Font` オブジェクトを入れ替える代わりに使用します。ロジックの分離という考え方は同じです—スタイルロジックはビュー層から切り離しましょう。 +- **メモリリーク回避:** `Label.Font` を再割り当てすると新しい `Font` オブジェクトが生成されます。頻繁にスタイルを切り替える場合は古いフォントを破棄してください: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## 結論 + +これで .NET コントロールに **apply font style** を適用し、**remove underline from text** を行い、**change text style** を動的に切り替える方法が分かりました。コードはクリーンで再利用可能です。小さな `WebFontStyle` ヘルパーは、いくつかのブールフラグを堅牢でテスト可能なコンポーネントに変換し、完全例は数行で **set bold text programmatically** が可能であることを証明しています。 + +次は何をしますか? このアプローチをユーザー設定と組み合わせたり、`Strikeout` など他の `FontStyle` フラグを試したりしてみましょう。さらには、非技術者が実行時に太字・斜体・下線を選択できる小さな UI パネルを公開すれば、再コンパイル不要で柔軟に対応できます。 + +この **text formatting tutorial** が役に立ったら、コメントを残すかご自身のバリエーションを共有してください。コーディングを楽しんで、UI が常に思い通りの見た目になることを願っています! + +--- + +![C# でラベルにフォントスタイルを適用する方法を示すスクリーンショット](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/japanese/net/html-extensions-and-conversions/_index.md index 4110fd8e8..d6e87741c 100644 --- a/html/japanese/net/html-extensions-and-conversions/_index.md +++ b/html/japanese/net/html-extensions-and-conversions/_index.md @@ -75,9 +75,13 @@ Aspose.HTML for .NET を使用して、HTML コンテンツを ZIP アーカイ ### [C# で HTML を Zip に圧縮する方法 – HTML を Zip に保存](./how-to-zip-html-in-c-save-html-to-zip/) C# と Aspose.HTML を使用して、HTML コンテンツを Zip アーカイブに保存する手順をステップバイステップで解説します。 + ### [C# で HTML を ZIP に保存 – 完全インメモリ例](./save-html-to-zip-in-c-complete-in-memory-example/) Aspose.HTML for .NET を使用して、HTML をメモリ内で ZIP アーカイブに保存する手順をステップバイステップで解説します。 +### [C# で HTML を Zip に圧縮する方法 – カスタム リソース ハンドラ ガイド](./how-to-zip-html-in-c-custom-resource-handler-guide/) +C# と Aspose.HTML のカスタム リソース ハンドラを使用して、HTML を Zip に圧縮する手順を解説します。 + ## 結論 結論として、HTML の拡張と変換は、現代の Web 開発に不可欠な要素です。Aspose.HTML for .NET はプロセスを簡素化し、あらゆるレベルの開発者が利用できるようにします。当社のチュートリアルに従うことで、幅広いスキルを備えた熟練した Web 開発者になるための道を順調に進むことができます。 diff --git a/html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..4232c9c3c --- /dev/null +++ b/html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-23 +description: カスタムリソースハンドラを使用して C# で HTML を zip にする方法を学ぶ – HTML を zip として保存し、HTML を + zip に変換し、HTML から zip を作成するステップバイステップガイド +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: ja +og_description: C#でHTMLをZIPにする方法を解説:カスタムリソースハンドラを使用してHTMLをZIPとして保存し、HTMLをZIPに変換し、数分でHTMLからZIPを作成します。 +og_title: C#でHTMLをZIPにする方法 – カスタムリソースハンドラガイド +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: C#でHTMLをZIPする方法 – カスタムリソースハンドラガイド +url: /ja/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でHTMLをZIPにする方法 – カスタムリソースハンドラガイド + +**how to zip html** をディスクにファイルを書き出さずに C# のコードから直接実行したいと思ったことはありませんか? あなただけではありません。HTML ページとその CSS、画像、フォントをオフライン配布用にパッケージ化する必要があるとき、多くの開発者が壁にぶつかり、保守が困難になる即席のファイルシステムコードを書いてしまいます。 + +このチュートリアルでは、Aspose.HTML の `ResourceHandler` を使って **HTML を ZIP アーカイブとして保存** する、クリーンで再利用可能なアプローチを紹介します。また、**HTML を ZIP に変換** する方法にも触れ、.NET プロジェクトで **HTML から ZIP を作成** できるパターンを実演します。外部スクリプト不要、テンポラリフォルダ不要—純粋な C# だけです。 + +ガイドの最後まで読むと、リンクされたすべてのリソースを含む `result.zip` を生成するサンプルが手に入り、実際のプロジェクトにすぐ適用できる実用的なヒントがいくつか得られます。 + +## 前提条件 + +- .NET 6+(コードは .NET Framework 4.7.2 でも動作しますが、最新 SDK の使用を推奨します) +- Aspose.HTML for .NET NuGet パッケージ(`Aspose.HTML`) – `dotnet add package Aspose.HTML` でインストール +- ストリームと `System.IO.Compression` 名前空間に関する基本的な知識 +- お好みの IDE またはエディタ(Visual Studio、VS Code、Rider など) + +これらがすでに揃っているなら、すぐにコードへ進みましょう。まだの場合は、NuGet の 1 行インストールだけで完了です。その他はすべて自己完結しています。 + +## 手順 1: メモリ上にシンプルな HTML ドキュメントを作成 + +まず、圧縮したいページを表す `HTMLDocument` オブジェクトを用意します。実際のシナリオでは URL やファイルからロードすることもありますが、ここでは分かりやすさのためにインラインで小さなドキュメントを組み立てます。 + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Why this matters:** +> By keeping the document in memory we avoid any intermediate file I/O, which makes the later **convert html to zip** step fast and thread‑safe. + +## 手順 2: メモリ上の ZIP ストリームを準備 + +一時的な `.zip` ファイルをディスクに書き出す代わりに、`MemoryStream` を使用します。これによりすべてが RAM 上に収まり、アーカイブを直接クライアントに返す必要がある Web サービスやバックグラウンドジョブに最適です。 + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** The `using` statement ensures the stream is disposed automatically, preventing memory leaks. + +## 手順 3: カスタム ResourceHandler を実装 + +Aspose.HTML は外部アセット(CSS ファイル、画像、フォントなど)を検出するたびに `ResourceHandler` を呼び出します。`ResourceHandler` を継承して、各リソースをどこに配置するかを自由に決められます。ここでは、ZIP アーカイブ内のエントリとして書き込む実装を行います。 + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### カスタムハンドラが必要な理由 + +- **命名の制御** – アーカイブ内のファイル名を自由に決められます。 +- **一時ファイル不要** – ハンドラはインメモリの ZIP に直接書き込みます。 +- **再利用性** – このクラスさえプロジェクトに追加すれば、**save html as zip** がすぐに使えます。 + +## 手順 4: ハンドラを使って HTML ドキュメントを保存 + +ここで全体を結びつけます。`Save` メソッドはリンクされたすべてのアセットに対して `HandleResource` を呼び出し、ハンドラはそれらのバイト列を先ほど作成した ZIP アーカイブにストリームします。 + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **What happens under the hood?** +> Aspose parses the HTML, discovers the `` reference, asks the handler for a stream, and the handler creates a `logo.png` entry inside the ZIP. The same flow repeats for CSS, fonts, or any other external resource. + +## 手順 5: ZIP アーカイブをディスクに永続化(または返却) + +最後に、インメモリのアーカイブをファイルに書き出します。Web API であれば `zipMemoryStream.ToArray()` をバイト配列として返すことも可能です。 + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### 期待される結果 + +`result.zip` を開くと以下のようになっているはずです: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +ファイルエクスプローラでアーカイブを確認すると、HTML ファイルが `resource.bin` として保存されていることに気付くでしょう。これはフレンドリーネームを付けていないためです。`resourceInfo.ContentType` をチェックし、適切な場合は `.html` を付与すれば簡単に改善できます。 + +## 完全動作サンプル + +以下は、上記の手順すべてを組み込んだコピー&ペースト可能なプログラムです。コンソール アプリから実行すれば、すぐに共有可能な ZIP ファイルが生成されます。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Running this code** will generate `result.zip` in the program’s working directory. Open it and you’ll find `index.html` (our original page) plus `logo.png` if that image existed on disk or was fetched from a URL. + +## よくあるバリエーションとエッジケース + +| シナリオ | +|----------| + +{{< /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/generate-jpg-and-png-images/_index.md b/html/korean/net/generate-jpg-and-png-images/_index.md index 2f2fd11d0..05a3df750 100644 --- a/html/korean/net/generate-jpg-and-png-images/_index.md +++ b/html/korean/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET을 .NET 프로젝트에 통합하는 것은 번거롭지 DOCX 문서를 PNG 또는 JPG 이미지로 변환할 때 안티앨리어싱을 적용하는 방법을 단계별로 안내합니다. ### [DOCX를 PNG로 변환하고 ZIP 아카이브 만들기 C# 튜토리얼](./convert-docx-to-png-create-zip-archive-c-tutorial/) C#을 사용해 DOCX 파일을 PNG 이미지로 변환하고, 결과를 ZIP 파일로 압축하는 방법을 단계별로 안내합니다. +### [HTML에서 PNG 만들기 – C# 개발자를 위한 단계별 가이드](./create-png-from-html-step-by-step-guide-for-c-developers/) +C#을 사용해 HTML을 PNG 이미지로 변환하는 방법을 단계별로 안내합니다. ## 결론 diff --git a/html/korean/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/korean/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..7ae113f89 --- /dev/null +++ b/html/korean/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-04-23 +description: Aspose.HTML를 사용하여 HTML에서 PNG를 빠르게 생성하세요. HTML을 PNG로 렌더링하고, 캔버스 크기를 설정하며, + 배경 색상을 추가하고, 몇 분 안에 렌더링된 이미지를 저장하는 방법을 배워보세요. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: ko +og_description: Aspose.HTML를 사용하여 HTML에서 PNG 만들기. 이 가이드는 HTML을 PNG로 렌더링하고, 캔버스 크기를 + 설정하며, 배경 색을 추가하고, 렌더링된 이미지를 저장하는 방법을 보여줍니다. +og_title: HTML에서 PNG 만들기 – 완전한 C# 렌더링 튜토리얼 +tags: +- C# +- Aspose.HTML +- Image Rendering +title: HTML에서 PNG 만들기 – C# 개발자를 위한 단계별 가이드 +url: /ko/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML에서 PNG 만들기 – 완전한 C# 렌더링 튜토리얼 + +**HTML에서 PNG 만들기**가 필요했지만 어느 라이브러리가 선명하고 안티앨리어싱된 결과를 제공할지 몰라 고민한 적 있나요? 당신만 그런 것이 아닙니다. 많은 웹‑투‑이미지 파이프라인에서 가장 큰 고통은 텍스트와 그래픽이 브라우저에서 보이는 만큼 선명하게 보이도록 만드는 것입니다. + +좋은 소식은? Aspose.HTML을 사용하면 **HTML을 PNG로 렌더링**을 몇 줄의 코드만으로 수행하고, 캔버스 크기를 제어하며, 단색 배경을 추가하고, 마지막으로 **렌더링된 이미지를** 디스크에 **저장**할 수 있습니다—브라우저를 전혀 건드리지 않고도 가능합니다. 이 튜토리얼에서는 전체 과정을 단계별로 살펴보고, 각 설정이 왜 중요한지 설명하며, 바로 실행 가능한 예제를 보여드립니다. + +## 배울 내용 + +- 문자열, 파일 또는 URL에서 HTML을 로드하는 방법 +- 예측 가능한 출력물을 위해 **캔버스 크기 설정** 및 **배경색 추가**를 구성하는 방법 +- 날카로운 헤딩을 위한 안티앨리어싱 및 서브픽셀 텍스트 힌팅 활성화 +- **렌더링된 이미지를** PNG 파일로 **저장**하는 정확한 단계 +- 흔히 발생하는 문제점과 다양한 시나리오에 대한 선택적 조정 + +Aspose.HTML에 대한 사전 경험은 필요 없습니다; 기본적인 C# 설정과 Visual Studio(또는 선호하는 IDE)만 있으면 됩니다. + +--- + +## Step 1: Aspose.HTML for .NET 설치 + +코드를 작성하기 전에 프로젝트에 Aspose.HTML NuGet 패키지가 참조되어 있는지 확인하세요. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** 최신 안정 버전(2026년 4월 현재, 23.9.0)을 사용하면 최신 렌더링 엔진과 버그 수정 사항을 얻을 수 있습니다. + +--- + +## Step 2: HTML 소스 로드 – HTML에서 PNG 만들기 + +렌더러에 인라인 문자열, 로컬 파일 또는 원격 URL을 제공할 수 있습니다. 이번 데모에서는 사용자 정의 폰트를 포함한 간단한 인라인 문자열을 사용합니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**왜 중요한가:** `HTMLDocument`에 HTML을 로드하면 엔진이 DOM 파싱, CSS 계단식 적용, 레이아웃 계산을 완전히 제어할 수 있습니다. 또한 외부 브라우저 상태와 격리되어 재현 가능한 결과를 보장합니다. + +--- + +## Step 3: 렌더링 옵션 구성 – 캔버스 크기 설정 및 배경색 추가 + +`ImageRenderingOptions` 클래스를 사용하면 출력 이미지에 대해 세밀하게 조정할 수 있습니다. 여기서는 안티앨리어싱을 활성화하고, 흰색 배경을 설정하며, **800 × 600 px** 캔버스를 명시적으로 정의합니다. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**값을 변경할 수 있는 이유:** +- **캔버스 크기:** 썸네일이 필요하면 차원을 축소하고, **고해상도** 인쇄가 필요하면 확대합니다. +- **배경색:** 투명 PNG도 가능하지만, 많은 다운스트림 도구(예: **PowerPoint**)는 불투명 배경을 기대합니다. + +--- + +## Step 4: 렌더링 및 **렌더링된 이미지 저장** as PNG + +이제 본격적인 작업이 시작됩니다. `ImageRenderer`가 `HTMLDocument`와 방금 정의한 옵션을 사용해 PNG 스트림을 디스크에 씁니다. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +프로그램을 실행하면 데스크톱에 `result.png` 파일이 생성됩니다. 파일을 열면 흰색 캔버스 중앙에 깨끗하고 안티앨리어싱된 헤딩이 표시됩니다. + +> **예상 출력:** 흰색 배경에 “Antialiased Heading” 텍스트가 Arial 폰트로 렌더링된 800 × 600 PNG. Chrome에서 보이는 것과 동일하게 부드럽게 표시됩니다. + +--- + +## Step 5: 결과 확인 – 빠른 체크리스트 + +1. **파일 존재 여부:** `File.Exists(outputPath)`가 `true`를 반환해야 합니다. +2. **크기:** 이미지 뷰어에서 PNG를 열면 800 × 600 px가 표시되어야 합니다. +3. **시각적 품질:** 200 % 확대했을 때 텍스트 가장자리가 매끄럽게 유지되고, 거칠지 않아야 합니다. + +문제가 있다면 `UseAntialiasing`과 `UseHinting`이 모두 `true`로 설정되어 있는지 다시 확인하세요. 이 두 플래그가 고품질 렌더링의 비결입니다. + +--- + +## Common Variations & Edge Cases + +| Scenario | What to Adjust | Why | +|----------|----------------|-----| +| **원격 웹 페이지 렌더링** | `new HTMLDocument(htmlContent)`를 `new HTMLDocument("https://example.com")`으로 교체 | HTML을 직접 복사하지 않고도 실시간 사이트를 캡처할 수 있습니다. | +| **투명 배경** | `BackgroundColor = Color.Transparent` 및 `ImageFormat.Png` 사용 | PNG를 다른 그래픽 위에 오버레이할 때 유용합니다. | +| **다른 이미지 포맷** | `renderer.Save(pngStream, ImageFormat.Jpeg)` 로 변경 | 사진 콘텐츠에는 JPEG가 더 작을 수 있지만 무손실 품질은 손실됩니다. | +| **동적 캔버스 크기** | 레이아웃 후 `imgOptions.Width = htmlDoc.Body.ClientWidth;` 사용 | HTML 콘텐츠의 자연스러운 너비에 맞게 이미지 크기를 조정합니다. | +| **고 DPI 출력** | `Width`와 `Height`에 스케일 팩터(예: 2)를 곱함 | 최신 디스플레이용 레티나 준비 자산을 생성합니다. | + +--- + +## Full Working Example (Copy‑Paste Ready) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +프로그램을 실행(`dotnet run` 또는 Visual Studio에서 F5)하면 이메일, 보고서 또는 HTML 정적 이미지를 필요로 하는 모든 곳에서 사용할 수 있는 완벽하게 렌더링된 PNG가 생성됩니다. + +--- + +## Frequently Asked Questions + +**Q: CSS 3의 flexbox 같은 기능도 지원하나요?** +A: 네. Aspose.HTML은 flexbox, grid, **media queries** 등 대부분의 최신 CSS를 지원합니다. 최신 라이브러리 버전을 사용하고 있는지 확인하세요. + +**Q: HTML에 외부 이미지가 포함되어 있으면 어떻게 되나요?** +A: 렌더러는 문서의 base URI를 기준으로 **상대 URL**을 따라갑니다. 문자열에서 HTML을 로드하는 경우 `doc.BaseUrl`을 자산이 있는 폴더로 설정하세요. + +**Q: 여러 페이지를 하나의 PNG로 렌더링할 수 있나요?** +A: 직접적으로는 불가능합니다—각 `ImageRenderer` 호출은 단일 래스터 이미지를 생성합니다. **다중 페이지 출력**이 필요하면 각 페이지를 별도로 렌더링한 뒤 ImageSharp와 같은 그래픽 라이브러리로 합쳐야 합니다. + +--- + +## Conclusion + +이제 Aspose.HTML을 사용해 **HTML에서 PNG 만들기**에 대한 완전한 엔드‑투‑엔드 솔루션을 갖추었습니다. **HTML을 PNG로 렌더링** 옵션—예를 들어 **캔버스 크기 설정**, **배경색 추가**, 안티앨리어싱 활성화—을 구성함으로써 브라우저 없이도 전문가 수준의 이미지를 생성할 수 있습니다. + +앞으로 DPI를 높이거나 투명 배경을 사용하거나 수십 개의 HTML 스니펫을 배치 처리하는 등 다양한 실험을 해볼 수 있습니다. 썸네일 서비스, PDF 생성 파이프라인, 정적 사이트 미리보기 도구 등 어떤 시나리오에서도 동일한 패턴이 적용됩니다. + +즐거운 렌더링 되세요, 그리고 문제가 생기면 언제든지 댓글로 알려주세요! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/korean/net/html-document-manipulation/_index.md b/html/korean/net/html-document-manipulation/_index.md index dc4818e47..2ac3d11d8 100644 --- a/html/korean/net/html-document-manipulation/_index.md +++ b/html/korean/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML for .NET을 사용하여 동적이고 웹 콘텐츠를 만드는 방 .NET용 Aspose.HTML을 사용하는 방법을 배우세요. 이 포괄적인 가이드로 네임스페이스를 가져오고, HTML을 XML과 병합하고, 웹 개발 기술을 향상시키세요. ### [Aspose.HTML을 사용하여 .NET에서 XpsDevice로 XPS 문서 생성](./generate-xps-documents-by-xpsdevice/) Aspose.HTML for .NET으로 웹 개발의 잠재력을 열어보세요. HTML 문서를 쉽게 만들고, 변환하고, 조작하세요. +### [프로그래밍으로 글꼴 스타일 적용 – 빠른 C# 가이드](./apply-font-style-programmatically-quick-c-guide/) +Aspose.HTML for .NET을 사용하여 글꼴 스타일을 프로그래밍 방식으로 적용하는 방법을 단계별로 안내합니다. ## 결론 diff --git a/html/korean/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/korean/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..76d03a744 --- /dev/null +++ b/html/korean/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-04-23 +description: 프로그래밍으로 글꼴 스타일을 적용하고, 텍스트에서 밑줄을 제거하고, 텍스트 스타일을 변경하며, 굵은 텍스트를 설정하는 방법을 + 간결한 튜토리얼에서 배워보세요. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: ko +og_description: 프로그래밍으로 글꼴 스타일을 적용하고, 텍스트에서 밑줄을 제거하고, 텍스트 스타일을 변경하며, 굵은 텍스트를 설정하는 + 방법을 짧고 실용적인 튜토리얼에서 알아보세요. +og_title: 프로그래밍으로 글꼴 스타일 적용 – 빠른 C# 가이드 +tags: +- csharp +- ui +- text-formatting +- programming +title: 프로그래밍으로 글꼴 스타일 적용 – 빠른 C# 가이드 +url: /ko/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 프로그램matically 폰트 스타일 적용하기 – 빠른 C# 가이드 + +UI 요소에 **폰트 스타일을 적용**해야 하는데 어디서부터 시작해야 할지 막막했나요? 당신만 그런 것이 아닙니다—동적 텍스트 포맷팅을 처음 다룰 때 대부분의 개발자가 이 문제에 부딪힙니다. 좋은 소식은? 몇 분만 투자하면 레이블의 외관을 바꾸고, 텍스트의 밑줄을 제거하며, 굵은 텍스트를 프로그래밍 방식으로 설정하는 방법을 정확히 알 수 있습니다. + +이 **텍스트 포맷팅 튜토리얼**에서는 완전하고 실행 가능한 예제를 단계별로 살펴보고, 각 라인 뒤에 숨은 “왜”를 설명하며, WinForms 또는 WPF 프로젝트 어디에든 복사‑붙여넣기 할 수 있는 실용적인 팁을 제공할 것입니다. 불필요한 내용은 없고, 바로 작업을 수행할 수 있는 내용만 담았습니다. + +--- + +## 배울 내용 + +- 작은 헬퍼 클래스를 사용해 **폰트 스타일을 적용**하는 방법. +- 다른 스타일은 유지하면서 **텍스트의 밑줄을 제거**하는 정확한 단계. +- 실행 중에 **텍스트 스타일(굵게, 기울임, 밑줄)**을 변경하는 방법. +- **프로그램matically 굵은 텍스트를 설정**하는 완전한 복사‑가능 스니펫. +- 나중에 놀라지 않도록 흔히 겪는 함정과 엣지‑케이스 처리 방법. + +**전제 조건:** .NET 6+ (또는 최신 .NET Framework), 기본 C# 지식, 그리고 선호하는 IDE(Visual Studio, Rider, VS Code). 추가 NuGet 패키지는 필요 없습니다. + +--- + +## Step 1 – 컨트롤에 폰트 스타일 적용하기 + +어떤 **폰트 스타일 적용** 작업이든 핵심은 `FontStyle` 열거형과 `Font` 객체를 결합하는 것입니다. 코드를 깔끔하게 유지하기 위해 작은 `WebFontStyle` 클래스로 열거형 로직을 감쌀 것입니다. 이 클래스는 원본 스니펫(`Bold`, `Italic`, `Underline`)에 있던 속성을 그대로 반영하고, `Font`에 전달할 수 있는 `FontStyle` 값을 만들어 줍니다. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**왜 중요한가:** +플래그‑구성 로직을 별도로 분리하면 UI 코드 곳곳에 비트 연산자 `|`를 흩뿌리는 일을 피할 수 있습니다. 읽기 쉽고, 테스트하기 쉬우며—무엇보다 **폰트 스타일 적용** 의도가 명확해집니다. + +--- + +## Step 2 – 텍스트의 밑줄 제거 (다른 스타일은 그대로 유지) + +이미 밑줄이 적용된 레이블을 상속받았지만 디자인상에서는 일반 굵은 텍스트가 필요하다고 가정해 보세요. 굵기는 유지하면서 밑줄만 없애고 싶을 겁니다. 바로 여기서 `WebFontStyle` 클래스가 빛을 발합니다. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**핵심 포인트:** `Underline = false` 를 명시적으로 설정하면 헬퍼가 밑줄 플래그를 *제외*하도록 지시합니다. 이 라인을 아예 빼면 이전에 적용된 밑줄이 그대로 남아 버리는 경우가 흔히 발생하는 버그의 원인입니다. + +--- + +## Step 3 – 텍스트 스타일 변경: 굵게, 기울임, 그리고 그 이상 + +“기울임도 토글해야 하면 어떻게 할까?” 라고 생각할 수 있습니다. 같은 객체가 모든 조합을 지원합니다. 아래 매트릭스를 참고해 코딩에 활용해 보세요. + +| Desired Style | Bold | Italic | Underline | +|---------------|------|--------|-----------| +| **Bold only** | true | false | false | +| *Italic only* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +필요한 속성을 설정하고 `ToFont` 를 호출하면 됩니다. 헬퍼가 무거운 작업을 대신해 주므로 UI 로직에 집중할 수 있습니다. + +--- + +## Full Example – 프로그램matically 굵은 텍스트 설정하기 + +아래는 **완전하고 실행 가능한 WinForms** 예제로, 지금까지 다룬 모든 내용을 보여줍니다. 새 콘솔‑스타일 WinForms 프로젝트에 붙여넣고 **F5** 를 눌러 실행해 보세요. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### 기대 결과 + +프로그램을 실행하면 **“Hello, world!”** 라는 텍스트가 **굵게**, **기울임 없이**, **밑줄 없이** 표시되는 창이 나타납니다. 이 시각적 확인을 통해 **폰트 스타일 적용** 로직이 정상적으로 동작했음을 알 수 있습니다. + +--- + +## Pro Tips & Edge Cases + +- **동적 업데이트:** 폼이 표시된 뒤 스타일을 바꿔야 할 경우(예: 체크박스 응답) `WebFontStyle` 인스턴스를 새로 만들거나 속성을 수정한 뒤 `lbl.Font`에 다시 할당하면 UI가 즉시 업데이트됩니다. +- **고 DPI 고려사항:** `Font` 객체를 교체하면 Windows가 현재 DPI에 맞게 자동으로 스케일링합니다. 직접 스케일링을 처리하지 않는 한 추가 코드는 필요 없습니다. +- **WPF 대응:** WPF에서는 `FontWeight`, `FontStyle`, `TextDecorations`를 바인딩하고 `Font` 객체를 교체하지 않습니다. 동일한 논리적 분리를 유지하면 됩니다—스타일 로직을 뷰 레이어에서 분리하세요. +- **메모리 누수 방지:** `Label.Font`를 재할당하면 새로운 `Font` 객체가 생성됩니다. 스타일을 자주 교체한다면 이전 객체를 `Dispose` 해야 합니다: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## 결론 + +이제 **폰트 스타일을 적용**하고, **텍스트의 밑줄을 제거**하며, **실행 중에 텍스트 스타일을 변경**하는 방법을 알게 되었습니다—코드를 깔끔하고 재사용 가능하게 유지하면서요. 작은 `WebFontStyle` 헬퍼는 몇 개의 불리언 플래그를 견고하고 테스트 가능한 컴포넌트로 변환해 주며, 전체 예제는 몇 줄만으로 **프로그램matically 굵은 텍스트를 설정**할 수 있음을 증명합니다. + +다음 단계는? 이 방식을 사용자 설정과 결합하거나, `Strikeout` 같은 다른 `FontStyle` 플래그를 실험해 보세요. 비기술 사용자도 런타임에 굵게, 기울임, 밑줄을 선택할 수 있는 작은 UI 패널을 제공하면 재컴파일 없이도 UI를 맞춤화할 수 있습니다. + +이 **텍스트 포맷팅 튜토리얼**이 도움이 되었다면 댓글을 남기거나 직접 변형한 예제를 공유해 주세요. 즐거운 코딩 되시고, UI가 언제나 원하는 대로 보이길 바랍니다! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/korean/net/html-extensions-and-conversions/_index.md index 38fc3bd7e..b7804b8a1 100644 --- a/html/korean/net/html-extensions-and-conversions/_index.md +++ b/html/korean/net/html-extensions-and-conversions/_index.md @@ -67,8 +67,8 @@ Aspose.HTML for .NET을 사용하여 HTML을 TIFF로 변환하는 방법을 알 .NET용 Aspose.HTML의 힘을 알아보세요: HTML을 XPS로 손쉽게 변환하세요. 필수 조건, 단계별 가이드, FAQ가 포함되어 있습니다. ### [C#에서 HTML을 Zip으로 압축하는 방법 – HTML을 Zip으로 저장](./how-to-zip-html-in-c-save-html-to-zip/) C#과 Aspose.HTML을 사용해 HTML 파일을 ZIP 압축 파일로 저장하는 단계별 가이드를 제공합니다. -### [스타일이 적용된 텍스트로 HTML 문서 만들기 및 PDF로 내보내기 – 전체 가이드](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Aspose.HTML for .NET을 사용하여 스타일이 적용된 텍스트가 포함된 HTML 문서를 만들고 PDF로 내보내는 전체 가이드를 확인하세요. +### [C#에서 HTML을 ZIP으로 압축하는 방법 – 커스텀 리소스 핸들러 가이드](./how-to-zip-html-in-c-custom-resource-handler-guide/) +C#와 Aspose.HTML을 사용해 커스텀 리소스 핸들러로 HTML을 ZIP 파일로 저장하는 단계별 가이드. ### [HTML을 ZIP으로 저장 – 전체 C# 튜토리얼](./save-html-as-zip-complete-c-tutorial/) Aspose.HTML for .NET을 사용해 HTML을 ZIP 파일로 저장하는 전체 C# 단계별 튜토리얼. ### [C#에서 HTML을 ZIP으로 저장 – 완전 인메모리 예제](./save-html-to-zip-in-c-complete-in-memory-example/) diff --git a/html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..c03a47d8d --- /dev/null +++ b/html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-23 +description: 맞춤 리소스 핸들러를 사용해 C#에서 HTML을 zip하는 방법을 배우세요 – HTML을 zip으로 저장하고, HTML을 zip으로 + 변환하며, HTML에서 zip을 생성하는 단계별 가이드. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: ko +og_description: 'C#에서 HTML을 zip으로 압축하는 방법: 사용자 정의 리소스 핸들러를 사용해 HTML을 zip으로 저장하고, HTML을 + zip으로 변환하며, 몇 분 안에 HTML에서 zip을 생성합니다.' +og_title: C#에서 HTML을 압축하는 방법 – 커스텀 리소스 핸들러 가이드 +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: C#에서 HTML을 압축하는 방법 – 맞춤 리소스 핸들러 가이드 +url: /ko/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML을 ZIP으로 압축하는 방법 – 커스텀 리소스 핸들러 가이드 + +HTML 페이지와 그 CSS, 이미지, 폰트를 오프라인 배포용으로 패키징해야 할 때, 파일을 먼저 디스크에 풀어놓고 압축하는 번거로운 작업을 해본 적 있나요? 많은 개발자들이 이 문제에 부딪히고, 유지보수가 어려운 임시 파일 시스템 코드를 작성하게 됩니다. + +이 튜토리얼에서는 Aspose.HTML의 `ResourceHandler`를 사용해 **HTML을 ZIP 아카이브로 저장**하는 깔끔하고 재사용 가능한 방법을 보여드립니다. 또한 **HTML을 ZIP으로 변환**하는 방법을 간단히 다루고, **HTML에서 ZIP을 만들기** 위한 패턴을 .NET 프로젝트 어디서든 재사용할 수 있도록 시연합니다. 외부 스크립트도, 임시 폴더도 필요 없습니다—순수 C#만으로 구현합니다. + +가이드를 끝까지 따라오시면, 모든 연결된 리소스를 포함한 `result.zip`을 생성하는 실행 가능한 샘플과, 실제 프로젝트에 적용할 수 있는 실용적인 팁들을 얻으실 수 있습니다. + +## Prerequisites + +- .NET 6+ (코드는 .NET Framework 4.7.2에서도 동작하지만 최신 SDK 사용을 권장합니다) +- Aspose.HTML for .NET NuGet 패키지 (`Aspose.HTML`) – `dotnet add package Aspose.HTML` 로 설치 +- 스트림 및 `System.IO.Compression` 네임스페이스에 대한 기본 지식 +- 선호하는 IDE 또는 편집기 (Visual Studio, VS Code, Rider 등) + +이미 준비되어 있다면 바로 코드로 들어갑니다. 아직이라면 NuGet 한 줄 설치만 하면 됩니다; 나머지는 모두 포함되어 있습니다. + +## Step 1: Create a Simple HTML Document in Memory + +먼저 압축하고자 하는 페이지를 나타내는 `HTMLDocument` 객체가 필요합니다. 실제 환경에서는 URL이나 파일에서 로드할 수 있지만, 여기서는 이해를 돕기 위해 인라인으로 작은 문서를 만들겠습니다. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Why this matters:** +> 문서를 메모리에 보관함으로써 중간 파일 I/O를 피할 수 있어, 이후 **convert html to zip** 단계가 빠르고 스레드‑안전하게 진행됩니다. + +## Step 2: Prepare an In‑Memory ZIP Stream + +임시 `.zip` 파일을 디스크에 쓰는 대신 `MemoryStream`을 사용합니다. 이렇게 하면 모든 작업이 RAM에서 이루어져, 웹 서비스나 백그라운드 작업에서 아카이브를 바로 클라이언트에 반환할 때 이상적입니다. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** `using` 문은 스트림을 자동으로 해제해 메모리 누수를 방지합니다. + +## Step 3: Implement a Custom ResourceHandler + +Aspose.HTML은 발견한 외부 자산(CSS 파일, 이미지, 폰트 등)마다 `ResourceHandler`를 호출합니다. `ResourceHandler`를 상속하면 각 리소스가 어디에 저장될지 정확히 제어할 수 있습니다—우리 경우엔 ZIP 아카이브 내부의 엔트리로 저장합니다. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Why a Custom Handler? + +- **Control over naming** – 파일이 아카이브에 어떻게 표시될지 직접 정합니다. +- **No temporary files** – 핸들러가 바로 인‑메모리 ZIP에 씁니다. +- **Reusability** – 이 클래스를 **save html as zip**이 필요한 어떤 프로젝트에도 그대로 넣어 사용할 수 있습니다. + +## Step 4: Save the HTML Document Using the Handler + +이제 모든 것을 연결합니다. `Save` 메서드는 연결된 각 자산에 대해 `HandleResource`를 호출하고, 핸들러는 해당 바이트를 앞서 만든 ZIP 스트림에 기록합니다. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **What happens under the hood?** +> Aspose가 HTML을 파싱하면서 ``와 같은 참조를 발견하고, 스트림을 요청하면 핸들러가 `logo.png` 엔트리를 ZIP에 생성합니다. CSS, 폰트, 기타 외부 리소스도 동일한 흐름으로 처리됩니다. + +## Step 5: Persist the ZIP Archive to Disk (or Return It) + +마지막으로 인‑메모리 아카이브를 파일로 저장합니다. 웹 API에서는 대신 `zipMemoryStream.ToArray()`를 바이트 배열로 반환할 수 있습니다. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Expected Result + +`result.zip`을 열면 다음과 같은 구조가 보일 것입니다: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +파일 탐색기에서 아카이브를 확인하면 HTML 파일이 `resource.bin`으로 저장된 것을 볼 수 있습니다. 이는 친숙한 이름을 지정하지 않았기 때문인데, `resourceInfo.ContentType`을 검사하고 적절할 때 `.html`을 할당하면 쉽게 개선할 수 있습니다. + +## Full Working Example + +아래는 앞서 설명한 모든 단계를 포함한 완전한 복사‑붙여넣기 가능한 프로그램입니다. 콘솔 앱에서 실행하면 바로 공유 가능한 ZIP 파일이 생성됩니다. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Running this code** will generate `result.zip` in the program’s working directory. Open it and you’ll find `index.html` (our original page) plus `logo.png` if that image existed on disk or was fetched from a URL. + +## Common Variations & Edge Cases + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/polish/net/generate-jpg-and-png-images/_index.md index fff5f7a92..ba3259d36 100644 --- a/html/polish/net/generate-jpg-and-png-images/_index.md +++ b/html/polish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Naucz się używać Aspose.HTML dla .NET do manipulowania dokumentami HTML, konw Dowiedz się, jak włączyć antyaliasing przy konwersji dokumentów DOCX do formatów PNG i JPG przy użyciu Aspose.HTML. ### [Konwertuj docx do png – utwórz archiwum zip w C# – samouczek](./convert-docx-to-png-create-zip-archive-c-tutorial/) Dowiedz się, jak konwertować pliki DOCX na obrazy PNG i spakować je do archiwum ZIP przy użyciu C# i Aspose.HTML. +### [Utwórz PNG z HTML – przewodnik krok po kroku dla programistów C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Dowiedz się, jak w prosty sposób konwertować HTML do plików PNG w C# przy użyciu Aspose.HTML, krok po kroku. ## Wniosek diff --git a/html/polish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/polish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..86ba95b79 --- /dev/null +++ b/html/polish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Szybko twórz pliki PNG z HTML za pomocą Aspose.HTML. Dowiedz się, jak + renderować HTML do PNG, ustawiać rozmiar płótna, dodawać kolor tła i zapisywać wyrenderowany + obraz w ciągu kilku minut. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: pl +og_description: Utwórz PNG z HTML za pomocą Aspose.HTML. Ten przewodnik pokazuje, + jak renderować HTML do PNG, ustawić rozmiar płótna, dodać kolor tła i zapisać wyrenderowany + obraz. +og_title: Utwórz PNG z HTML – Kompletny poradnik renderowania w C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Tworzenie PNG z HTML – Przewodnik krok po kroku dla programistów C# +url: /pl/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tworzenie PNG z HTML – Kompletny poradnik renderowania w C# + +Kiedykolwiek potrzebowałeś **utworzyć PNG z HTML**, ale nie byłeś pewien, która biblioteka zapewni Ci wyraźne, antyaliasowane wyniki? Nie jesteś sam. W wielu przepływach pracy web‑to‑image największym problemem jest uzyskanie tekstu i grafiki o takiej samej ostrości, jak w przeglądarce. + +Dobra wiadomość? Z Aspose.HTML możesz **renderować HTML do PNG** w kilku linijkach, kontrolować rozmiar płótna, dodać jednolity kolor tła i w końcu **zapisać wyrenderowany obraz** na dysku — bez użycia przeglądarki. W tym poradniku przejdziemy przez cały proces, wyjaśnimy, dlaczego każde ustawienie ma znaczenie, i pokażemy gotowy przykład do uruchomienia. + +## Czego się nauczysz + +- Jak wczytać HTML ze stringa, pliku lub URL +- Jak skonfigurować **rozmiar płótna** i **dodać kolor tła** dla przewidywalnego wyniku +- Włączenie antyaliasingu i podpikselowego hintingu tekstu dla ostrych nagłówków +- Dokładne kroki, aby **zapisać wyrenderowany obraz** jako plik PNG +- Typowe pułapki i opcjonalne poprawki dla różnych scenariuszy + +Nie wymagana jest wcześniejsza znajomość Aspose.HTML; wystarczy podstawowa konfiguracja C# i Visual Studio (lub Twoje ulubione IDE). + +--- + +## Krok 1: Zainstaluj Aspose.HTML dla .NET + +Zanim napiszesz jakikolwiek kod, upewnij się, że pakiet NuGet Aspose.HTML jest dodany do Twojego projektu. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Użyj najnowszej stabilnej wersji (stan na kwiecień 2026, 23.9.0), aby uzyskać najnowszy silnik renderujący i poprawki błędów. + +--- + +## Krok 2: Wczytaj źródło HTML – Tworzenie PNG z HTML + +Możesz przekazać rendererowi string w kodzie, lokalny plik lub zdalny URL. W tym demo użyjemy prostego stringa zawierającego nagłówek z niestandardową czcionką. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Dlaczego to ważne:** Wczytanie HTML do `HTMLDocument` daje silnikowi pełną kontrolę nad parsowaniem DOM, kaskadą CSS i obliczeniami układu. Izoluje to także renderowanie od jakiegokolwiek zewnętrznego stanu przeglądarki, zapewniając powtarzalne wyniki. + +--- + +## Krok 3: Skonfiguruj opcje renderowania – Ustaw rozmiar płótna i dodaj kolor tła + +Klasa `ImageRenderingOptions` pozwala precyzyjnie dostroić wyjściowy obraz. Tutaj włączymy antyaliasing, ustawimy białe tło i jawnie zdefiniujemy płótno o **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Dlaczego możesz chcieć zmienić te wartości:** +- **Rozmiar płótna:** Jeśli potrzebujesz miniaturki, zmniejsz wymiary; dla wysokiej rozdzielczości wydruków zwiększ je. +- **Kolor tła:** Przezroczyste PNG są możliwe, ale wiele narzędzi downstream (np. PowerPoint) oczekuje nieprzezroczystego tła. + +--- + +## Krok 4: Renderuj i **zapisz wyrenderowany obraz** jako PNG + +Teraz następuje ciężka praca. `ImageRenderer` pobiera `HTMLDocument` oraz zdefiniowane opcje, a następnie zapisuje strumień PNG na dysk. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Po uruchomieniu programu znajdziesz `result.png` na pulpicie. Otwórz go, a zobaczysz czysty, antyaliasowany nagłówek wyśrodkowany na białym płótnie. + +> **Oczekiwany wynik:** PNG 800 × 600 z białym tłem i tekstem „Antialiased Heading” renderowanym w Arial, wyglądającym tak gładko, jak w Chrome. + +--- + +## Krok 5: Zweryfikuj wynik – Szybkie kontrole + +1. **Istnienie pliku:** `File.Exists(outputPath)` powinno zwrócić `true`. +2. **Wymiary:** Otwórz PNG w dowolnym przeglądarce obrazów; powinien raportować 800 × 600 px. +3. **Jakość wizualna:** Powiększ do 200 % – krawędzie tekstu muszą pozostać gładkie, nie postrzępione. + +Jeśli coś wygląda nie tak, sprawdź, czy `UseAntialiasing` i `UseHinting` są ustawione na `true`. Te dwa flagi to sekret wysokiej jakości renderowania. + +--- + +## Typowe wariacje i przypadki brzegowe + +| Scenariusz | Co należy dostosować | Dlaczego | +|------------|----------------------|----------| +| **Renderowanie zdalnej strony internetowej** | Zamień `new HTMLDocument(htmlContent)` na `new HTMLDocument("https://example.com")` | Umożliwia przechwycenie stron na żywo bez ręcznego kopiowania HTML. | +| **Przezroczyste tło** | Ustaw `BackgroundColor = Color.Transparent` i użyj `ImageFormat.Png` | Przydatne przy nakładaniu PNG na inne grafiki. | +| **Inny format obrazu** | Zmień `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG może być mniejszy przy treściach fotograficznych, ale traci jakość bezstratną. | +| **Dynamiczny rozmiar płótna** | Użyj `imgOptions.Width = htmlDoc.Body.ClientWidth;` po układzie | Pozwala obrazowi dopasować się do naturalnej szerokości treści HTML. | +| **Wyjście w wysokiej rozdzielczości DPI** | Pomnóż `Width` i `Height` przez współczynnik skali (np. 2) | Generuje zasoby gotowe na wyświetlacze Retina dla nowoczesnych ekranów. | + +--- + +## Pełny działający przykład (gotowy do kopiowania) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Uruchom program (`dotnet run` lub naciśnij F5 w Visual Studio) i otrzymasz perfekcyjnie wyrenderowany PNG gotowy do użycia w e‑mailach, raportach lub w dowolnym miejscu, gdzie potrzebny jest statyczny obraz HTML. + +--- + +## Najczęściej zadawane pytania + +**P: Czy to działa z funkcjami CSS 3 takimi jak flexbox?** +O: Tak. Aspose.HTML obsługuje większość nowoczesnych funkcji CSS, w tym flexbox, grid i media queries. Wystarczy, że korzystasz z najnowszej wersji biblioteki. + +**P: Co jeśli mój HTML odwołuje się do zewnętrznych obrazów?** +O: Renderer podąża za względnymi URL‑ami w oparciu o bazowy URI dokumentu. Jeśli wczytujesz HTML ze stringa, ustaw `doc.BaseUrl` na folder zawierający zasoby. + +**P: Czy mogę renderować wiele stron w jednym PNG?** +O: Nie bezpośrednio — każde wywołanie `ImageRenderer` generuje pojedynczy obraz rastrowy. Aby uzyskać wielostronicowy wynik, renderuj każdą stronę osobno i połącz je przy pomocy biblioteki graficznej (np. ImageSharp). + +--- + +## Podsumowanie + +Masz teraz solidne, kompleksowe rozwiązanie do **tworzenia PNG z HTML** przy użyciu Aspose.HTML. Konfigurując opcje **render html to png** — takie jak **set canvas size**, **add background color** i włączając antyaliasing — możesz generować obrazy profesjonalnej jakości bez przeglądarki. + +Od tego momentu możesz eksperymentować z wyższym DPI, przezroczystymi tłami lub przetwarzaniem wsadowym dziesiątek fragmentów HTML. Ten sam wzorzec sprawdzi się, czy budujesz usługę miniatur, pipeline generowania PDF, czy narzędzie podglądu statycznych stron. + +Miłego renderowania, a w razie problemów zostaw komentarz! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/polish/net/html-document-manipulation/_index.md index 4d8dfd764..619c7a404 100644 --- a/html/polish/net/html-document-manipulation/_index.md +++ b/html/polish/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Naucz się korzystać z Aspose.HTML dla .NET. Importuj przestrzenie nazw, scalaj Odblokuj potencjał rozwoju sieci z Aspose.HTML dla .NET. Twórz, konwertuj i manipuluj dokumentami HTML w prosty sposób. ### [Tworzenie HTML z ciągu w C# – Przewodnik po niestandardowym obsługiwaniu zasobów](./create-html-from-string-in-c-custom-resource-handler-guide/) Dowiedz się, jak generować dokumenty HTML z łańcucha znaków w C# przy użyciu niestandardowego obsługiwacza zasobów w Aspose.HTML. +### [Zastosowanie stylu czcionki programowo – szybki przewodnik C#](./apply-font-style-programmatically-quick-c-guide/) +Dowiedz się, jak programowo ustawiać style czcionki w dokumentach HTML przy użyciu Aspose.HTML i C#. ## Wniosek diff --git a/html/polish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/polish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..bbb3225fb --- /dev/null +++ b/html/polish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Zastosuj styl czcionki programowo i dowiedz się, jak usunąć podkreślenie + z tekstu, zmienić styl tekstu oraz ustawić pogrubiony tekst programowo w zwięzłym + samouczku. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: pl +og_description: Zastosuj styl czcionki programowo i dowiedz się, jak usunąć podkreślenie + z tekstu, zmienić styl tekstu oraz ustawić pogrubiony tekst programowo w krótkim, + praktycznym poradniku. +og_title: Zastosuj styl czcionki programowo – szybki przewodnik C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Zastosuj styl czcionki programowo – szybki przewodnik C# +url: /pl/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Zastosuj styl czcionki programowo – szybki przewodnik C# + +Kiedykolwiek potrzebowałeś **apply font style** na elemencie UI, ale nie wiedziałeś od czego zacząć? Nie jesteś jedyny — większość programistów napotyka ten problem, gdy po raz pierwszy bawi się dynamicznym formatowaniem tekstu. Dobra wiadomość? W ciągu kilku minut dokładnie dowiesz się, jak zmienić wygląd etykiety, usunąć podkreślenie z tekstu i ustawić pogrubiony tekst programowo, bez przeszukiwania niekończących się dokumentacji. + +W tym **text formatting tutorial** przeprowadzimy Cię przez kompletny, działający przykład, wyjaśnimy „dlaczego” za każdą linią i podamy praktyczne wskazówki, które możesz kopiować‑wklejać do dowolnego projektu WinForms lub WPF. Bez zbędnych treści, tylko to, co naprawdę działa. + +--- + +## Czego się nauczysz + +- Jak **apply font style** przy użyciu małej klasy pomocniczej. +- Precyzyjne kroki, aby **remove underline from text**, zachowując pozostałe style. +- Sposoby na **change text style** (pogrubienie, kursywa, podkreślenie) w locie. +- Pełny, gotowy do kopiowania fragment kodu, który **sets bold text programmatically**. +- Typowe pułapki i obsługa przypadków brzegowych, aby nie zostać zaskoczonym później. + +**Prerequisites:** .NET 6+ (lub dowolny nowszy .NET Framework), podstawowa znajomość C#, oraz wybrane przez Ciebie IDE (Visual Studio, Rider lub VS Code). To wszystko — nie są wymagane dodatkowe pakiety NuGet. + +--- + +## Krok 1 – Zastosuj styl czcionki w swoim kontrolce + +Rdzeniem każdej operacji **apply font style** jest wyliczenie `FontStyle` połączone z obiektem `Font`. Aby utrzymać kod schludnym, opakujemy logikę wyliczenia w małej klasie `WebFontStyle`. Klasa ta odzwierciedla właściwości, które widziałeś w oryginalnym fragmencie (`Bold`, `Italic`, `Underline`) i tworzy wartość `FontStyle`, którą możesz przekazać do `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Dlaczego to ma znaczenie:** +Izolując logikę budowania flag, unikasz rozrzucania bitowych operacji `|` w całym kodzie UI. Jest to łatwiejsze do odczytania, łatwiejsze do testowania i — co najważniejsze — sprawia, że intencja **apply font style** jest krystalicznie jasna. + +--- + +## Krok 2 – Usuń podkreślenie z tekstu (i zachowaj pozostałe style) + +Załóżmy, że odziedziczyłeś etykietę, która jest już podkreślona, ale projekt wymaga zwykłego pogrubionego tekstu. Nie chcesz tracić pogrubienia, usuwając podkreślenie. Właśnie tutaj klasa `WebFontStyle` błyszczy. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Kluczowy punkt:** Ustawienie `Underline = false` wyraźnie informuje pomocnika, aby *wykluczyć* flagę podkreślenia. Jeśli pominiesz tę linię, poprzednie podkreślenie pozostanie, co jest częstym źródłem błędów, gdy programiści przełączają tylko właściwość `Bold`. + +--- + +## Krok 3 – Zmień styl tekstu: pogrubienie, kursywa i więcej + +Możesz się zastanawiać: „Co jeśli muszę przełączyć także kursywę?” Ten sam obiekt działa dla dowolnej kombinacji. Poniżej znajduje się szybka macierz, którą możesz wykorzystać podczas kodowania. + +| Żądany styl | `Bold` | `Italic` | `Underline` | +|-------------|--------|----------|-------------| +| **Tylko pogrubienie** | true | false | false | +| *Tylko kursywa* | false | true | false | +| **Pogrubienie + Kursywa** | true | true | false | +| **Pogrubienie + Podkreślenie** | true | false | true | + +Po prostu ustaw potrzebne właściwości i wywołaj `ToFont`. Pomocnik wykona ciężką pracę za Ciebie, więc możesz skupić się na logice UI. + +--- + +## Pełny przykład – ustaw pogrubiony tekst programowo + +Poniżej znajduje się **complete, runnable WinForms** przykład, który demonstruje wszystko, co omówiliśmy. Wklej go do nowego projektu WinForms w stylu konsoli i naciśnij **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Oczekiwany wynik + +Po uruchomieniu programu pojawi się okno z tekstem **„Hello, world!”** wyświetlonym **pogrubionym**, **niekursywą** i **bez podkreślenia**. To wizualne potwierdzenie mówi, że logika **apply font style** działała perfekcyjnie. + +--- + +## Profesjonalne wskazówki i przypadki brzegowe + +- **Dynamic updates:** Jeśli musisz zmienić styl po wyświetleniu formularza (np. w odpowiedzi na zaznaczenie checkboxa), po prostu odtwórz instancję `WebFontStyle` lub zmodyfikuj jej właściwości i ponownie przypisz `lbl.Font`. UI aktualizuje się natychmiast. +- **High‑DPI considerations:** Gdy zamieniasz obiekt `Font`, Windows automatycznie skaluje go w zależności od bieżącego DPI. Nie potrzebny dodatkowy kod, chyba że ręcznie obsługujesz skalowanie. +- **WPF equivalent:** W WPF powinieneś powiązać `FontWeight`, `FontStyle` i `TextDecorations` zamiast wymieniać obiekt `Font`. Ta sama logiczna separacja ma zastosowanie — trzymaj logikę stylu poza warstwą widoku. +- **Avoiding memory leaks:** Ponowne przypisanie `Label.Font` tworzy nowy obiekt `Font`. Usuń (dispose) poprzedni, jeśli często wymieniasz style: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Podsumowanie + +Teraz wiesz, jak **apply font style** na dowolnym kontrolce .NET, **remove underline from text**, i **change text style** w locie — wszystko przy zachowaniu czystego i wielokrotnego użycia kodu. Mały pomocnik `WebFontStyle` zamienia garść flag boolowskich w solidny, testowalny komponent, a pełny przykład dowodzi, że możesz **set bold text programmatically** w zaledwie kilku linijkach. + +Co dalej? Spróbuj połączyć to podejście z ustawieniami sterowanymi przez użytkownika lub poeksperymentuj z innymi flagami `FontStyle`, takimi jak `Strikeout`. Możesz nawet udostępnić mały panel UI, który pozwoli nietechnicznym użytkownikom wybierać pogrubienie, kursywę lub podkreślenie w czasie działania — bez konieczności rekompilacji. + +Jeśli uznałeś ten **text formatting tutorial** za pomocny, zostaw komentarz lub podziel się własnymi wariacjami. Szczęśliwego kodowania i niech Twój UI zawsze wygląda dokładnie tak, jak zamierzałeś! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/polish/net/html-extensions-and-conversions/_index.md index 5b553b002..0b39c708c 100644 --- a/html/polish/net/html-extensions-and-conversions/_index.md +++ b/html/polish/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Dowiedz się, jak stworzyć dokument HTML z formatowanym tekstem i wyeksportowa Zapisz dokument HTML jako archiwum ZIP w C# przy użyciu Aspose.HTML – kompletny przewodnik krok po kroku. ### [Zapisz HTML do ZIP w C# – Kompletny przykład w pamięci](./save-html-to-zip-in-c-complete-in-memory-example/) Zapisz dokument HTML do archiwum ZIP w pamięci przy użyciu Aspose.HTML w C#. +### [Jak spakować HTML w C# – przewodnik po niestandardowym obsługiwaniu zasobów](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Dowiedz się, jak spakować plik HTML do archiwum ZIP w C# przy użyciu niestandardowego obsługiwacza zasobów w Aspose.HTML. ## Wniosek diff --git a/html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..4794625bf --- /dev/null +++ b/html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Naucz się kompresować HTML w C# przy użyciu własnego obsługiwacza zasobów + – krok po kroku przewodnik, jak zapisać HTML jako zip, konwertować HTML na zip i + tworzyć zip z HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: pl +og_description: 'Jak spakować HTML w C# – wyjaśnienie: użyj własnego obsługiwacza + zasobów, aby zapisać HTML jako zip, konwertuj HTML na zip i twórz zip z HTML w kilka + minut.' +og_title: jak spakować HTML w C# – Przewodnik po niestandardowym obsługiwaniu zasobów +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: jak spakować HTML w C# – przewodnik po niestandardowym obsługiwaniu zasobów +url: /pl/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# jak spakować html w C# – przewodnik po własnym obsługiwaniu zasobów + +Zastanawiałeś się kiedyś, **jak spakować html** bezpośrednio z kodu C#, nie zapisując najpierw plików na dysku? Nie jesteś sam. Wielu programistów napotyka problem, gdy muszą spakować stronę HTML wraz z jej CSS, obrazkami i czcionkami do dystrybucji offline, i kończą pisząc ad‑hocowy kod operujący na systemie plików, który szybko staje się koszmarem utrzymaniowym. + +W tym samouczku rozwiążemy ten problem, pokazując czyste, wielokrotnego użytku podejście, które **zapisuje HTML jako archiwum ZIP** przy użyciu `ResourceHandler` z Aspose.HTML. Poruszymy także temat **konwersji HTML do ZIP**, a nawet pokażemy wzorzec, który możesz ponownie wykorzystać, aby **tworzyć ZIP z HTML** w dowolnym projekcie .NET. Bez zewnętrznych skryptów, bez folderów tymczasowych — czysty C#. + +Po zakończeniu tego przewodnika będziesz mieć gotowy do uruchomienia przykład, który generuje `result.zip` zawierający wszystkie powiązane zasoby, oraz kilka praktycznych wskazówek, które możesz zastosować w własnych projektach. + +## Wymagania wstępne + +- .NET 6+ (kod działa również na .NET Framework 4.7.2, ale zalecamy najnowszy SDK) +- Pakiet NuGet Aspose.HTML for .NET (`Aspose.HTML`) – zainstaluj poleceniem `dotnet add package Aspose.HTML` +- Podstawowa znajomość strumieni oraz przestrzeni nazw `System.IO.Compression` +- IDE lub edytor według własnego wyboru (Visual Studio, VS Code, Rider…) + +Jeśli masz już te elementy, świetnie — przejdźmy od razu do kodu. Jeśli nie, jedynym dodatkowym krokiem jest jednowierszowa instalacja NuGet; wszystko inne jest zawarte w samym przykładzie. + +## Krok 1: Utwórz prosty dokument HTML w pamięci + +Najpierw potrzebujemy obiektu `HTMLDocument`, który reprezentuje stronę, którą chcemy spakować. W rzeczywistym scenariuszu możesz wczytać go z URL lub pliku, ale dla przejrzystości zbudujemy mały dokument bezpośrednio w kodzie. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Dlaczego to ważne:** +> Trzymając dokument w pamięci, unikamy pośredniego zapisu plików, co przyspiesza późniejszy krok **convert html to zip** i zapewnia bezpieczeństwo wątkowe. + +## Krok 2: Przygotuj strumień ZIP w pamięci + +Zamiast zapisywać tymczasowy plik `.zip` na dysku, użyjemy `MemoryStream`. Dzięki temu wszystko pozostaje w RAM, co jest idealne dla usług webowych lub zadań w tle, które muszą zwrócić archiwum bezpośrednio klientowi. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Wskazówka:** Instrukcja `using` zapewnia automatyczne zwolnienie strumienia, zapobiegając wyciekom pamięci. + +## Krok 3: Zaimplementuj własny ResourceHandler + +Aspose.HTML wywołuje `ResourceHandler` dla każdego zewnętrznego zasobu, który znajdzie (pliki CSS, obrazy, czcionki itp.). Dziedzicząc po `ResourceHandler`, możemy dokładnie określić, gdzie każdy zasób trafi — w naszym przypadku jako wpis w archiwum ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Dlaczego własny handler? + +- **Kontrola nad nazwami** – sam decydujesz, jak każdy plik pojawi się w archiwum. +- **Brak plików tymczasowych** – handler zapisuje bezpośrednio do pamięciowego ZIP. +- **Wielokrotne użycie** – możesz wkleić tę klasę do dowolnego projektu, który potrzebuje **save html as zip**. + +## Krok 4: Zapisz dokument HTML przy użyciu handlera + +Teraz łączymy wszystkie elementy. Metoda `Save` wywoła `HandleResource` dla każdego powiązanego zasobu, a handler przekaże te bajty do wcześniej utworzonego archiwum ZIP. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Co się dzieje „pod maską”?** +> Aspose analizuje HTML, wykrywa odwołanie ``, pyta handler o strumień, a handler tworzy wpis `logo.png` w ZIP. Ten sam proces powtarza się dla CSS, czcionek i innych zewnętrznych zasobów. + +## Krok 5: Zapisz archiwum ZIP na dysku (lub zwróć je) + +Na koniec zapisujemy pamięciowe archiwum do pliku. W API webowym możesz zamiast tego zwrócić `zipMemoryStream.ToArray()` jako tablicę bajtów. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Oczekiwany rezultat + +Otwórz `result.zip` i powinieneś zobaczyć: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Jeśli otworzyłeś archiwum w eksploratorze plików, zauważysz, że plik HTML jest zapisany jako `resource.bin`, ponieważ nie nadaliśmy mu przyjaznej nazwy. Możesz to łatwo poprawić, sprawdzając `resourceInfo.ContentType` i przypisując rozszerzenie `.html`, gdy jest to odpowiednie. + +## Pełny działający przykład + +Poniżej znajduje się kompletny, gotowy do skopiowania program, który łączy wszystkie powyższe kroki. Uruchom go jako aplikację konsolową, a otrzymasz gotowe do udostępnienia archiwum ZIP. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Uruchomienie tego kodu** wygeneruje `result.zip` w katalogu roboczym programu. Otwórz go, a znajdziesz `index.html` (naszą oryginalną stronę) oraz `logo.png`, jeśli ten obraz istniał na dysku lub został pobrany z URL. + +## Typowe warianty i przypadki brzegowe + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/portuguese/net/generate-jpg-and-png-images/_index.md index 25a4d8da7..efb901f58 100644 --- a/html/portuguese/net/generate-jpg-and-png-images/_index.md +++ b/html/portuguese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aprenda a usar Aspose.HTML para .NET para manipular documentos HTML, converter H Aprenda a ativar antialiasing ao converter documentos DOCX em imagens PNG ou JPG usando Aspose.HTML para .NET. ### [Converter docx para png – criar arquivo zip em C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Aprenda a converter documentos DOCX em imagens PNG e compactá-los em um arquivo ZIP usando C# e Aspose.HTML. +### [Criar PNG a partir de HTML – Guia passo a passo para desenvolvedores C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Aprenda a criar imagens PNG a partir de HTML usando Aspose.HTML para .NET em um guia passo a passo para desenvolvedores C#. ## Conclusão diff --git a/html/portuguese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/portuguese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..150068b78 --- /dev/null +++ b/html/portuguese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Crie PNG a partir de HTML rapidamente com Aspose.HTML. Aprenda como renderizar + HTML para PNG, definir o tamanho da tela, adicionar cor de fundo e salvar a imagem + renderizada em minutos. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: pt +og_description: Crie PNG a partir de HTML com Aspose.HTML. Este guia mostra como renderizar + HTML para PNG, definir o tamanho da tela, adicionar cor de fundo e salvar a imagem + renderizada. +og_title: Crie PNG a partir de HTML – Tutorial Completo de Renderização em C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Crie PNG a partir de HTML – Guia passo a passo para desenvolvedores C# +url: /pt/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar PNG a partir de HTML – Tutorial Completo de Renderização em C# + +Já precisou **criar PNG a partir de HTML** mas não sabia qual biblioteca ofereceria resultados nítidos e antialiasing? Você não está sozinho. Em muitos pipelines de web‑to‑image o maior ponto crítico é fazer o texto e os gráficos ficarem tão nítidos quanto no navegador. + +A boa notícia? Com Aspose.HTML você pode **renderizar HTML para PNG** em poucas linhas, controlar o tamanho da tela, adicionar uma cor de fundo sólida e, finalmente, **salvar a imagem renderizada** no disco — tudo sem abrir um navegador. Neste tutorial percorreremos todo o processo, explicaremos por que cada configuração importa e mostraremos um exemplo pronto‑para‑executar. + +## O que você vai aprender + +- Como carregar HTML a partir de uma string, arquivo ou URL +- Como configurar **definir tamanho da tela** e **adicionar cor de fundo** para uma saída previsível +- Habilitar antialiasing e hinting de texto sub‑pixel para títulos ultra‑nítidos +- Os passos exatos para **salvar a imagem renderizada** como um arquivo PNG +- Armadilhas comuns e ajustes opcionais para diferentes cenários + +Nenhuma experiência prévia com Aspose.HTML é necessária; basta uma configuração básica de C# e Visual Studio (ou sua IDE favorita). + +--- + +## Etapa 1: Instalar Aspose.HTML para .NET + +Antes de escrever qualquer código, certifique‑se de que o pacote NuGet Aspose.HTML está referenciado no seu projeto. + +```bash +dotnet add package Aspose.HTML +``` + +> **Dica profissional:** Use a versão estável mais recente (a partir de abril 2026, 23.9.0) para obter o motor de renderização mais novo e correções de bugs. + +--- + +## Etapa 2: Carregar a fonte HTML – Criar PNG a partir de HTML + +Você pode fornecer ao renderizador uma string inline, um arquivo local ou uma URL remota. Para esta demonstração usaremos uma simples string inline que contém um título com fonte personalizada. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Por que isso importa:** Carregar o HTML em um `HTMLDocument` dá ao motor controle total sobre a análise do DOM, cascata de CSS e cálculos de layout. Também isola a renderização de qualquer estado externo do navegador, garantindo resultados reproduzíveis. + +--- + +## Etapa 3: Configurar Opções de Renderização – Definir Tamanho da Tela e Adicionar Cor de Fundo + +A classe `ImageRenderingOptions` permite ajustar finamente a imagem de saída. Aqui habilitaremos antialiasing, definiremos um fundo branco e especificaremos explicitamente uma tela de **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Por que você pode mudar esses valores:** +- **Tamanho da tela:** Se precisar de uma miniatura, diminua as dimensões; para impressões de alta resolução, aumente-as. +- **Cor de fundo:** PNGs transparentes são possíveis, mas muitas ferramentas downstream (por exemplo, PowerPoint) esperam um fundo opaco. + +--- + +## Etapa 4: Renderizar e **Salvar a Imagem Renderizada** como PNG + +Agora o trabalho pesado acontece. O `ImageRenderer` consome o `HTMLDocument` e as opções que definimos, então grava um fluxo PNG no disco. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Ao executar o programa, você encontrará `result.png` na sua área de trabalho. Abra-o e deverá ver um título limpo, antialiasado, centralizado em uma tela branca. + +> **Saída esperada:** Um PNG 800 × 600 com fundo branco e o texto “Antialiased Heading” renderizado em Arial, tão suave quanto no Chrome. + +--- + +## Etapa 5: Verificar o Resultado – Checagens Rápidas + +1. **Existência do arquivo:** `File.Exists(outputPath)` deve retornar `true`. +2. **Dimensões:** Abra o PNG em qualquer visualizador de imagens; ele deve relatar 800 × 600 px. +3. **Qualidade visual:** Amplie para 200 % – as bordas do texto devem permanecer suaves, não serrilhadas. + +Se algo parecer errado, verifique se `UseAntialiasing` e `UseHinting` estão ambos definidos como `true`. Essas duas flags são o “segredo” para renderização de alta qualidade. + +--- + +## Variações Comuns & Casos de Borda + +| Cenário | O que Ajustar | Por quê | +|----------|----------------|-----| +| **Renderizar uma página remota** | Substitua `new HTMLDocument(htmlContent)` por `new HTMLDocument("https://example.com")` | Permite capturar sites ao vivo sem copiar o HTML manualmente. | +| **Fundo transparente** | Defina `BackgroundColor = Color.Transparent` e use `ImageFormat.Png` | Útil para sobrepor o PNG em outras imagens. | +| **Formato de imagem diferente** | Altere `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG pode ser menor para conteúdo fotográfico, mas perde qualidade sem perdas. | +| **Tamanho de tela dinâmico** | Use `imgOptions.Width = htmlDoc.Body.ClientWidth;` após o layout | Faz a imagem combinar com a largura natural do conteúdo HTML. | +| **Saída em alta DPI** | Multiplique `Width` e `Height` por um fator de escala (ex.: 2) | Gera ativos prontos para retina em telas modernas. | + +--- + +## Exemplo Completo Funcional (Pronto para Copiar‑Colar) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Execute o programa (`dotnet run` ou pressione F5 no Visual Studio) e você terá um PNG perfeitamente renderizado pronto para uso em e‑mails, relatórios ou qualquer outro lugar que precise de uma imagem estática do HTML. + +--- + +## Perguntas Frequentes + +**P: Isso funciona com recursos CSS 3 como flexbox?** +R: Sim. Aspose.HTML suporta a maioria dos CSS modernos, incluindo flexbox, grid e media queries. Apenas assegure‑se de estar usando a versão mais recente da biblioteca. + +**P: E se meu HTML referenciar imagens externas?** +R: O renderizador segue URLs relativas com base no URI base do documento. Se você carregar HTML a partir de uma string, defina `doc.BaseUrl` para a pasta que contém os recursos. + +**P: Posso renderizar várias páginas em um único PNG?** +R: Não diretamente — cada chamada ao `ImageRenderer` produz uma única imagem raster. Para saída multipágina, renderize cada página separadamente e una‑as com uma biblioteca gráfica (por exemplo, ImageSharp). + +--- + +## Conclusão + +Agora você tem uma solução completa, de ponta a ponta, para **criar PNG a partir de HTML** usando Aspose.HTML. Ao configurar as opções de **render html to png** — como **definir tamanho da tela**, **adicionar cor de fundo** e habilitar antialiasing — você pode gerar imagens de qualidade profissional sem precisar de um navegador. + +A partir daqui, experimente DPI mais alto, fundos transparentes ou processamento em lote de dezenas de trechos HTML. O mesmo padrão se aplica seja você quem esteja construindo um serviço de miniaturas, um pipeline de geração de PDF ou uma ferramenta de pré‑visualização de sites estáticos. + +Boa renderização, e sinta‑se à vontade para deixar um comentário caso encontre algum obstáculo! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/portuguese/net/html-document-manipulation/_index.md index df151c49f..97fbcb85f 100644 --- a/html/portuguese/net/html-document-manipulation/_index.md +++ b/html/portuguese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aprenda a usar Aspose.HTML para .NET. Importe namespace, mescle HTML com XML e a Desbloqueie o potencial do desenvolvimento web com Aspose.HTML para .NET. Crie, converta e manipule documentos HTML facilmente. ### [Criar HTML a partir de String em C# – Guia de Manipulador de Recurso Personalizado](./create-html-from-string-in-c-custom-resource-handler-guide/) Aprenda a gerar documentos HTML a partir de strings usando um manipulador de recurso personalizado em C# com Aspose.HTML. +### [Aplicar Estilo de Fonte Programaticamente – Guia Rápido em C#](./apply-font-style-programmatically-quick-c-guide/) +Aprenda a aplicar estilos de fonte programaticamente em C# usando Aspose.HTML. Guia rápido passo a passo. ## Conclusão diff --git a/html/portuguese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/portuguese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..3c69df1a7 --- /dev/null +++ b/html/portuguese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Aplique estilo de fonte programaticamente e aprenda como remover sublinhado + do texto, alterar o estilo do texto e definir texto em negrito programaticamente + em um tutorial conciso. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: pt +og_description: Aplique estilos de fonte programaticamente e descubra como remover + sublinhado do texto, alterar o estilo do texto e definir texto em negrito programaticamente + em um tutorial curto e prático. +og_title: Aplicar Estilo de Fonte Programaticamente – Guia Rápido de C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Aplicar Estilo de Fonte Programaticamente – Guia Rápido de C# +url: /pt/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aplicar Estilo de Fonte Programaticamente – Guia Rápido em C# + +Já precisou **aplicar estilo de fonte** a um elemento de UI mas não sabia por onde começar? Você não está sozinho—a maioria dos desenvolvedores encontra esse obstáculo ao primeiro contato com formatação de texto dinâmica. A boa notícia? Em poucos minutos você saberá exatamente como mudar a aparência de um label, remover sublinhado do texto e definir texto em negrito programaticamente sem precisar vasculhar documentação interminável. + +Neste **tutorial de formatação de texto** vamos percorrer um exemplo completo e executável, explicar o “porquê” de cada linha e inserir dicas práticas que você pode copiar‑colar em qualquer projeto WinForms ou WPF. Sem enrolação, só o que realmente funciona. + +--- + +## O Que Você Vai Aprender + +- Como **aplicar estilo de fonte** usando uma pequena classe auxiliar. +- Os passos precisos para **remover sublinhado do texto** mantendo os demais estilos intactos. +- Maneiras de **alterar estilo de texto** (negrito, itálico, sublinhado) em tempo real. +- Um trecho completo, pronto para copiar, que **define texto em negrito programaticamente**. +- Armadilhas comuns e tratamento de casos de borda para que você não seja surpreendido depois. + +**Pré‑requisitos:** .NET 6+ (ou qualquer versão recente do .NET Framework), conhecimento básico de C# e uma IDE de sua escolha (Visual Studio, Rider ou VS Code). Só isso—não são necessários pacotes NuGet extras. + +--- + +## Etapa 1 – Aplicar Estilo de Fonte ao Seu Controle + +O núcleo de qualquer operação de **aplicar estilo de fonte** é um enum `FontStyle` combinado com um objeto `Font`. Para manter o código organizado, vamos envolver a lógica do enum dentro de uma pequena classe `WebFontStyle`. Essa classe espelha as propriedades que você viu no snippet original (`Bold`, `Italic`, `Underline`) e constrói um valor `FontStyle` que pode ser passado para `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Por que isso importa:** +Ao isolar a lógica de construção de flags, você evita espalhar operações bitwise `|` por todo o código da UI. Fica mais fácil de ler, de testar e—o mais importante—torna a intenção de **aplicar estilo de fonte** cristalina. + +--- + +## Etapa 2 – Remover Sublinhado do Texto (e Manter Outros Estilos Intactos) + +Suponha que você tenha herdado um label que já está sublinhado, mas o design pede texto em negrito simples. Você não quer perder o negrito ao remover o sublinhado. É aqui que a classe `WebFontStyle` brilha. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Ponto chave:** Definir `Underline = false` explicitamente indica ao helper para *excluir* a flag de sublinhado. Se você simplesmente omitir a linha, o sublinhado anterior permanecerá, o que é uma fonte comum de bugs quando desenvolvedores só alternam a propriedade `Bold`. + +--- + +## Etapa 3 – Alterar Estilo de Texto: Negrito, Itálico e Mais + +Você pode se perguntar: “E se eu precisar alternar itálico também?” O mesmo objeto funciona para qualquer combinação. Abaixo está uma matriz rápida que você pode consultar enquanto codifica. + +| Estilo Desejado | `Bold` | `Italic` | `Underline` | +|-----------------|--------|----------|-------------| +| **Negrito apenas** | true | false | false | +| *Itálico apenas* | false | true | false | +| **Negrito + Itálico** | true | true | false | +| **Negrito + Sublinhado** | true | false | true | + +Basta definir as propriedades que precisar e chamar `ToFont`. O helper faz o trabalho pesado para você, permitindo que foque na lógica da UI. + +--- + +## Exemplo Completo – Definir Texto em Negrito Programaticamente + +A seguir, um exemplo **completo e executável em WinForms** que demonstra tudo o que foi abordado. Cole-o em um novo projeto WinForms estilo console e pressione **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Resultado Esperado + +Ao executar o programa, uma janela aparecerá com o texto **“Hello, world!”** renderizado **em negrito**, **não itálico**, e **sem sublinhado**. Essa confirmação visual indica que a lógica de **aplicar estilo de fonte** funcionou perfeitamente. + +--- + +## Dicas Profissionais & Casos de Borda + +- **Atualizações dinâmicas:** Se precisar mudar o estilo após o formulário ser exibido (por exemplo, em resposta a um checkbox), basta recriar a instância `WebFontStyle` ou modificar suas propriedades e reatribuir `lbl.Font`. A UI é atualizada instantaneamente. +- **Considerações de High‑DPI:** Quando você substitui um objeto `Font`, o Windows o escala automaticamente com base no DPI atual. Não é necessário código extra, a menos que você esteja lidando manualmente com o escalonamento. +- **Equivalente em WPF:** No WPF você faria binding de `FontWeight`, `FontStyle` e `TextDecorations` ao invés de trocar um objeto `Font`. A mesma separação lógica se aplica—mantenha a lógica de estilo fora da camada de visualização. +- **Evitando vazamentos de memória:** Reatribuir `Label.Font` cria um novo objeto `Font`. Descarte o antigo se estiver trocando estilos com frequência: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Conclusão + +Agora você sabe como **aplicar estilo de fonte** a qualquer controle .NET, **remover sublinhado do texto** e **alterar estilo de texto** em tempo real—tudo mantendo seu código limpo e reutilizável. O pequeno helper `WebFontStyle` transforma alguns flags booleanos em um componente sólido e testável, e o exemplo completo prova que você pode **definir texto em negrito programaticamente** em apenas algumas linhas. + +Qual o próximo passo? Experimente combinar essa abordagem com configurações controladas pelo usuário, ou teste outras flags de `FontStyle` como `Strikeout`. Você pode até expor um pequeno painel de UI que permita a usuários não técnicos escolher negrito, itálico ou sublinhado em tempo de execução—sem necessidade de recompilação. + +Se este **tutorial de formatação de texto** foi útil, deixe um comentário ou compartilhe suas próprias variações. Boa codificação, e que sua UI esteja sempre exatamente como você imaginou! + +--- + +![Captura de tela mostrando como aplicar estilo de fonte a um label em C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/portuguese/net/html-extensions-and-conversions/_index.md index 8971d46a5..f7c570b8b 100644 --- a/html/portuguese/net/html-extensions-and-conversions/_index.md +++ b/html/portuguese/net/html-extensions-and-conversions/_index.md @@ -77,6 +77,8 @@ Aprenda a salvar documentos HTML em arquivos ZIP usando Aspose.HTML para .NET co Aprenda a criar um arquivo ZIP contendo arquivos HTML usando Aspose.HTML para .NET em C#. ### [Salvar HTML em ZIP em C# – Exemplo Completo em Memória](./save-html-to-zip-in-c-complete-in-memory-example/) Aprenda a salvar arquivos HTML em um arquivo ZIP usando C# com um exemplo completo totalmente em memória. +### [Como compactar HTML em C# – guia de manipulador de recursos personalizado](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Aprenda a usar um manipulador de recursos personalizado para compactar HTML em arquivos ZIP com C# e Aspose.HTML. ## Conclusão diff --git a/html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..28c2c375c --- /dev/null +++ b/html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Aprenda a compactar HTML em C# usando um manipulador de recursos personalizado + – guia passo a passo para salvar HTML como zip, converter HTML em zip e criar zip + a partir de HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: pt +og_description: 'como compactar html em C# explicado: use um manipulador de recursos + personalizado para salvar html como zip, converta html para zip e crie zip a partir + de html em minutos.' +og_title: como compactar HTML em C# – Guia do Manipulador de Recursos Personalizado +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: como compactar html em C# – guia de manipulador de recursos personalizado +url: /pt/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# como compactar html em C# – guia de manipulador de recursos personalizado + +Já se perguntou **como compactar html** diretamente do seu código C# sem precisar gravar arquivos no disco primeiro? Você não está sozinho. Muitos desenvolvedores se deparam com um obstáculo quando precisam empacotar uma página HTML junto com seu CSS, imagens e fontes para distribuição offline, e acabam escrevendo código ad‑hoc de sistema de arquivos que rapidamente se torna um pesadelo de manutenção. + +Neste tutorial vamos resolver esse problema mostrando uma abordagem limpa e reutilizável que **salva HTML como um arquivo ZIP** usando o `ResourceHandler` do Aspose.HTML. Também abordaremos como **converter HTML para ZIP**, e até demonstraremos um padrão que você pode reutilizar para **criar ZIP a partir de HTML** em qualquer projeto .NET. Sem scripts externos, sem pastas temporárias — apenas C# puro. + +Ao final do guia você terá um exemplo pronto‑para‑executar que produz um `result.zip` contendo todos os recursos vinculados, além de algumas dicas práticas que você pode aplicar nos seus próprios projetos. + +## Pré‑requisitos + +- .NET 6+ (o código também funciona no .NET Framework 4.7.2, mas recomendamos o SDK mais recente) +- Pacote NuGet Aspose.HTML for .NET (`Aspose.HTML`) – instale via `dotnet add package Aspose.HTML` +- Familiaridade básica com streams e o namespace `System.IO.Compression` +- Uma IDE ou editor de sua escolha (Visual Studio, VS Code, Rider…) + +Se você já tem esses itens configurados, ótimo — vamos direto ao código. Caso contrário, o único passo extra é uma linha de instalação do NuGet; todo o resto está contido no exemplo. + +## Etapa 1: Criar um Documento HTML Simples na Memória + +Primeiro precisamos de um objeto `HTMLDocument` que represente a página que queremos compactar. Em um cenário real você poderia carregá‑lo de uma URL ou de um arquivo, mas para clareza vamos construir um documento pequeno inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Por que isso importa:** +> Ao manter o documento na memória evitamos qualquer I/O de arquivo intermediário, o que torna a etapa de **converter html para zip** rápida e segura para threads. + +## Etapa 2: Preparar um Stream ZIP na Memória + +Em vez de gravar um arquivo `.zip` temporário no disco, usaremos um `MemoryStream`. Isso mantém tudo em RAM, ideal para serviços web ou jobs em background que precisam devolver o arquivo diretamente ao cliente. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Dica:** A instrução `using` garante que o stream seja descartado automaticamente, evitando vazamentos de memória. + +## Etapa 3: Implementar um ResourceHandler Personalizado + +O Aspose.HTML chama um `ResourceHandler` para cada recurso externo que ele descobre (arquivos CSS, imagens, fontes, etc.). Ao estender `ResourceHandler` podemos decidir exatamente onde cada recurso será colocado — no nosso caso, como uma entrada dentro do arquivo ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Por que um Manipulador Personalizado? + +- **Controle sobre a nomeação** – você decide como cada arquivo aparecerá no arquivo. +- **Sem arquivos temporários** – o manipulador grava diretamente no ZIP em memória. +- **Reutilização** – você pode inserir esta classe em qualquer projeto que precise **salvar html como zip**. + +## Etapa 4: Salvar o Documento HTML Usando o Manipulador + +Agora juntamos tudo. O método `Save` invocará `HandleResource` para cada recurso vinculado, e o manipulador enviará esses bytes para o arquivo ZIP que criamos anteriormente. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **O que acontece nos bastidores?** +> O Aspose analisa o HTML, descobre a referência ``, solicita ao manipulador um stream, e o manipulador cria uma entrada `logo.png` dentro do ZIP. O mesmo fluxo se repete para CSS, fontes ou qualquer outro recurso externo. + +## Etapa 5: Persistir o Arquivo ZIP no Disco (ou Retorná‑lo) + +Por fim gravamos o arquivo ZIP em memória em um arquivo. Em uma API web você poderia, ao invés disso, retornar `zipMemoryStream.ToArray()` como um array de bytes. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Resultado Esperado + +Abra `result.zip` e você deverá ver: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Se você abrir o arquivo em um explorador verá que o arquivo HTML está armazenado como `resource.bin` porque não atribuímos um nome amigável. Você pode melhorar isso facilmente verificando `resourceInfo.ContentType` e atribuindo a extensão `.html` quando apropriado. + +## Exemplo Completo Funcional + +Abaixo está o programa completo, pronto para copiar e colar, que incorpora todas as etapas acima. Execute‑o a partir de um aplicativo console e você obterá um arquivo ZIP pronto‑para‑compartilhar. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Executar este código** gerará `result.zip` no diretório de trabalho do programa. Abra‑o e você encontrará `index.html` (nossa página original) mais `logo.png` caso essa imagem exista no disco ou tenha sido obtida de uma URL. + +## Variações Comuns & Casos de Borda + +| Cenário + +{{< /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/generate-jpg-and-png-images/_index.md b/html/russian/net/generate-jpg-and-png-images/_index.md index 74f005949..425d6b95c 100644 --- a/html/russian/net/generate-jpg-and-png-images/_index.md +++ b/html/russian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML для .NET предлагает простой метод прео Узнайте, как включить сглаживание при преобразовании DOCX в PNG или JPG с помощью Aspose.HTML для .NET. ### [Конвертация DOCX в PNG – создание ZIP-архива на C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) Узнайте, как преобразовать файлы DOCX в PNG и упаковать их в ZIP-архив с помощью C# и Aspose.HTML. +### [Создание PNG из HTML – пошаговое руководство для разработчиков C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Подробное руководство по конвертации HTML в PNG с использованием Aspose.HTML для C#. ## Заключение diff --git a/html/russian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/russian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..f685628c9 --- /dev/null +++ b/html/russian/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Создавайте PNG из HTML быстро с Aspose.HTML. Узнайте, как преобразовать + HTML в PNG, задать размер холста, добавить цвет фона и сохранить отрендеренное изображение + за считанные минуты. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: ru +og_description: Создайте PNG из HTML с помощью Aspose.HTML. Это руководство показывает, + как отобразить HTML в PNG, установить размер холста, добавить цвет фона и сохранить + полученное изображение. +og_title: Создание PNG из HTML – Полный учебник по рендерингу на C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Создание PNG из HTML – пошаговое руководство для разработчиков C# +url: /ru/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание PNG из HTML – Полный учебник по рендерингу на C# + +Когда‑то вам нужно **создать PNG из HTML**, но вы не знали, какая библиотека даст чёткие, сглаженные результаты? Вы не одиноки. Во многих конвейерах «web‑to‑image» самая большая проблема – заставить текст и графику выглядеть так же остро, как в браузере. + +Хорошая новость? С Aspose.HTML вы можете **рендерить HTML в PNG** в паре строк кода, задать размер холста, добавить сплошной цвет фона и, наконец, **сохранить отрендеренное изображение** на диск — всё без обращения к браузеру. В этом руководстве мы пройдём весь процесс, объясним, почему важна каждая настройка, и покажем готовый к запуску пример. + +## Что вы узнаете + +- Как загрузить HTML из строки, файла или URL +- Как настроить **установку размера холста** и **добавление цвета фона** для предсказуемого результата +- Включение сглаживания и субпиксельного хинтинга текста для кристально‑чётких заголовков +- Точные шаги **сохранения отрендеренного изображения** в файл PNG +- Распространённые подводные камни и дополнительные настройки для разных сценариев + +Опыт работы с Aspose.HTML не требуется; достаточно базовой настройки C# и Visual Studio (или вашей любимой IDE). + +--- + +## Шаг 1: Установите Aspose.HTML для .NET + +Прежде чем писать код, убедитесь, что пакет Aspose.HTML подключён к вашему проекту через NuGet. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Используйте последнюю стабильную версию (на апрель 2026 года — 23.9.0), чтобы получить новейший движок рендеринга и исправления ошибок. + +--- + +## Шаг 2: Загрузите источник HTML – Создание PNG из HTML + +Вы можете передать рендереру строку, локальный файл или удалённый URL. Для демонстрации мы используем простую встроенную строку, содержащую заголовок с пользовательским шрифтом. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Почему это важно:** Загрузка HTML в `HTMLDocument` даёт движку полный контроль над разбором DOM, каскадом CSS и расчётами раскладки. Это также изолирует процесс рендеринга от любого внешнего состояния браузера, обеспечивая воспроизводимые результаты. + +--- + +## Шаг 3: Настройте параметры рендеринга – Установите размер холста и добавьте цвет фона + +Класс `ImageRenderingOptions` позволяет точно настроить итоговое изображение. Здесь мы включаем сглаживание, задаём белый фон и явно определяем холст **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Почему вы можете изменить эти значения:** +- **Размер холста:** Если нужен миниатюрный образ, уменьшите размеры; для печати высокого разрешения увеличьте их. +- **Цвет фона:** Прозрачные PNG возможны, но многие downstream‑инструменты (например, PowerPoint) ожидают непрозрачный фон. + +--- + +## Шаг 4: Рендеринг и **сохранение отрендеренного изображения** в PNG + +Теперь происходит основная работа. `ImageRenderer` принимает `HTMLDocument` и только что заданные параметры, затем записывает PNG‑поток на диск. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +При запуске программы вы найдёте `result.png` на рабочем столе. Откройте его — вы увидите чистый, сглаженный заголовок, центрированный на белом холсте. + +> **Ожидаемый результат:** PNG размером 800 × 600 px с белым фоном и текстом «Antialiased Heading», отрендеренным шрифтом Arial, выглядящим так же плавно, как в Chrome. + +--- + +## Шаг 5: Проверка результата – Быстрые проверки + +1. **Наличие файла:** `File.Exists(outputPath)` должно вернуть `true`. +2. **Размеры:** Откройте PNG в любом просмотрщике изображений; он должен показывать 800 × 600 px. +3. **Визуальное качество:** При увеличении до 200 % края текста должны оставаться гладкими, без зазубрин. + +Если что‑то выглядит неправильно, проверьте, что `UseAntialiasing` и `UseHinting` оба установлены в `true`. Эти два флага — секретный ингредиент для рендеринга высокого качества. + +--- + +## Распространённые варианты и граничные случаи + +| Сценарий | Что изменить | Почему | +|----------|--------------|--------| +| **Рендеринг удалённой веб‑страницы** | Заменить `new HTMLDocument(htmlContent)` на `new HTMLDocument("https://example.com")` | Позволяет захватывать живые сайты без копирования HTML вручную. | +| **Прозрачный фон** | Установить `BackgroundColor = Color.Transparent` и использовать `ImageFormat.Png` | Полезно для наложения PNG на другие графические элементы. | +| **Другой формат изображения** | Изменить `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG может быть меньше для фотоконтента, но теряет безупречное качество. | +| **Динамический размер холста** | Использовать `imgOptions.Width = htmlDoc.Body.ClientWidth;` после раскладки | Позволяет изображению соответствовать естественной ширине HTML‑контента. | +| **Вывод с высоким DPI** | Умножить `Width` и `Height` на коэффициент масштабирования (например, 2) | Генерирует изображения, готовые к Retina‑дисплеям. | + +--- + +## Полный рабочий пример (готов к копированию) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Запустите программу (`dotnet run` или нажмите F5 в Visual Studio) — и у вас будет идеально отрендеренный PNG, готовый к использованию в письмах, отчётах или любом другом месте, где нужен статический образ HTML. + +--- + +## Часто задаваемые вопросы + +**В: Работает ли это с CSS 3, например flexbox?** +О: Да. Aspose.HTML поддерживает большинство современных CSS, включая flexbox, grid и media queries. Просто убедитесь, что используете последнюю версию библиотеки. + +**В: Что делать, если мой HTML ссылается на внешние изображения?** +О: Рендерер следует относительным URL‑ам, основываясь на базовом URI документа. Если вы загружаете HTML из строки, задайте `doc.BaseUrl` в папку, где находятся ресурсы. + +**В: Можно ли отрендерить несколько страниц в один PNG?** +О: Не напрямую — каждый вызов `ImageRenderer` создаёт отдельное растровое изображение. Для многостраничного вывода отрендерьте каждую страницу отдельно и соедините их с помощью графической библиотеки (например, ImageSharp). + +--- + +## Заключение + +Теперь у вас есть надёжное сквозное решение для **создания PNG из HTML** с помощью Aspose.HTML. Настраивая параметры **render html to png** — такие как **set canvas size**, **add background color** и включение сглаживания, — вы можете генерировать профессиональные изображения без браузера. + +Дальше вы можете экспериментировать с более высоким DPI, прозрачными фонами или пакетной обработкой десятков HTML‑фрагментов. Тот же шаблон подходит как для сервиса создания миниатюр, конвейера генерации PDF, так и для инструмента предварительного просмотра статических сайтов. + +Удачного рендеринга, и не стесняйтесь оставлять комментарии, если столкнётесь с проблемами! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/html-document-manipulation/_index.md b/html/russian/net/html-document-manipulation/_index.md index cf442f62c..9466f0691 100644 --- a/html/russian/net/html-document-manipulation/_index.md +++ b/html/russian/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML для .NET выделяется своей простотой и м Раскройте потенциал веб-разработки с Aspose.HTML для .NET. Создавайте, конвертируйте и обрабатывайте HTML-документы легко. ### [Создание HTML из строки в C# – Руководство по пользовательскому обработчику ресурсов](./create-html-from-string-in-c-custom-resource-handler-guide/) Узнайте, как создавать HTML из строки в C# с помощью пользовательского обработчика ресурсов в Aspose.HTML. +### [Применение стиля шрифта программно – Быстрое руководство C#](./apply-font-style-programmatically-quick-c-guide/) +Узнайте, как программно изменить стиль шрифта в HTML с помощью Aspose.HTML для .NET в кратком руководстве на C#. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/russian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/russian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..03d97ae7f --- /dev/null +++ b/html/russian/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Применяйте стиль шрифта программно и узнайте, как удалить подчеркивание + из текста, изменить стиль текста и установить полужирный текст программно в кратком + руководстве. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: ru +og_description: Применяйте стиль шрифта программно и узнайте, как удалить подчеркивание + текста, изменить стиль текста и установить полужирный шрифт программно в коротком + практическом руководстве. +og_title: Применение стиля шрифта программно — Краткое руководство по C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Применение стиля шрифта программно — Краткое руководство по C# +url: /ru/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Применение стиля шрифта программно – Краткое руководство C# + +Когда‑то вам нужно было **применить стиль шрифта** к элементу UI, но вы не знали, с чего начать? Вы не одиноки — большинство разработчиков сталкиваются с этим, когда впервые пробуют динамическое форматирование текста. Хорошая новость? Через несколько минут вы точно будете знать, как изменить внешний вид метки, убрать подчеркивание из текста и задать жирный шрифт программно, не копаясь в бесконечных документах. + +В этом **уроке по форматированию текста** мы пройдем полный, готовый к запуску пример, объясним «почему» каждой строки и добавим практические советы, которые можно скопировать‑вставить в любой проект WinForms или WPF. Без лишних слов, только то, что действительно работает. + +--- + +## Что вы узнаете + +- Как **применить стиль шрифта** с помощью небольшого вспомогательного класса. +- Точные шаги для **удаления подчеркивания из текста**, оставляя остальные стили нетронутыми. +- Способы **изменения стиля текста** (жирный, курсив, подчеркивание) «на лету». +- Полный, готовый к копированию фрагмент, который **задает жирный текст программно**. +- Распространённые подводные камни и обработка граничных случаев, чтобы вас не удивило позже. + +**Предварительные требования:** .NET 6+ (или любой современный .NET Framework), базовые знания C#, и IDE по вашему выбору (Visual Studio, Rider или VS Code). Всё — без дополнительных пакетов NuGet. + +--- + +## Шаг 1 – Применить стиль шрифта к вашему элементу управления + +Суть любой операции **apply font style** — это перечисление `FontStyle`, комбинируемое с объектом `Font`. Чтобы код оставался чистым, мы обернём логику перечисления в небольшой класс `WebFontStyle`. Этот класс отражает свойства, которые вы видели в оригинальном фрагменте (`Bold`, `Italic`, `Underline`), и формирует значение `FontStyle`, которое можно передать в `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Почему это важно:** +Изолируя логику построения флагов, вы избегаете разбросанных побитовых операций `|` по всему UI‑коду. Это проще читать, проще тестировать и — самое главное — делает намерение **apply font style** кристально ясным. + +--- + +## Шаг 2 – Удалить подчеркивание из текста (и сохранить остальные стили) + +Предположим, вы получили метку, которая уже подчёркнута, но дизайн требует обычного жирного текста. Вы не хотите терять жирность, удаляя подчеркивание. Здесь на помощь приходит класс `WebFontStyle`. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Ключевой момент:** Установка `Underline = false` явно сообщает помощнику *исключить* флаг подчеркивания. Если бы вы просто опустили эту строку, предыдущее подчеркивание осталось бы, что часто становится источником багов, когда разработчики меняют только свойство `Bold`. + +--- + +## Шаг 3 – Изменить стиль текста: жирный, курсив и прочее + +Вы можете задаться вопросом: «А что, если нужно переключить курсив тоже?» Тот же объект работает для любой комбинации. Ниже представлена быстрая таблица, к которой можно обращаться во время кодинга. + +| Требуемый стиль | `Bold` | `Italic` | `Underline` | +|-----------------|--------|----------|-------------| +| **Только жирный** | true | false | false | +| *Только курсив* | false | true | false | +| **Жирный + Курсив** | true | true | false | +| **Жирный + Подчёркнутый** | true | false | true | + +Просто задайте нужные свойства и вызовите `ToFont`. Помощник выполнит всю тяжёлую работу за вас, позволяя сосредоточиться на логике UI. + +--- + +## Полный пример – Задать жирный текст программно + +Ниже представлен **полный, готовый к запуску пример WinForms**, демонстрирующий всё, что мы рассмотрели. Вставьте его в новый проект WinForms в стиле console‑style и нажмите **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Ожидаемый результат + +При запуске программы появится окно с текстом **«Hello, world!»**, отображённым **жирным**, **не курсивом** и **без подчеркивания**. Этот визуальный результат подтверждает, что логика **apply font style** отработала безупречно. + +--- + +## Профессиональные советы и граничные случаи + +- **Динамические обновления:** Если нужно изменить стиль после отображения формы (например, в ответ на чекбокс), просто создайте новый экземпляр `WebFontStyle` или измените его свойства и переустановите `lbl.Font`. UI обновится мгновенно. +- **Учёт High‑DPI:** При замене объекта `Font` Windows автоматически масштабирует его в соответствии с текущим DPI. Дополнительный код не требуется, если только вы не обрабатываете масштабирование вручную. +- **Эквивалент в WPF:** В WPF вы будете привязывать `FontWeight`, `FontStyle` и `TextDecorations` вместо замены объекта `Font`. Та же логическая разъединённость применима — держите логику стилей вне уровня представления. +- **Избежание утечек памяти:** Переустановка `Label.Font` создаёт новый объект `Font`. При частой смене стилей освобождайте старый: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Заключение + +Теперь вы знаете, как **apply font style** к любому элементу .NET, **удалять подчеркивание из текста** и **изменять стиль текста** «на лету», сохраняя код чистым и переиспользуемым. Маленький помощник `WebFontStyle` превращает несколько булевых флагов в надёжный, тестируемый компонент, а полный пример доказывает, что вы можете **задать жирный текст программно** всего в несколько строк. + +Что дальше? Попробуйте сочетать этот подход с пользовательскими настройками или поэкспериментируйте с другими флагами `FontStyle`, такими как `Strikeout`. Вы даже можете создать небольшую панель UI, позволяющую нетехническим пользователям выбирать жирный, курсив или подчеркивание во время выполнения — без необходимости перекомпиляции. + +Если этот **урок по форматированию текста** оказался полезным, оставьте комментарий или поделитесь своими вариантами. Приятного кодинга, и пусть ваш UI всегда выглядит именно так, как вы задумали! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/russian/net/html-extensions-and-conversions/_index.md index 00354e673..8ae337947 100644 --- a/html/russian/net/html-extensions-and-conversions/_index.md +++ b/html/russian/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Aspose.HTML для .NET — это не просто библиотека; эт Узнайте, как сохранить HTML‑страницу в архив ZIP с помощью Aspose.HTML для .NET, используя C# в полном пошаговом руководстве. ### [Сохраните HTML в ZIP в C# – Полный пример в памяти](./save-html-to-zip-in-c-complete-in-memory-example/) Сохраните HTML в архив ZIP полностью в памяти с помощью Aspose.HTML для .NET, используя C#. +### [Как заархивировать HTML в C# – руководство по пользовательскому обработчику ресурсов](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Узнайте, как использовать пользовательский обработчик ресурсов для создания ZIP‑архивов HTML‑файлов в C# с Aspose.HTML. ## Заключение diff --git a/html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..090166de2 --- /dev/null +++ b/html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-04-23 +description: Узнайте, как упаковать HTML в ZIP в C# с помощью пользовательского обработчика + ресурсов — пошаговое руководство по сохранению HTML в виде ZIP, конвертации HTML + в ZIP и созданию ZIP из HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: ru +og_description: 'как заархивировать html в C# объяснено: используйте пользовательский + обработчик ресурсов, чтобы сохранить html в виде zip, преобразуйте html в zip и + создайте zip из html за несколько минут.' +og_title: Как заархивировать HTML в C# – Руководство по пользовательскому обработчику + ресурсов +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: Как сжать HTML в C# – руководство по пользовательскому обработчику ресурсов +url: /ru/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# как упаковать html в zip в C# – руководство по пользовательскому обработчику ресурсов + +Когда‑то задавались вопросом **как упаковать html** напрямую из кода C# без предварительного сохранения файлов на диск? Вы не одиноки. Многие разработчики сталкиваются с проблемой, когда нужно собрать HTML‑страницу вместе с её CSS, изображениями и шрифтами для офлайн‑распространения, и в итоге пишут ad‑hoc код работы с файловой системой, который быстро превращается в кошмар по обслуживанию. + +В этом руководстве мы решим эту задачу, показав чистый, переиспользуемый подход, который **сохраняет HTML как ZIP‑архив** с помощью `ResourceHandler` из Aspose.HTML. Мы также коснёмся того, как **конвертировать HTML в ZIP**, и продемонстрируем шаблон, который можно использовать для **создания ZIP из HTML** в любом .NET‑проекте. Без внешних скриптов, без временных папок — только чистый C#. + +К концу руководства у вас будет готовый к запуску пример, который создаёт `result.zip`, содержащий каждый связанный ресурс, а также набор практических советов, которые вы сможете применить в своих проектах. + +## Prerequisites + +- .NET 6+ (код также работает на .NET Framework 4.7.2, но рекомендуется последняя версия SDK) +- NuGet‑пакет Aspose.HTML for .NET (`Aspose.HTML`) — установить через `dotnet add package Aspose.HTML` +- Базовое знакомство со стримами и пространством имён `System.IO.Compression` +- Любая IDE или редактор (Visual Studio, VS Code, Rider…) + +Если все эти компоненты уже у вас есть, отлично — сразу переходим к коду. Если нет, единственный дополнительный шаг — однострочная установка NuGet; всё остальное включено в пример. + +## Step 1: Create a Simple HTML Document in Memory + +First we need an `HTMLDocument` object that represents the page we want to zip. In a real‑world scenario you might load this from a URL or a file, but for clarity we’ll build a tiny document inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Why this matters:** +> By keeping the document in memory we avoid any intermediate file I/O, which makes the later **convert html to zip** step fast and thread‑safe. + +## Step 2: Prepare an In‑Memory ZIP Stream + +Instead of writing a temporary `.zip` file to disk, we’ll use a `MemoryStream`. This keeps everything in RAM, ideal for web services or background jobs that need to return the archive directly to a client. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** The `using` statement ensures the stream is disposed automatically, preventing memory leaks. + +## Step 3: Implement a Custom ResourceHandler + +Aspose.HTML calls a `ResourceHandler` for every external asset it discovers (CSS files, images, fonts, etc.). By subclassing `ResourceHandler` we can decide exactly where each resource ends up—in our case, as an entry inside the ZIP archive. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Why a Custom Handler? + +- **Control over naming** – you decide how each file appears in the archive. +- **No temporary files** – the handler writes straight into the in‑memory ZIP. +- **Reusability** – you can drop this class into any project that needs to **save html as zip**. + +## Step 4: Save the HTML Document Using the Handler + +Now we tie everything together. The `Save` method will invoke `HandleResource` for every linked asset, and the handler will stream those bytes into the ZIP archive we created earlier. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **What happens under the hood?** +> Aspose parses the HTML, discovers the `` reference, asks the handler for a stream, and the handler creates a `logo.png` entry inside the ZIP. The same flow repeats for CSS, fonts, or any other external resource. + +## Step 5: Persist the ZIP Archive to Disk (or Return It) + +Finally we write the in‑memory archive to a file. In a web API you could instead return `zipMemoryStream.ToArray()` as a byte array. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Expected Result + +Open `result.zip` and you should see: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +If you opened the archive in a file explorer you’d notice that the HTML file is stored as `resource.bin` because we didn’t give it a friendly name. You can easily improve that by checking `resourceInfo.ContentType` and assigning `.html` when appropriate. + +## Full Working Example + +Below is the complete, copy‑paste‑ready program that incorporates all the steps above. Run it from a console app, and you’ll get a ready‑to‑share ZIP file. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Running this code** will generate `result.zip` in the program’s working directory. Open it and you’ll find `index.html` (our original page) plus `logo.png` if that image existed on disk or was fetched from a URL. + +## Common Variations & Edge Cases + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/spanish/net/generate-jpg-and-png-images/_index.md index 4323c4591..839cb9a70 100644 --- a/html/spanish/net/generate-jpg-and-png-images/_index.md +++ b/html/spanish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aprenda a utilizar Aspose.HTML para .NET para manipular documentos HTML, convert Aprenda a activar el antialiasing al convertir documentos DOCX a imágenes PNG o JPG usando Aspose.HTML para .NET. ### [Convertir docx a PNG – crear archivo ZIP con C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Aprenda a convertir documentos DOCX a imágenes PNG y empaquetarlos en un archivo ZIP usando C#. +### [Crear PNG a partir de HTML – Guía paso a paso para desarrolladores C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Aprenda a generar archivos PNG desde HTML con una guía paso a paso para desarrolladores C# usando Aspose.HTML. ## Conclusión diff --git a/html/spanish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/spanish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..47df23918 --- /dev/null +++ b/html/spanish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Crea PNG a partir de HTML rápidamente con Aspose.HTML. Aprende cómo renderizar + HTML a PNG, establecer el tamaño del lienzo, agregar color de fondo y guardar la + imagen renderizada en minutos. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: es +og_description: Crear PNG a partir de HTML con Aspose.HTML. Esta guía muestra cómo + renderizar HTML a PNG, establecer el tamaño del lienzo, añadir color de fondo y + guardar la imagen renderizada. +og_title: Crear PNG a partir de HTML – Tutorial completo de renderizado en C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Crear PNG a partir de HTML – Guía paso a paso para desarrolladores de C# +url: /es/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear PNG a partir de HTML – Tutorial completo de renderizado en C# + +¿Alguna vez necesitaste **crear PNG a partir de HTML** pero no estabas seguro de qué biblioteca te daría resultados nítidos y antialiasing? No estás solo. En muchos flujos de trabajo web‑a‑imagen, el mayor dolor es lograr que el texto y los gráficos se vean tan nítidos como en el navegador. + +¿La buena noticia? Con Aspose.HTML puedes **renderizar HTML a PNG** en unas pocas líneas, controlar el tamaño del lienzo, añadir un color de fondo sólido y, finalmente, **guardar la imagen renderizada** en disco—todo sin tocar un navegador. En este tutorial recorreremos todo el proceso, explicaremos por qué cada configuración es importante y te mostraremos un ejemplo listo para ejecutar. + +## Lo que aprenderás + +- Cómo cargar HTML desde una cadena, archivo o URL +- Cómo configurar **set canvas size** y **add background color** para una salida predecible +- Habilitar antialiasing y sub‑pixel text hinting para encabezados ultra nítidos +- Los pasos exactos para **save rendered image** como archivo PNG +- Problemas comunes y ajustes opcionales para diferentes escenarios + +No se requiere experiencia previa con Aspose.HTML; solo una configuración básica de C# y Visual Studio (o tu IDE favorito). + +--- + +## Paso 1: Instalar Aspose.HTML para .NET + +Antes de escribir cualquier código, asegúrate de que el paquete NuGet de Aspose.HTML esté referenciado en tu proyecto. + +```bash +dotnet add package Aspose.HTML +``` + +> **Consejo profesional:** Usa la última versión estable (a partir de abril 2026, 23.9.0) para obtener el motor de renderizado más reciente y correcciones de errores. + +--- + +## Paso 2: Cargar la fuente HTML – Crear PNG a partir de HTML + +Puedes proporcionar al renderizador una cadena en línea, un archivo local o una URL remota. Para esta demostración usaremos una cadena simple en línea que contiene un encabezado con una fuente personalizada. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Por qué es importante:** Cargar HTML en un `HTMLDocument` le da al motor control total sobre el análisis del DOM, la cascada de CSS y los cálculos de diseño. También aísla el renderizado de cualquier estado externo del navegador, garantizando resultados reproducibles. + +--- + +## Paso 3: Configurar opciones de renderizado – Establecer tamaño del lienzo y añadir color de fondo + +La clase `ImageRenderingOptions` te permite afinar la imagen de salida. Aquí habilitaremos antialiasing, estableceremos un fondo blanco y definiremos explícitamente un lienzo de **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Por qué podrías cambiar estos valores:** +- **Tamaño del lienzo:** Si necesitas una miniatura, reduce las dimensiones; para impresiones de alta resolución, aumentálas. +- **Color de fondo:** Los PNG transparentes son posibles, pero muchas herramientas posteriores (p. ej., PowerPoint) esperan un fondo opaco. + +--- + +## Paso 4: Renderizar y **Save Rendered Image** como PNG + +Ahora ocurre el trabajo pesado. El `ImageRenderer` consume el `HTMLDocument` y las opciones que acabamos de definir, y luego escribe un flujo PNG en el disco. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Cuando ejecutes el programa, encontrarás `result.png` en tu escritorio. Ábrelo y deberías ver un encabezado limpio y antialiasado centrado en un lienzo blanco. + +> **Salida esperada:** Un PNG de 800 × 600 con fondo blanco y el texto “Antialiased Heading” renderizado en Arial, con la misma suavidad que en Chrome. + +--- + +## Paso 5: Verificar el resultado – Verificaciones rápidas + +1. **Existencia del archivo:** `File.Exists(outputPath)` debería devolver `true`. +2. **Dimensiones:** Abre el PNG en cualquier visor de imágenes; debería reportar 800 × 600 px. +3. **Calidad visual:** Acércate al 200 % – los bordes del texto deben permanecer suaves, no dentados. + +Si algo se ve incorrecto, verifica que `UseAntialiasing` y `UseHinting` estén ambos configurados en `true`. Esas dos banderas son la clave secreta para un renderizado de alta calidad. + +--- + +## Variaciones comunes y casos límite + +| Escenario | Qué ajustar | Por qué | +|----------|----------------|-----| +| **Renderizar una página web remota** | Reemplaza `new HTMLDocument(htmlContent)` con `new HTMLDocument("https://example.com")` | Permite capturar sitios en vivo sin copiar HTML manualmente. | +| **Fondo transparente** | Establece `BackgroundColor = Color.Transparent` y usa `ImageFormat.Png` | Útil para superponer el PNG sobre otros gráficos. | +| **Formato de imagen diferente** | Cambia `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG puede ser más pequeño para contenido fotográfico, pero pierde calidad sin pérdida. | +| **Tamaño de lienzo dinámico** | Usa `imgOptions.Width = htmlDoc.Body.ClientWidth;` después del layout | Permite que la imagen coincida con el ancho natural del contenido HTML. | +| **Salida de alta DPI** | Multiplica `Width` y `Height` por un factor de escala (p. ej., 2) | Genera recursos listos para retina en pantallas modernas. | + +--- + +## Ejemplo completo funcional (listo para copiar‑pegar) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Ejecuta el programa (`dotnet run` o presiona F5 en Visual Studio) y tendrás un PNG perfectamente renderizado listo para usar en correos electrónicos, informes o cualquier otro lugar donde necesites una imagen estática de HTML. + +--- + +## Preguntas frecuentes + +**Q: ¿Esto funciona con características de CSS 3 como flexbox?** +A: Sí. Aspose.HTML soporta la mayoría de CSS modernos, incluyendo flexbox, grid y media queries. Solo asegúrate de estar en la última versión de la biblioteca. + +**Q: ¿Qué pasa si mi HTML hace referencia a imágenes externas?** +A: El renderizador sigue URLs relativas basadas en la URI base del documento. Si cargas HTML desde una cadena, establece `doc.BaseUrl` a la carpeta que contiene los recursos. + +**Q: ¿Puedo renderizar múltiples páginas en un solo PNG?** +A: No directamente—cada llamada a `ImageRenderer` produce una sola imagen rasterizada. Para salida multipágina, renderiza cada página por separado y únelas con una biblioteca gráfica (p. ej., ImageSharp). + +--- + +## Conclusión + +Ahora tienes una solución sólida de extremo a extremo para **create PNG from HTML** usando Aspose.HTML. Configurando opciones de **render html to png**—como **set canvas size**, **add background color**, y habilitando antialiasing—puedes generar imágenes de calidad profesional sin un navegador. + +A partir de aquí puedes experimentar con DPI más alto, fondos transparentes o procesamiento por lotes de docenas de fragmentos HTML. El mismo patrón se aplica tanto si estás construyendo un servicio de miniaturas, una canalización de generación de PDF o una herramienta de vista previa de sitios estáticos. + +¡Feliz renderizado, y siéntete libre de dejar un comentario si encuentras algún problema! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/spanish/net/html-document-manipulation/_index.md index 84acbc5a9..1330f5b74 100644 --- a/html/spanish/net/html-document-manipulation/_index.md +++ b/html/spanish/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aprenda a utilizar Aspose.HTML para .NET. Importe espacios de nombres, combine H Descubra el potencial del desarrollo web con Aspose.HTML para .NET. Cree, convierta y manipule documentos HTML fácilmente. ### [Crear HTML a partir de una cadena en C# – Guía del controlador de recursos personalizado](./create-html-from-string-in-c-custom-resource-handler-guide/) Aprenda a generar contenido HTML a partir de una cadena en C# utilizando un controlador de recursos personalizado con Aspose.HTML. +### [Aplicar estilo de fuente programáticamente – Guía rápida de C#](./apply-font-style-programmatically-quick-c-guide/) +Aprenda a aplicar estilos de fuente a documentos HTML mediante código C# con Aspose.HTML. ## Conclusión diff --git a/html/spanish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/spanish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..7e0be8a70 --- /dev/null +++ b/html/spanish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Aplica estilos de fuente de forma programática y aprende a eliminar el + subrayado del texto, cambiar el estilo del texto y establecer texto en negrita de + forma programática en un tutorial conciso. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: es +og_description: Aplica estilos de fuente programáticamente y descubre cómo eliminar + el subrayado del texto, cambiar el estilo del texto y establecer texto en negrita + de forma programática en un tutorial corto y práctico. +og_title: Aplicar estilo de fuente programáticamente – Guía rápida de C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Aplicar estilo de fuente programáticamente – Guía rápida de C# +url: /es/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aplicar estilo de fuente programáticamente – Guía rápida de C# + +¿Alguna vez necesitaste **aplicar estilo de fuente** a un elemento de UI pero no sabías por dónde empezar? No eres el único—la mayoría de los desarrolladores se topan con ese obstáculo cuando se inician en el formato dinámico de texto. ¿La buena noticia? En solo unos minutos sabrás exactamente cómo cambiar la apariencia de una etiqueta, eliminar el subrayado del texto y establecer texto en negrita programáticamente sin buscar en interminables documentos. + +En este **tutorial de formato de texto** recorreremos un ejemplo completo y ejecutable, explicaremos el “por qué” detrás de cada línea y añadiremos consejos prácticos que puedes copiar‑pegar en cualquier proyecto WinForms o WPF. Sin rodeos, solo lo necesario para hacer el trabajo. + +--- + +## Lo que aprenderás + +- Cómo **aplicar estilo de fuente** usando una pequeña clase auxiliar. +- Los pasos precisos para **eliminar el subrayado del texto** manteniendo los demás estilos intactos. +- Formas de **cambiar el estilo de texto** (negrita, cursiva, subrayado) sobre la marcha. +- Un fragmento completo, listo para copiar, que **establece texto en negrita programáticamente**. +- Trampas comunes y manejo de casos límite para que no te sorprendan más adelante. + +**Requisitos previos:** .NET 6+ (o cualquier .NET Framework reciente), conocimientos básicos de C# y un IDE de tu elección (Visual Studio, Rider o VS Code). Eso es todo—no se requieren paquetes NuGet adicionales. + +--- + +## Paso 1 – Aplicar estilo de fuente a tu control + +El núcleo de cualquier operación de **aplicar estilo de fuente** es un enum `FontStyle` combinado con un objeto `Font`. Para mantener el código ordenado envolveremos la lógica del enum dentro de una pequeña clase `WebFontStyle`. Esta clase refleja las propiedades que viste en el fragmento original (`Bold`, `Italic`, `Underline`) y construye un valor `FontStyle` que puedes pasar a `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Por qué es importante:** +Al aislar la lógica de construcción de banderas, evitas esparcir operaciones bit a bit `|` por todo tu código de UI. Es más fácil de leer, más fácil de probar y—lo más importante—deja la intención de **aplicar estilo de fuente** perfectamente clara. + +--- + +## Paso 2 – Eliminar subrayado del texto (y mantener los demás estilos intactos) + +Supongamos que heredaste una etiqueta que ya está subrayada, pero el diseño requiere texto en negrita simple. No quieres perder la negrita al eliminar el subrayado. Aquí es donde la clase `WebFontStyle` brilla. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Punto clave:** Establecer `Underline = false` indica explícitamente al ayudante que *excluya* la bandera de subrayado. Si omites esa línea por completo, el subrayado anterior persistirá, lo cual es una fuente común de errores cuando los desarrolladores solo alternan la propiedad `Bold`. + +--- + +## Paso 3 – Cambiar estilo de texto: negrita, cursiva y más + +Podrías preguntarte, “¿Y si también necesito alternar la cursiva?” El mismo objeto funciona para cualquier combinación. A continuación tienes una matriz rápida que puedes consultar mientras codificas. + +| Estilo deseado | `Bold` | `Italic` | `Underline` | +|---------------|--------|----------|-------------| +| **Solo negrita** | true | false | false | +| *Solo cursiva* | false | true | false | +| **Negrita + Cursiva** | true | true | false | +| **Negrita + Subrayado** | true | false | true | + +Simplemente establece las propiedades que necesites y llama a `ToFont`. El ayudante hace el trabajo pesado por ti, para que puedas centrarte en la lógica de la UI. + +--- + +## Ejemplo completo – Establecer texto en negrita programáticamente + +A continuación tienes un ejemplo **completo y ejecutable de WinForms** que demuestra todo lo que hemos cubierto. Pégalo en un nuevo proyecto WinForms estilo consola y pulsa **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Resultado esperado + +Al ejecutar el programa, aparece una ventana con el texto **“Hello, world!”** renderizado en **negrita**, **no cursiva**, y **sin subrayado**. Esa confirmación visual te indica que la lógica de **aplicar estilo de fuente** funcionó perfectamente. + +--- + +## Consejos profesionales y casos límite + +- **Actualizaciones dinámicas:** Si necesitas cambiar el estilo después de que el formulario se muestre (p. ej., en respuesta a una casilla de verificación), simplemente recrea la instancia `WebFontStyle` o modifica sus propiedades y vuelve a asignar `lbl.Font`. La UI se actualiza al instante. +- **Consideraciones de alta DPI:** Cuando reemplazas un objeto `Font`, Windows lo escala automáticamente según la DPI actual. No se necesita código adicional a menos que manejes el escalado manualmente. +- **Equivalente en WPF:** En WPF enlazarías `FontWeight`, `FontStyle` y `TextDecorations` en lugar de intercambiar un objeto `Font`. La misma separación lógica se aplica—mantén la lógica de estilo fuera de la capa de vista. +- **Evitar fugas de memoria:** Reasignar `Label.Font` crea un nuevo objeto `Font`. Desecha el anterior si cambias estilos con frecuencia: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Conclusión + +Ahora sabes cómo **aplicar estilo de fuente** a cualquier control .NET, **eliminar el subrayado del texto** y **cambiar el estilo de texto** sobre la marcha—todo mientras mantienes tu código limpio y reutilizable. El pequeño ayudante `WebFontStyle` convierte un puñado de banderas booleanas en un componente sólido y testeable, y el ejemplo completo demuestra que puedes **establecer texto en negrita programáticamente** en solo unas pocas líneas. + +¿Qué sigue? Prueba combinar este enfoque con configuraciones dirigidas por el usuario, o experimenta con otras banderas `FontStyle` como `Strikeout`. Incluso podrías exponer un pequeño panel de UI que permita a usuarios no técnicos elegir negrita, cursiva o subrayado en tiempo de ejecución—sin necesidad de recompilar. + +Si encontraste útil este **tutorial de formato de texto**, no dudes en dejar un comentario o compartir tus propias variantes. ¡Feliz codificación, y que tu UI siempre se vea exactamente como la imaginaste! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/spanish/net/html-extensions-and-conversions/_index.md index 58e38eec4..a9b0123c8 100644 --- a/html/spanish/net/html-extensions-and-conversions/_index.md +++ b/html/spanish/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Descubra el poder de Aspose.HTML para .NET: convierta HTML a XPS sin esfuerzo. R Aprenda a empaquetar archivos HTML en un archivo ZIP usando C# y Aspose.HTML. Guía paso a paso con ejemplos de código. ### [Guardar HTML en ZIP en C# – Ejemplo completo en memoria](./save-html-to-zip-in-c-complete-in-memory-example/) Aprenda a guardar HTML en un archivo ZIP usando C# con un ejemplo completo en memoria. +### [Cómo comprimir HTML en C# – guía de controlador de recursos personalizado](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Aprenda a comprimir archivos HTML usando un controlador de recursos personalizado en C# con Aspose.HTML. Guía paso a paso. ## Conclusión diff --git a/html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..643454ec5 --- /dev/null +++ b/html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Aprende cómo comprimir HTML en C# usando un controlador de recursos personalizado + – guía paso a paso para guardar HTML como zip, convertir HTML a zip y crear zip + a partir de HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: es +og_description: 'Cómo comprimir HTML en C# explicado: usa un controlador de recursos + personalizado para guardar HTML como zip, convierte HTML a zip y crea zip a partir + de HTML en minutos.' +og_title: cómo comprimir html en C# – Guía del manejador de recursos personalizado +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: cómo comprimir HTML en C# – guía del controlador de recursos personalizado +url: /es/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# cómo comprimir html en C# – guía de controlador de recursos personalizado + +¿Alguna vez te has preguntado **cómo comprimir html** directamente desde tu código C# sin copiar archivos al disco primero? No estás solo. Muchos desarrolladores se topan con un obstáculo cuando necesitan empaquetar una página HTML junto con su CSS, imágenes y fuentes para distribución offline, y terminan escribiendo código ad‑hoc de sistema de archivos que rápidamente se convierte en una pesadilla de mantenimiento. + +En este tutorial resolveremos ese problema mostrándote un enfoque limpio y reutilizable que **guarda HTML como un archivo ZIP** usando el `ResourceHandler` de Aspose.HTML. También abordaremos cómo **convertir HTML a ZIP**, e incluso demostraremos un patrón que puedes reutilizar para **crear ZIP a partir de HTML** en cualquier proyecto .NET. Sin scripts externos, sin carpetas temporales—solo C# puro. + +Al final de la guía tendrás un ejemplo listo‑para‑ejecutar que produce un `result.zip` que contiene todos los recursos vinculados, además de un puñado de consejos prácticos que puedes aplicar a tus propios proyectos. + +## Requisitos previos + +- .NET 6+ (el código también funciona en .NET Framework 4.7.2, pero recomendamos el SDK más reciente) +- Paquete NuGet Aspose.HTML para .NET (`Aspose.HTML`) – instalar mediante `dotnet add package Aspose.HTML` +- Familiaridad básica con streams y el espacio de nombres `System.IO.Compression` +- Un IDE o editor de tu elección (Visual Studio, VS Code, Rider…) + +Si ya tienes estos componentes listos, genial—pasemos directamente al código. Si no, el único paso adicional es una instalación de NuGet de una línea; todo lo demás está contenido en sí mismo. + +## Paso 1: Crear un documento HTML simple en memoria + +Primero necesitamos un objeto `HTMLDocument` que represente la página que queremos comprimir. En un escenario del mundo real podrías cargarlo desde una URL o un archivo, pero para mayor claridad construiremos un pequeño documento en línea. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Por qué es importante:** +> Al mantener el documento en memoria evitamos cualquier I/O de archivo intermedio, lo que hace que el paso posterior de **convertir html a zip** sea rápido y seguro para hilos. + +## Paso 2: Preparar un flujo ZIP en memoria + +En lugar de escribir un archivo `.zip` temporal en el disco, usaremos un `MemoryStream`. Esto mantiene todo en RAM, ideal para servicios web o trabajos en segundo plano que necesitan devolver el archivo directamente a un cliente. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Consejo:** La instrucción `using` garantiza que el flujo se libere automáticamente, evitando fugas de memoria. + +## Paso 3: Implementar un ResourceHandler personalizado + +Aspose.HTML llama a un `ResourceHandler` para cada recurso externo que descubre (archivos CSS, imágenes, fuentes, etc.). Al subclasificar `ResourceHandler` podemos decidir exactamente dónde termina cada recurso—en nuestro caso, como una entrada dentro del archivo ZIP. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### ¿Por qué un controlador personalizado? + +- **Control sobre el nombre** – tú decides cómo aparece cada archivo en el archivo. +- **Sin archivos temporales** – el controlador escribe directamente en el ZIP en memoria. +- **Reutilización** – puedes incorporar esta clase en cualquier proyecto que necesite **guardar html como zip**. + +## Paso 4: Guardar el documento HTML usando el controlador + +Ahora unimos todo. El método `Save` invocará `HandleResource` para cada recurso vinculado, y el controlador transmitirá esos bytes al archivo ZIP que creamos anteriormente. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **¿Qué ocurre bajo el capó?** +> Aspose analiza el HTML, descubre la referencia ``, solicita al controlador un flujo, y el controlador crea una entrada `logo.png` dentro del ZIP. El mismo flujo se repite para CSS, fuentes o cualquier otro recurso externo. + +## Paso 5: Persistir el archivo ZIP en disco (o devolverlo) + +Finalmente escribimos el archivo en memoria a un archivo. En una API web podrías, en su lugar, devolver `zipMemoryStream.ToArray()` como un arreglo de bytes. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Resultado esperado + +Abre `result.zip` y deberías ver: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Si abres el archivo en un explorador de archivos notarás que el archivo HTML se almacena como `resource.bin` porque no le dimos un nombre amigable. Puedes mejorar eso fácilmente verificando `resourceInfo.ContentType` y asignando `.html` cuando corresponda. + +## Ejemplo completo y funcional + +A continuación se muestra el programa completo, listo para copiar y pegar, que incorpora todos los pasos anteriores. Ejecútalo desde una aplicación de consola y obtendrás un archivo ZIP listo para compartir. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Ejecutar este código** generará `result.zip` en el directorio de trabajo del programa. Ábrelo y encontrarás `index.html` (nuestra página original) más `logo.png` si esa imagen existía en disco o se obtuvo de una URL. + +## Variaciones comunes y casos límite + +| Escenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/swedish/net/generate-jpg-and-png-images/_index.md index 39785fb46..c2f425257 100644 --- a/html/swedish/net/generate-jpg-and-png-images/_index.md +++ b/html/swedish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Lär dig att använda Aspose.HTML för .NET för att manipulera HTML-dokument, k Lär dig hur du aktiverar kantutjämning för att förbättra bildkvaliteten när du konverterar DOCX-dokument till PNG eller JPG med Aspose.HTML. ### [Konvertera DOCX till PNG – skapa zip‑arkiv C#‑handledning](./convert-docx-to-png-create-zip-archive-c-tutorial/) Lär dig hur du konverterar DOCX-filer till PNG-bilder och packar dem i ett zip‑arkiv med C# och Aspose.HTML. +### [Skapa PNG från HTML – steg‑för‑steg‑guide för C#‑utvecklare](./create-png-from-html-step-by-step-guide-for-c-developers/) +Lär dig hur du skapar PNG‑bilder från HTML med en steg‑för‑steg‑guide för C#‑utvecklare. ## Slutsats diff --git a/html/swedish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/swedish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..90f8053f2 --- /dev/null +++ b/html/swedish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Skapa PNG från HTML snabbt med Aspose.HTML. Lär dig hur du renderar HTML + till PNG, ställer in canvasstorlek, lägger till bakgrundsfärg och sparar den renderade + bilden på några minuter. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: sv +og_description: Skapa PNG från HTML med Aspose.HTML. Den här guiden visar hur du renderar + HTML till PNG, ställer in canvasstorlek, lägger till bakgrundsfärg och sparar den + renderade bilden. +og_title: Skapa PNG från HTML – Komplett C#-renderingshandledning +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Skapa PNG från HTML – Steg‑för‑steg guide för C#‑utvecklare +url: /sv/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa PNG från HTML – Komplett C# Rendering‑handledning + +Har du någonsin behövt **create PNG from HTML** men varit osäker på vilket bibliotek som ger dig skarpa, antialiasade resultat? Du är inte ensam. I många web‑till‑bild‑pipelines är den största smärtan att få text och grafik att se lika skarpa ut som i webbläsaren. + +Den goda nyheten? Med Aspose.HTML kan du **render HTML to PNG** på några få rader, kontrollera canvas‑storleken, lägga till en solid bakgrundsfärg och slutligen **save rendered image** till disk—utan att röra en webbläsare. I den här handledningen går vi igenom hela processen, förklarar varför varje inställning är viktig och visar dig ett färdigt exempel. + +## Vad du kommer att lära dig + +- Hur du laddar HTML från en sträng, fil eller URL +- Hur du konfigurerar **set canvas size** och **add background color** för förutsägbart resultat +- Aktivera antialiasing och sub‑pixel text hinting för extremt skarpa rubriker +- De exakta stegen för att **save rendered image** som en PNG‑fil +- Vanliga fallgropar och valfria justeringar för olika scenarier + +Ingen tidigare erfarenhet av Aspose.HTML krävs; bara en grundläggande C#‑miljö och Visual Studio (eller din föredragna IDE). + +--- + +## Steg 1: Installera Aspose.HTML för .NET + +Innan vi skriver någon kod, se till att Aspose.HTML‑NuGet‑paketet är refererat i ditt projekt. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** Använd den senaste stabila versionen (från april 2026, 23.9.0) för att få den nyaste renderingsmotorn och buggfixar. + +--- + +## Steg 2: Ladda HTML‑källan – Skapa PNG från HTML + +Du kan mata renderaren med en inline‑sträng, en lokal fil eller en fjärr‑URL. För den här demon använder vi en enkel inline‑sträng som innehåller en rubrik med ett anpassat typsnitt. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Varför detta är viktigt:** Att ladda HTML i ett `HTMLDocument` ger motorn full kontroll över DOM‑parsing, CSS‑kaskad och layoutberäkningar. Det isolerar också renderingen från någon extern webbläsartillstånd, vilket säkerställer reproducerbara resultat. + +--- + +## Steg 3: Konfigurera renderingsalternativ – Ställ in canvas‑storlek & lägg till bakgrundsfärg + +`ImageRenderingOptions`‑klassen låter dig finjustera utdata‑bilden. Här kommer vi att aktivera antialiasing, sätta en vit bakgrund och explicit definiera en canvas på **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Varför du kan vilja ändra dessa värden:** +- **Canvas size:** Om du behöver en miniatyr, minska dimensionerna; för högupplösta utskrifter, öka dem. +- **Background color:** Transparenta PNG‑filer är möjliga, men många efterföljande verktyg (t.ex. PowerPoint) förväntar en ogenomskinlig bakgrund. + +--- + +## Steg 4: Rendera och **Save Rendered Image** som PNG + +Nu sker det tunga arbetet. `ImageRenderer` använder `HTMLDocument` och de alternativ vi just definierat, och skriver sedan en PNG‑ström till disk. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +När du kör programmet hittar du `result.png` på ditt skrivbord. Öppna den, så bör du se en ren, antialiasad rubrik centrerad på en vit canvas. + +> **Förväntat resultat:** En 800 × 600 PNG med vit bakgrund och texten “Antialiased Heading” renderad i Arial, som ser lika mjuk ut som i Chrome. + +--- + +## Steg 5: Verifiera resultatet – Snabba kontroller + +1. **File existence:** `File.Exists(outputPath)` bör returnera `true`. +2. **Dimensions:** Öppna PNG‑filen i någon bildvisare; den bör rapportera 800 × 600 px. +3. **Visual quality:** Zooma in till 200 % – textens kanter måste förbli släta, inte hackiga. + +Om något ser felaktigt ut, dubbelkolla att `UseAntialiasing` och `UseHinting` båda är satta till `true`. Dessa två flaggor är den hemliga såsen för högkvalitativ rendering. + +--- + +## Vanliga variationer & kantfall + +| Scenario | Vad som ska justeras | Varför | +|----------|----------------------|--------| +| **Rendera en fjärrwebbsida** | Replace `new HTMLDocument(htmlContent)` with `new HTMLDocument("https://example.com")` | Allows you to capture live sites without copying HTML manually. | +| **Transparent bakgrund** | Set `BackgroundColor = Color.Transparent` and use `ImageFormat.Png` | Useful for overlaying the PNG on other graphics. | +| **Annat bildformat** | Change `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG may be smaller for photographic content, but loses lossless quality. | +| **Dynamisk canvas‑storlek** | Use `imgOptions.Width = htmlDoc.Body.ClientWidth;` after layout | Lets the image match the natural width of the HTML content. | +| **High‑DPI‑utdata** | Multiply `Width` and `Height` by a scale factor (e.g., 2) | Generates retina‑ready assets for modern displays. | + +--- + +## Fullt fungerande exempel (Klar‑för‑kopiering) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Kör programmet (`dotnet run` eller tryck F5 i Visual Studio) så får du en perfekt renderad PNG klar för användning i e‑post, rapporter eller någon annan plats där du behöver en statisk bild av HTML. + +--- + +## Vanliga frågor + +**Q: Fungerar detta med CSS 3‑funktioner som flexbox?** +A: Ja. Aspose.HTML stödjer de flesta moderna CSS, inklusive flexbox, grid och media queries. Se bara till att du använder den senaste biblioteks‑versionen. + +**Q: Vad händer om min HTML refererar till externa bilder?** +A: Renderaren följer relativa URL‑er baserat på dokumentets base‑URI. Om du laddar HTML från en sträng, sätt `doc.BaseUrl` till mappen som innehåller resurserna. + +**Q: Kan jag rendera flera sidor till en PNG?** +A: Inte direkt—varje anrop av `ImageRenderer` producerar en enskild raster‑bild. För flersidigt resultat, rendera varje sida separat och sätt ihop dem med ett grafikbibliotek (t.ex. ImageSharp). + +--- + +## Slutsats + +Du har nu en solid, end‑to‑end‑lösning för att **create PNG from HTML** med Aspose.HTML. Genom att konfigurera **render html to png**‑alternativ—såsom **set canvas size**, **add background color**, och aktivera antialiasing—kan du generera professionella bilder utan en webbläsare. + +Från och med nu kan du experimentera med högre DPI, transparenta bakgrunder eller batch‑bearbetning av dussintals HTML‑snuttar. Samma mönster gäller oavsett om du bygger en miniatyr‑tjänst, en PDF‑genereringspipeline eller ett verktyg för förhandsgranskning av statiska webbplatser. + +Lycka till med renderingen, och tveka inte att lämna en kommentar om du stöter på problem! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/swedish/net/html-document-manipulation/_index.md index b766c5742..b76b183c2 100644 --- a/html/swedish/net/html-document-manipulation/_index.md +++ b/html/swedish/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Lär dig att använda Aspose.HTML för .NET. Importera namnutrymme, slå samman Lås upp potentialen för webbutveckling med Aspose.HTML för .NET. Skapa, konvertera och manipulera HTML-dokument enkelt. ### [Skapa HTML från sträng i C# – Anpassad resurs‑hanterare guide](./create-html-from-string-in-c-custom-resource-handler-guide/) Lär dig hur du skapar HTML från en sträng i C# med en anpassad resurs‑hanterare i Aspose.HTML för .NET. +### [Applicera teckensnittsstil programatiskt – Snabb C#-guide](./apply-font-style-programmatically-quick-c-guide/) +Lär dig hur du programatiskt ändrar teckensnittsstil i HTML med en kort C#-guide. ## Slutsats diff --git a/html/swedish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/swedish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..85d4a8cef --- /dev/null +++ b/html/swedish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-04-23 +description: Applicera teckensnittsstil programatiskt och lär dig hur du tar bort + understrykning från text, ändrar textstil och sätter fet text programatiskt i en + kortfattad handledning. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: sv +og_description: Applicera teckensnittsstil programatiskt och upptäck hur du tar bort + understrykning från text, ändrar textstil och sätter fet text programatiskt i en + kort, praktisk handledning. +og_title: Applicera teckensnittsstil programatiskt – Snabb C#‑guide +tags: +- csharp +- ui +- text-formatting +- programming +title: Applicera teckensnittsstil programatiskt – Snabb C#-guide +url: /sv/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Applicera teckensnittsstil programatiskt – Snabb C#‑guide + +Har du någonsin behövt **apply font style** på ett UI‑element men varit osäker på var du ska börja? Du är inte ensam – de flesta utvecklare stöter på detta problem när de först börjar leka med dynamisk textformatering. Den goda nyheten? På bara några minuter vet du exakt hur du ändrar en etikettens utseende, tar bort understrykning från text och sätter fet text programatiskt utan att leta igenom oändliga dokument. + +I den här **text formatting tutorial** går vi igenom ett komplett, körbart exempel, förklarar “varför” bakom varje rad och strör in praktiska tips som du kan copy‑paste in i vilket WinForms‑ eller WPF‑projekt som helst. Ingen fluff, bara det som får jobbet gjort. + +--- + +## Vad du kommer att lära dig + +- Hur du **apply font style** med en liten hjälparklass. +- De exakta stegen för att **remove underline from text** samtidigt som du behåller andra stilar intakta. +- Sätt att **change text style** (bold, italic, underline) i farten. +- Ett komplett, kopieringsklart kodsnutt som **sets bold text programmatically**. +- Vanliga fallgropar och hantering av edge‑cases så att du inte blir överraskad senare. + +**Förutsättningar:** .NET 6+ (eller någon recent .NET Framework), grundläggande C#‑kunskaper och en IDE du föredrar (Visual Studio, Rider eller VS Code). Det är allt – inga extra NuGet‑paket behövs. + +## Steg 1 – Applicera teckensnittsstil på din kontroll + +Kärnan i varje **apply font style**‑operation är en `FontStyle`‑enum kombinerad med ett `Font`‑objekt. För att hålla koden snygg omsluter vi enum‑logiken i en liten `WebFontStyle`‑klass. Denna klass speglar egenskaperna du såg i det ursprungliga kodsnutten (`Bold`, `Italic`, `Underline`) och bygger ett `FontStyle`‑värde som du kan skicka till `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Varför detta är viktigt:** +Genom att isolera flagg‑bygglogiken undviker du att sprida bitvisa `|`‑operationer över hela din UI‑kod. Det blir lättare att läsa, lättare att testa och – viktigast av allt – gör avsikten **apply font style** kristallklar. + +## Steg 2 – Ta bort understrykning från text (och behåll andra stilar intakta) + +Anta att du har ärvt en etikett som redan är understruken, men designen kräver ren fet text. Du vill inte förlora fetstil när du tar bort understrykningen. Här kommer `WebFontStyle`‑klassen till sin rätt. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Viktigt:** Genom att sätta `Underline = false` explicit talar du om för hjälpen att *exkludera* understrykning‑flaggan. Om du utelämnar raden helt skulle den tidigare understrykningen bestå, vilket är en vanlig felkälla när utvecklare bara växlar `Bold`‑egenskapen. + +## Steg 3 – Ändra textstil: Fet, Kursiv och mer + +Du kanske undrar, “Vad händer om jag också behöver växla kursiv?” Samma objekt fungerar för alla kombinationer. Nedan är en snabb matris du kan referera till medan du kodar. + +| Önskad stil | `Bold` | `Italic` | `Underline` | +|-------------|--------|----------|-------------| +| **Endast fet** | true | false | false | +| *Endast kursiv* | false | true | false | +| **Fet + Kursiv** | true | true | false | +| **Fet + Understreck** | true | false | true | + +Ställ bara in de egenskaper du behöver och anropa `ToFont`. Hjälpen gör det tunga lyftet åt dig, så att du kan fokusera på UI‑logiken. + +## Fullt exempel – Sätt fet text programatiskt + +Nedan är ett **komplett, körbart WinForms**‑exempel som demonstrerar allt vi gått igenom. Klistra in det i ett nytt konsol‑stil WinForms‑projekt och tryck **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Förväntat resultat + +När du kör programmet visas ett fönster med texten **“Hello, world!”** renderad **fet**, **inte kursiv**, och **utan någon understrykning**. Den visuella bekräftelsen visar att **apply font style**‑logiken fungerade perfekt. + +## Pro‑tips & edge‑cases + +- **Dynamiska uppdateringar:** Om du behöver ändra stilen efter att formuläret visats (t.ex. som svar på en kryssruta), skapa bara om `WebFontStyle`‑instansen eller ändra dess egenskaper och återtilldela `lbl.Font`. UI‑et uppdateras omedelbart. +- **High‑DPI‑överväganden:** När du ersätter ett `Font`‑objekt skalar Windows det automatiskt baserat på aktuell DPI. Ingen extra kod behövs såvida du inte hanterar skalning manuellt. +- **WPF‑motsvarighet:** I WPF skulle du binda `FontWeight`, `FontStyle` och `TextDecorations` istället för att byta ett `Font`‑objekt. Samma logiska separation gäller – håll stil‑logiken utanför visningslagret. +- **Undvika minnesläckor:** Att återtilldela `Label.Font` skapar ett nytt `Font`‑objekt. Disposera det gamla om du byter stilar ofta: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +## Slutsats + +Du vet nu hur du **apply font style** på vilken .NET‑kontroll som helst, **remove underline from text**, och **change text style** i farten – allt medan du håller din kod ren och återanvändbar. Den lilla `WebFontStyle`‑hjälpen förvandlar ett fåtal boolska flaggor till en solid, testbar komponent, och det fullständiga exemplet visar att du kan **set bold text programmatically** på bara några rader. + +Vad blir nästa steg? Prova att kombinera detta tillvägagångssätt med användarstyrda inställningar, eller experimentera med andra `FontStyle`‑flaggor som `Strikeout`. Du kan till och med exponera en liten UI‑panel som låter icke‑tekniska användare välja fet, kursiv eller understrykning vid körning – ingen omkompilering krävs. + +Om du fann denna **text formatting tutorial** hjälpsam, tveka inte att lämna en kommentar eller dela dina egna varianter. Lycklig kodning, och må ditt UI alltid se exakt ut som du tänkt! + +--- + +![Skärmdump som visar hur man applicerar teckensnittsstil på en etikett i C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/swedish/net/html-extensions-and-conversions/_index.md index 6d01c9b96..dcdb1b12c 100644 --- a/html/swedish/net/html-extensions-and-conversions/_index.md +++ b/html/swedish/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Lär dig hur du konverterar HTML till TIFF med Aspose.HTML för .NET. Följ vår Upptäck kraften i Aspose.HTML för .NET: Konvertera HTML till XPS utan ansträngning. Förutsättningar, steg-för-steg-guide och vanliga frågor ingår. ### [Hur du zippar HTML i C# – Spara HTML till zip](./how-to-zip-html-in-c-save-html-to-zip/) Lär dig hur du packar HTML-filer i en zip-arkiv med C# och Aspose.HTML för .NET i en steg-för-steg-guide. +### [Hur du zippar HTML i C# – guide för anpassad resurs‑hanterare](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Lär dig hur du packar HTML-filer i ett ZIP‑arkiv med en anpassad resurs‑hanterare i C# och Aspose.HTML för .NET. ### [Skapa HTML-dokument med formaterad text och exportera till PDF – Fullständig guide](./create-html-document-with-styled-text-and-export-to-pdf-full/) Lär dig skapa ett HTML-dokument med stiliserad text och konvertera det till PDF med Aspose.HTML för .NET i en komplett steg-för-steg-guide. ### [Skapa PDF från HTML – C# steg‑för‑steg‑guide](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..7e07f2432 --- /dev/null +++ b/html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-04-23 +description: Lär dig hur du zippar HTML i C# med en anpassad resurs‑hanterare – steg‑för‑steg‑guide + för att spara HTML som zip, konvertera HTML till zip och skapa zip från HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: sv +og_description: 'hur man zippar html i C# förklarat: använd en anpassad resurs‑hanterare + för att spara html som zip, konvertera html till zip och skapa zip från html på + några minuter.' +og_title: hur man zippar html i C# – Guide för anpassad resurs‑hanterare +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: Hur man zippar HTML i C# – guide för anpassad resurs‑hanterare +url: /sv/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# hur man zippar html i C# – guide för anpassad resource‑handler + +Har du någonsin funderat **hur man zippar html** direkt från din C#‑kod utan att först skriva filer till disk? Du är inte ensam. Många utvecklare fastnar när de måste paketera en HTML‑sida tillsammans med dess CSS, bilder och typsnitt för offline‑distribution, och de slutar med att skriva ad‑hoc‑fil‑system‑kod som snabbt blir ett underhållshelvete. + +I den här tutorialen löser vi problemet genom att visa ett rent, återanvändbart tillvägagångssätt som **sparar HTML som ett ZIP‑arkiv** med hjälp av Aspose.HTML:s `ResourceHandler`. Vi berör också hur man **konverterar HTML till ZIP**, och demonstrerar ett mönster du kan återanvända för att **skapa ZIP från HTML** i vilket .NET‑projekt som helst. Inga externa skript, inga temporära mappar – bara ren C#. + +När du är klar med guiden har du ett färdigt exempel som producerar en `result.zip` som innehåller varje länkat resurstillgång, samt ett antal praktiska tips du kan tillämpa i dina egna projekt. + +## Förutsättningar + +- .NET 6+ (koden fungerar även på .NET Framework 4.7.2, men vi rekommenderar den senaste SDK:n) +- Aspose.HTML för .NET NuGet‑paket (`Aspose.HTML`) – installera via `dotnet add package Aspose.HTML` +- Grundläggande kunskap om streams och `System.IO.Compression`‑namnutrymmet +- En IDE eller editor du föredrar (Visual Studio, VS Code, Rider …) + +Om du redan har dessa komponenter på plats, toppen – låt oss hoppa rakt in i koden. Om inte, är det enda extra steget en en‑radig NuGet‑installation; allt annat är självständigt. + +## Steg 1: Skapa ett enkelt HTML‑dokument i minnet + +Först behöver vi ett `HTMLDocument`‑objekt som representerar sidan vi vill zipa. I ett verkligt scenario kan du ladda detta från en URL eller en fil, men för tydlighetens skull bygger vi ett litet dokument inline. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Varför detta är viktigt:** +> Genom att hålla dokumentet i minnet undviker vi någon mellanliggande fil‑I/O, vilket gör det efterföljande **convert html to zip**‑steget snabbt och trådsäkert. + +## Steg 2: Förbered en ZIP‑stream i minnet + +Istället för att skriva en temporär `.zip`‑fil till disk använder vi en `MemoryStream`. Detta håller allt i RAM, idealiskt för webbtjänster eller bakgrundsjobb som behöver returnera arkivet direkt till en klient. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tips:** `using`‑satsen säkerställer att streamen disponeras automatiskt, vilket förhindrar minnesläckor. + +## Steg 3: Implementera en anpassad ResourceHandler + +Aspose.HTML anropar en `ResourceHandler` för varje extern tillgång den upptäcker (CSS‑filer, bilder, typsnitt osv.). Genom att subklassa `ResourceHandler` kan vi bestämma exakt var varje resurs hamnar – i vårt fall som ett entry i ZIP‑arkivet. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Varför en anpassad handler? + +- **Kontroll över namn** – du bestämmer hur varje fil visas i arkivet. +- **Inga temporära filer** – handlern skriver rakt in i den minnes‑ZIP. +- **Återanvändbarhet** – du kan släppa den här klassen i vilket projekt som helst som behöver **save html as zip**. + +## Steg 4: Spara HTML‑dokumentet med handlern + +Nu knyter vi ihop allt. `Save`‑metoden kommer att anropa `HandleResource` för varje länkat asset, och handlern kommer att strömma dessa bytes in i ZIP‑arkivet vi skapade tidigare. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Vad händer under huven?** +> Aspose analyserar HTML‑koden, upptäcker ``‑referensen, ber handlern om en stream, och handlern skapar ett `logo.png`‑entry i ZIP‑filen. Samma flöde upprepas för CSS, typsnitt eller någon annan extern resurs. + +## Steg 5: Spara ZIP‑arkivet till disk (eller returnera det) + +Till sist skriver vi det minnes‑arkivet till en fil. I ett web‑API kan du istället returnera `zipMemoryStream.ToArray()` som en byte‑array. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Förväntat resultat + +Öppna `result.zip` och du bör se: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Om du öppnade arkivet i en filutforskare skulle du märka att HTML‑filen lagras som `resource.bin` eftersom vi inte gav den ett vänligt namn. Du kan enkelt förbättra detta genom att kontrollera `resourceInfo.ContentType` och tilldela `.html` när det är lämpligt. + +## Fullt fungerande exempel + +Nedan är det kompletta, kopiera‑och‑klistra‑klara programmet som inkluderar alla stegen ovan. Kör det från en konsolapp, så får du en färdig‑att‑dela ZIP‑fil. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Att köra den här koden** kommer att generera `result.zip` i programmets arbetskatalog. Öppna den så hittar du `index.html` (vår ursprungliga sida) plus `logo.png` om den bilden fanns på disk eller hämtades från en URL. + +## Vanliga varianter & kantfall + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/thai/net/generate-jpg-and-png-images/_index.md index bb3254275..80d3bf250 100644 --- a/html/thai/net/generate-jpg-and-png-images/_index.md +++ b/html/thai/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML สำหรับ .NET นำเสนอวิธีการง เรียนรู้วิธีเปิดใช้งาน Antialiasing เพื่อให้ภาพ PNG/JPG ที่แปลงจาก DOCX มีความคมชัดและลื่นไหล ### [แปลง DOCX เป็น PNG – สร้างไฟล์ ZIP ด้วย C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) เรียนรู้วิธีแปลงไฟล์ DOCX เป็น PNG แล้วบีบอัดเป็นไฟล์ ZIP ด้วย C# โดยใช้ Aspose.HTML +### [สร้าง PNG จาก HTML – คู่มือขั้นตอนสำหรับนักพัฒนา C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +เรียนรู้วิธีแปลง HTML เป็นไฟล์ PNG อย่างละเอียดด้วย C# โดยใช้ Aspose.HTML สำหรับ .NET ## บทสรุป diff --git a/html/thai/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/thai/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..5f1fb6179 --- /dev/null +++ b/html/thai/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-04-23 +description: สร้าง PNG จาก HTML อย่างรวดเร็วด้วย Aspose.HTML เรียนรู้วิธีเรนเดอร์ + HTML เป็น PNG ตั้งขนาดแคนวาส เพิ่มสีพื้นหลัง และบันทึกภาพที่เรนเดอร์ได้ภายในไม่กี่นาที. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: th +og_description: สร้าง PNG จาก HTML ด้วย Aspose.HTML คู่มือนี้แสดงวิธีการเรนเดอร์ HTML + เป็น PNG ตั้งขนาดแคนวาส เพิ่มสีพื้นหลัง และบันทึกภาพที่เรนเดอร์แล้ว +og_title: สร้าง PNG จาก HTML – บทเรียนการเรนเดอร์ C# อย่างครบถ้วน +tags: +- C# +- Aspose.HTML +- Image Rendering +title: สร้าง PNG จาก HTML – คู่มือขั้นตอนต่อขั้นสำหรับนักพัฒนา C# +url: /th/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้าง PNG จาก HTML – การสอนการเรนเดอร์ C# อย่างครบถ้วน + +เคยต้องการ **สร้าง PNG จาก HTML** แต่ไม่แน่ใจว่าห้องสมุดใดจะให้ผลลัพธ์ที่คมชัดและแอนติอาลีส? คุณไม่ได้อยู่คนเดียว ในหลาย ๆ pipeline จากเว็บไปยังภาพ จุดเจ็บปวดที่ใหญ่ที่สุดคือการทำให้ข้อความและกราฟิกดูคมชัดเท่าที่แสดงในเบราว์เซอร์ + +ข่าวดีคืออะไร? ด้วย Aspose.HTML คุณสามารถ **render HTML to PNG** ได้ในไม่กี่บรรทัด ควบคุมขนาด canvas เพิ่มสีพื้นหลังแบบทึบ และสุดท้าย **save rendered image** ลงดิสก์—ทั้งหมดโดยไม่ต้องเปิดเบราว์เซอร์ ในบทแนะนำนี้เราจะเดินผ่านกระบวนการทั้งหมด อธิบายว่าการตั้งค่าแต่ละอย่างสำคัญอย่างไร และแสดงตัวอย่างที่พร้อมรัน + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีโหลด HTML จากสตริง ไฟล์ หรือ URL +- วิธีกำหนด **set canvas size** และ **add background color** เพื่อให้ผลลัพธ์คาดเดาได้ +- การเปิดใช้งาน antialiasing และ sub‑pixel text hinting เพื่อหัวข้อที่คมชัดเหมือนมีมีดโกน +- ขั้นตอนที่แน่นอนในการ **save rendered image** เป็นไฟล์ PNG +- ข้อผิดพลาดทั่วไปและการปรับแต่งเพิ่มเติมสำหรับสถานการณ์ต่าง ๆ + +ไม่จำเป็นต้องมีประสบการณ์กับ Aspose.HTML มาก่อน; เพียงแค่ตั้งค่า C# เบื้องต้นและ Visual Studio (หรือ IDE ที่คุณชอบ) + +--- + +## Step 1: Install Aspose.HTML for .NET + +ก่อนที่เราจะเขียนโค้ดใด ๆ ให้แน่ใจว่าแพคเกจ NuGet ของ Aspose.HTML ถูกอ้างอิงในโปรเจกต์ของคุณ + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro tip:** ใช้เวอร์ชันเสถียรล่าสุด (ณ เมษายน 2026, 23.9.0) เพื่อรับเอ็นจิ้นการเรนเดอร์และการแก้บั๊กใหม่ ๆ + +--- + +## Step 2: Load the HTML Source – Create PNG from HTML + +คุณสามารถป้อน renderer ด้วยสตริงในบรรทัดเดียว ไฟล์ในเครื่อง หรือ URL ระยะไกล สำหรับการสาธิตนี้เราจะใช้สตริงง่าย ๆ ที่มีหัวข้อพร้อมฟอนต์กำหนดเอง + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Why this matters:** การโหลด HTML เข้า `HTMLDocument` ให้เอนจินควบคุมการพาร์ส DOM, การ cascade ของ CSS, และการคำนวณเลย์เอาต์อย่างเต็มที่ นอกจากนี้ยังแยกการเรนเดอร์ออกจากสถานะของเบราว์เซอร์ภายนอก ทำให้ผลลัพธ์ทำซ้ำได้ + +--- + +## Step 3: Configure Rendering Options – Set Canvas Size & Add Background Color + +คลาส `ImageRenderingOptions` ให้คุณปรับแต่งภาพเอาต์พุตได้ละเอียด ที่นี่เราจะเปิด antialiasing ตั้งพื้นหลังสีขาว และกำหนด canvas ขนาด **800 × 600 px** อย่างชัดเจน + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Why you might change these values:** +- **Canvas size:** หากต้องการ thumbnail ให้ลดขนาด; หากต้องการพิมพ์ความละเอียดสูงให้เพิ่มขนาด +- **Background color:** สามารถทำ PNG โปร่งใสได้ แต่เครื่องมือหลายตัว (เช่น PowerPoint) คาดหวังพื้นหลังทึบ + +--- + +## Step 4: Render and **Save Rendered Image** as PNG + +ตอนนี้งานหนักเริ่มทำงาน `ImageRenderer` จะรับ `HTMLDocument` และตัวเลือกที่เรากำหนดไว้ จากนั้นเขียนสตรีม PNG ลงดิสก์ + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +เมื่อคุณรันโปรแกรม คุณจะพบ `result.png` บนเดสก์ท็อปของคุณ เปิดไฟล์แล้วคุณควรเห็นหัวข้อที่แอนติอาลีสเรียบเรียงอยู่กึ่งกลางบน canvas สีขาว + +> **Expected output:** PNG ขนาด 800 × 600 พร้อมพื้นหลังสีขาวและข้อความ “Antialiased Heading” แสดงด้วย Arial ราบรื่นเท่าที่ Chrome แสดง + +--- + +## Step 5: Verify the Result – Quick Checks + +1. **File existence:** `File.Exists(outputPath)` ควรคืนค่า `true` +2. **Dimensions:** เปิด PNG ด้วยโปรแกรมดูภาพใด ๆ ควรแสดง 800 × 600 px +3. **Visual quality:** ซูมที่ 200 % – ขอบข้อความต้องยังคงเรียบ ไม่เป็นฟันเฟือง + +หากผลลัพธ์ดูแปลก ให้ตรวจสอบว่า `UseAntialiasing` และ `UseHinting` ถูกตั้งเป็น `true` ทั้งสองค่านี้คือสูตรลับสำหรับการเรนเดอร์คุณภาพสูง + +--- + +## Common Variations & Edge Cases + +| Scenario | What to Adjust | Why | +|----------|----------------|-----| +| **Render a remote web page** | แทนที่ `new HTMLDocument(htmlContent)` ด้วย `new HTMLDocument("https://example.com")` | ช่วยให้คุณจับภาพเว็บไซต์สดโดยไม่ต้องคัดลอก HTML ด้วยตนเอง | +| **Transparent background** | ตั้งค่า `BackgroundColor = Color.Transparent` และใช้ `ImageFormat.Png` | มีประโยชน์เมื่อจะวาง PNG บนกราฟิกอื่น | +| **Different image format** | เปลี่ยน `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG อาจมีขนาดเล็กกว่าสำหรับเนื้อหาภาพถ่าย แต่จะเสียคุณภาพ lossless | +| **Dynamic canvas size** | ใช้ `imgOptions.Width = htmlDoc.Body.ClientWidth;` หลังจาก layout | ทำให้ภาพตรงกับความกว้างตามธรรมชาติของเนื้อหา HTML | +| **High‑DPI output** | คูณ `Width` และ `Height` ด้วยปัจจัยสเกล (เช่น 2) | สร้าง assets พร้อม Retina สำหรับจอแสดงผลสมัยใหม่ | + +--- + +## Full Working Example (Copy‑Paste Ready) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +รันโปรแกรม (`dotnet run` หรือกด F5 ใน Visual Studio) แล้วคุณจะได้ PNG ที่เรนเดอร์อย่างสมบูรณ์พร้อมใช้ในอีเมล รายงาน หรือที่ใดก็ตามที่ต้องการภาพคงที่ของ HTML + +--- + +## Frequently Asked Questions + +**Q: Does this work with CSS 3 features like flexbox?** +A: ใช่. Aspose.HTML รองรับ CSS สมัยใหม่ส่วนใหญ่ รวมถึง flexbox, grid, และ media queries. เพียงตรวจสอบว่าคุณใช้เวอร์ชันไลบรารีล่าสุด + +**Q: What if my HTML references external images?** +A: renderer จะตาม URL แบบ relative ตาม base URI ของเอกสาร หากคุณโหลด HTML จากสตริง ให้ตั้ง `doc.BaseUrl` เป็นโฟลเดอร์ที่มีไฟล์ assets + +**Q: Can I render multiple pages into one PNG?** +A: ไม่ได้โดยตรง—แต่ละการเรียก `ImageRenderer` จะสร้าง raster image เพียงภาพเดียว สำหรับเอาต์พุตหลายหน้า ให้เรนเดอร์แต่ละหน้าแยกกันแล้วต่อด้วยไลบรารีกราฟิก (เช่น ImageSharp) + +--- + +## Conclusion + +ตอนนี้คุณมีวิธีแก้ปัญหาแบบครบวงจรเพื่อ **create PNG from HTML** ด้วย Aspose.HTML โดยการกำหนด **render html to png** options เช่น **set canvas size**, **add background color**, และเปิด antialiasing คุณสามารถสร้างภาพคุณภาพระดับมืออาชีพโดยไม่ต้องใช้เบราว์เซอร์ + +จากจุดนี้คุณอาจทดลองเพิ่ม DPI, พื้นหลังโปร่งใส, หรือประมวลผลหลาย HTML พร้อมกัน รูปแบบเดียวกันนี้ใช้ได้ทั้งการสร้างบริการ thumbnail, pipeline การสร้าง PDF, หรือเครื่องมือพรีวิวเว็บไซต์แบบสเตติก + +ขอให้เรนเดอร์สนุกนะครับ และอย่าลังเลที่จะคอมเมนต์หากเจออุปสรรคใด ๆ! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/thai/net/html-document-manipulation/_index.md b/html/thai/net/html-document-manipulation/_index.md index 6df7d74b1..625253ebb 100644 --- a/html/thai/net/html-document-manipulation/_index.md +++ b/html/thai/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML สำหรับ .NET โดดเด่นด้วยควา ปลดล็อกศักยภาพของการพัฒนาเว็บด้วย Aspose.HTML สำหรับ .NET สร้าง แปลง และจัดการเอกสาร HTML ได้อย่างง่ายดาย ### [สร้าง HTML จากสตริงใน C# – คู่มือ Custom Resource Handler](./create-html-from-string-in-c-custom-resource-handler-guide/) เรียนรู้วิธีสร้าง HTML จากสตริงใน C# ด้วยตัวจัดการทรัพยากรแบบกำหนดเองใน Aspose.HTML สำหรับ .NET +### [ใช้สไตล์ฟอนต์แบบโปรแกรมเมติก – คู่มือ C# อย่างรวดเร็ว](./apply-font-style-programmatically-quick-c-guide/) +เรียนรู้วิธีปรับใช้สไตล์ฟอนต์ให้กับเอกสาร HTML ด้วย C# อย่างง่ายและรวดเร็ว ## บทสรุป diff --git a/html/thai/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/thai/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..26de9d261 --- /dev/null +++ b/html/thai/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-04-23 +description: ใช้สไตล์ฟอนต์แบบโปรแกรมและเรียนรู้วิธีลบขีดเส้นใต้จากข้อความ, เปลี่ยนสไตล์ข้อความ, + และตั้งข้อความเป็นตัวหนาแบบโปรแกรมในบทแนะนำสั้น ๆ +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: th +og_description: ใช้สไตล์ฟอนต์แบบโปรแกรมเมติกและค้นหาวิธีลบขีดเส้นใต้จากข้อความ, เปลี่ยนสไตล์ข้อความ, + และตั้งข้อความเป็นตัวหนาแบบโปรแกรมเมติกในบทแนะนำสั้น ๆ ที่ใช้งานได้จริง. +og_title: ใช้สไตล์ฟอนต์โดยโปรแกรม – คู่มือ C# อย่างรวดเร็ว +tags: +- csharp +- ui +- text-formatting +- programming +title: ใช้สไตล์ฟอนต์แบบโปรแกรม – คู่มือ C# อย่างรวดเร็ว +url: /th/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ใช้สไตล์ฟอนต์แบบโปรแกรมเมติก – คู่มือสั้น C# + +เคยต้อง **ใช้สไตล์ฟอนต์** กับองค์ประกอบ UI แต่ไม่รู้ว่าจะเริ่มจากตรงไหนหรือเปล่า? คุณไม่ได้เป็นคนเดียว—นักพัฒนาส่วนใหญ่มักเจอปัญหานี้เมื่อลองทำการจัดรูปแบบข้อความแบบไดนามิก ข่าวดีคือในไม่กี่นาทีคุณจะรู้วิธีเปลี่ยนลักษณะของ label, ลบเส้นขีดใต้จากข้อความ, และตั้งค่าข้อความหนาแบบโปรแกรมเมติกโดยไม่ต้องค้นหาเอกสารยาว ๆ + +ใน **บทแนะนำการจัดรูปแบบข้อความ** นี้เราจะเดินผ่านตัวอย่างที่ทำงานได้เต็มรูปแบบ, อธิบาย “ทำไม” ของแต่ละบรรทัด, และให้เคล็ดลับที่คุณสามารถคัดลอก‑วางไปใช้ในโปรเจกต์ WinForms หรือ WPF ใดก็ได้ ไม่มีส่วนเกิน เพียงสิ่งที่ทำให้งานสำเร็จ + +--- + +## สิ่งที่คุณจะได้เรียน + +- วิธี **ใช้สไตล์ฟอนต์** ด้วยคลาสช่วยเหลือขนาดเล็ก +- ขั้นตอนที่แม่นยำในการ **ลบเส้นขีดใต้จากข้อความ** ขณะยังคงรักษาสไตล์อื่นไว้ +- วิธี **เปลี่ยนสไตล์ข้อความ** (หนา, เอียง, ขีดใต้) อย่างรวดเร็ว +- ชิ้นส่วนโค้ดเต็มพร้อมคัดลอกที่ **ตั้งค่าข้อความหนาแบบโปรแกรมเมติก** +- ข้อผิดพลาดทั่วไปและการจัดการกรณีขอบ เพื่อให้คุณไม่เจอปัญหาในภายหลัง + +**ข้อกำหนดเบื้องต้น:** .NET 6+ (หรือ .NET Framework เวอร์ชันใหม่), ความรู้พื้นฐาน C#, และ IDE ที่คุณชอบ (Visual Studio, Rider, หรือ VS Code) เพียงเท่านี้—ไม่ต้องติดตั้ง NuGet แพคเกจเพิ่มเติม + +--- + +## ขั้นตอนที่ 1 – ใช้สไตล์ฟอนต์กับคอนโทรลของคุณ + +หัวใจของการ **ใช้สไตล์ฟอนต์** ใด ๆ คือ enum `FontStyle` ที่รวมกับอ็อบเจกต์ `Font` เพื่อให้โค้ดดูเรียบร้อย เราจะห่อหุ้มตรรกะของ enum นี้ไว้ในคลาสเล็ก ๆ ชื่อ `WebFontStyle` คลาสนี้สะท้อนคุณสมบัติที่คุณเห็นในโค้ดต้นฉบับ (`Bold`, `Italic`, `Underline`) และสร้างค่า `FontStyle` ที่คุณสามารถส่งให้ `Font` ได้ + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**ทำไมถึงสำคัญ:** +โดยการแยกตรรกะการสร้างแฟล็กออกจาก UI คุณจะหลีกเลี่ยงการกระจายการใช้ `|` แบบบิตไวด์ทั่วโค้ด ทำให้อ่านง่ายขึ้น, ทดสอบง่ายขึ้น, และ—ที่สำคัญที่สุด—ทำให้เจตนาของ **ใช้สไตล์ฟอนต์** ชัดเจนเป็นผลลัพธ์ + +--- + +## ขั้นตอนที่ 2 – ลบเส้นขีดใต้จากข้อความ (และรักษาสไตล์อื่นไว้) + +สมมติว่าคุณได้รับมรดกจาก label ที่มีเส้นขีดใต้แล้ว แต่การออกแบบต้องการข้อความหนาแบบธรรมดา คุณไม่ต้องการสูญเสียความหนาเมื่อเอาเส้นขีดใต้ออก ที่นี่ `WebFontStyle` จะช่วยได้ + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**จุดสำคัญ:** การตั้งค่า `Underline = false` อย่างชัดเจนบอกให้ตัวช่วย *ไม่* รวมแฟล็กเส้นขีดใต้ หากคุณละเว้นบรรทัดนี้ เส้นขีดใต้เดิมจะคงอยู่ ซึ่งเป็นแหล่งที่มาของบั๊กบ่อยครั้งเมื่อผู้พัฒนาเพียงแค่สลับคุณสมบัติ `Bold` + +--- + +## ขั้นตอนที่ 3 – เปลี่ยนสไตล์ข้อความ: หนา, เอียง, และอื่น ๆ + +คุณอาจสงสัยว่า “ถ้าต้องการสลับเอียงด้วยล่ะ?” อ็อบเจกต์เดียวกันทำงานได้กับการผสมใด ๆ ด้านล่างเป็นเมทริกซ์สั้น ๆ ที่คุณสามารถอ้างอิงขณะเขียนโค้ด + +| สไตล์ที่ต้องการ | `Bold` | `Italic` | `Underline` | +|------------------|--------|----------|-------------| +| **หนาเท่านั้น** | true | false | false | +| *เอียงเท่านั้น* | false | true | false | +| **หนา + เอียง** | true | true | false | +| **หนา + ขีดใต้** | true | false | true | + +เพียงตั้งค่าคุณสมบัติที่ต้องการและเรียก `ToFont` ตัวช่วยจะทำงานหนักให้คุณ เพื่อให้คุณโฟกัสที่ตรรกะ UI + +--- + +## ตัวอย่างเต็ม – ตั้งค่าข้อความหนาแบบโปรแกรมเมติก + +ด้านล่างเป็นตัวอย่าง **WinForms ที่ทำงานได้เต็มรูปแบบ** ซึ่งสาธิตทุกอย่างที่เราได้พูดถึงแล้ว คัดลอกไปวางในโปรเจกต์ WinForms แบบ console‑style ใหม่และกด **F5** + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +เมื่อคุณรันโปรแกรม หน้าต่างจะปรากฏพร้อมข้อความ **“Hello, world!”** ที่แสดงเป็น **หนา**, **ไม่เอียง**, และ **ไม่มีเส้นขีดใต้** การยืนยันด้วยภาพนี้บอกว่าตรรกะ **ใช้สไตล์ฟอนต์** ทำงานได้อย่างสมบูรณ์ + +--- + +## เคล็ดลับระดับมืออาชีพ & กรณีขอบ + +- **อัปเดตแบบไดนามิก:** หากต้องการเปลี่ยนสไตล์หลังจากฟอร์มแสดง (เช่น ตอบสนองต่อเช็คบ็อกซ์) เพียงสร้างอินสแตนซ์ `WebFontStyle` ใหม่หรือแก้ไขคุณสมบัติแล้วกำหนดค่า `lbl.Font` ใหม่ UI จะอัปเดตทันที +- **พิจารณา High‑DPI:** เมื่อคุณแทนที่อ็อบเจกต์ `Font` Windows จะสเกลอัตโนมัติตาม DPI ปัจจุบัน ไม่ต้องเขียนโค้ดเพิ่มเติม เว้นแต่คุณจัดการสเกลด้วยตนเอง +- **เทียบเท่า WPF:** ใน WPF คุณจะผูก `FontWeight`, `FontStyle`, และ `TextDecorations` แทนการสลับอ็อบเจกต์ `Font` การแยกตรรกะสไตล์ออกจากเลเยอร์วิวยังคงใช้ได้เช่นกัน +- **หลีกเลี่ยง memory leak:** การกำหนดค่า `Label.Font` ใหม่จะสร้างอ็อบเจกต์ `Font` ตัวใหม่ ควร Dispose อ็อบเจกต์เก่าเมื่อสลับสไตล์บ่อย ๆ: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## สรุป + +ตอนนี้คุณรู้วิธี **ใช้สไตล์ฟอนต์** กับคอนโทรล .NET ใด ๆ, **ลบเส้นขีดใต้จากข้อความ**, และ **เปลี่ยนสไตล์ข้อความ** อย่างรวดเร็ว—ทั้งหมดนี้โดยรักษาโค้ดให้สะอาดและนำกลับมาใช้ใหม่ได้ ตัวช่วย `WebFontStyle` ขนาดเล็กทำให้การจัดการบูลีนหลายค่าเป็นคอมโพเนนต์ที่ทดสอบได้, และตัวอย่างเต็มพิสูจน์ว่าคุณสามารถ **ตั้งค่าข้อความหนาแบบโปรแกรมเมติก** ได้ในไม่กี่บรรทัด + +ต่อไปทำอะไรดี? ลองผสานวิธีนี้กับการตั้งค่าที่ผู้ใช้กำหนด, หรือทดลองใช้แฟล็ก `FontStyle` อื่น ๆ เช่น `Strikeout` คุณอาจสร้างพาเนล UI เล็ก ๆ ที่ให้ผู้ใช้ที่ไม่ใช่นักพัฒนาเลือกหนา, เอียง, หรือขีดใต้ได้ในขณะรัน—ไม่ต้องคอมไพล์ใหม่ + +หากคุณพบว่า **บทแนะนำการจัดรูปแบบข้อความ** นี้เป็นประโยชน์ อย่าลังเลที่จะแสดงความคิดเห็นหรือแชร์วิธีของคุณเอง ขอให้เขียนโค้ดอย่างสนุกสนานและ UI ของคุณดูตรงตามที่คุณต้องการเสมอ! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/thai/net/html-extensions-and-conversions/_index.md index 2474ca32c..bf3288c46 100644 --- a/html/thai/net/html-extensions-and-conversions/_index.md +++ b/html/thai/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Aspose.HTML สำหรับ .NET ไม่ใช่แค่ไลบรา ค้นพบพลังของ Aspose.HTML สำหรับ .NET: แปลง HTML เป็น XPS ได้อย่างง่ายดาย มีข้อกำหนดเบื้องต้น คำแนะนำทีละขั้นตอน และคำถามที่พบบ่อยรวมอยู่ด้วย ### [วิธีบีบอัด HTML เป็น Zip ใน C# – บันทึก HTML เป็น Zip](./how-to-zip-html-in-c-save-html-to-zip/) เรียนรู้วิธีบีบอัดไฟล์ HTML เป็นไฟล์ Zip ด้วย C# และ Aspose.HTML สำหรับ .NET อย่างง่ายดายและปลอดภัย +### [วิธีบีบอัด HTML เป็น Zip ใน C# – คู่มือตัวจัดการทรัพยากรแบบกำหนดเอง](./how-to-zip-html-in-c-custom-resource-handler-guide/) +เรียนรู้วิธีบีบอัดไฟล์ HTML เป็น Zip ด้วย C# โดยใช้ตัวจัดการทรัพยากรแบบกำหนดเองใน Aspose.HTML สำหรับ .NET ### [สร้างเอกสาร HTML พร้อมข้อความที่มีสไตล์และส่งออกเป็น PDF – คู่มือเต็ม](./create-html-document-with-styled-text-and-export-to-pdf-full/) เรียนรู้วิธีสร้างเอกสาร HTML ที่มีข้อความจัดรูปแบบและแปลงเป็น PDF อย่างละเอียดด้วย Aspose.HTML สำหรับ .NET ### [สร้าง PDF จาก HTML – คำแนะนำขั้นตอนโดยขั้นตอน C#](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..ae498ed2d --- /dev/null +++ b/html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-04-23 +description: เรียนรู้วิธีบีบอัด HTML ด้วย C# โดยใช้ตัวจัดการทรัพยากรแบบกำหนดเอง – + คู่มือขั้นตอนต่อขั้นตอนในการบันทึก HTML เป็นไฟล์ zip, แปลง HTML เป็น zip, และสร้าง + zip จาก HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: th +og_description: 'วิธีบีบอัด HTML ด้วย C# อธิบาย: ใช้ตัวจัดการทรัพยากรแบบกำหนดเองเพื่อบันทึก + HTML เป็นไฟล์ zip, แปลง HTML เป็น zip, และสร้าง zip จาก HTML ภายในไม่กี่นาที.' +og_title: วิธีบีบอัด HTML ด้วย C# – คู่มือ Custom Resource Handler +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: วิธีบีบอัด HTML ใน C# – คู่มือผู้จัดการทรัพยากรแบบกำหนดเอง +url: /th/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีบีบอัด HTML เป็น ZIP ใน C# – คู่มือ Custom Resource Handler + +เคยสงสัย **how to zip html** โดยตรงจากโค้ด C# ของคุณโดยไม่ต้องดึงไฟล์ลงดิสก์ก่อนหรือไม่? คุณไม่ได้เป็นคนเดียว นักพัฒนาจำนวนมากเจออุปสรรคเมื่อจำเป็นต้องบรรจุหน้า HTML พร้อมกับ CSS, รูปภาพ, และฟอนต์สำหรับการแจกจ่ายแบบออฟไลน์ และพวกเขามักเขียนโค้ดจัดการไฟล์แบบ ad‑hoc ที่เร็ว ๆ นี้กลายเป็นความยุ่งยากในการบำรุงรักษา + +ในบทแนะนำนี้ เราจะแก้ปัญหานั้นโดยแสดงวิธีที่สะอาดและนำกลับมาใช้ใหม่ได้ที่ **saves HTML as a ZIP archive** ด้วยการใช้ `ResourceHandler` ของ Aspose.HTML เราจะพูดถึงวิธี **convert HTML to ZIP** อีกด้วย และแม้กระทั่งสาธิตรูปแบบที่คุณสามารถนำกลับมาใช้เพื่อ **create ZIP from HTML** ในโครงการ .NET ใด ๆ ไม่มีสคริปต์ภายนอก ไม่มีโฟลเดอร์ชั่วคราว—เพียงแค่ C# แท้ ๆ + +เมื่อจบคู่มือ คุณจะมีตัวอย่างที่พร้อมรันซึ่งสร้างไฟล์ `result.zip` ที่บรรจุทรัพยากรที่เชื่อมโยงทั้งหมด พร้อมกับเคล็ดลับเชิงปฏิบัติบางอย่างที่คุณสามารถนำไปใช้ในโครงการของคุณเอง + +## ข้อกำหนดเบื้องต้น + +- .NET 6+ (โค้ดยังทำงานบน .NET Framework 4.7.2 ด้วย แต่เราแนะนำให้ใช้ SDK ล่าสุด) +- Aspose.HTML for .NET NuGet package (`Aspose.HTML`) – install via `dotnet add package Aspose.HTML` +- ความคุ้นเคยพื้นฐานกับ streams และ namespace `System.IO.Compression` +- IDE หรือ editor ที่คุณเลือก (Visual Studio, VS Code, Rider…) + +หากคุณมีส่วนเหล่านี้พร้อมแล้ว ยอดเยี่ยม—ให้เรากระโดดตรงไปยังโค้ดกันเลย หากยังไม่มี ขั้นตอนเพิ่มเติมเพียงบรรทัดเดียวของการติดตั้ง NuGet; ส่วนอื่น ๆ อยู่ในตัวเอง + +## ขั้นตอนที่ 1: สร้างเอกสาร HTML อย่างง่ายในหน่วยความจำ + +ก่อนอื่นเราต้องการอ็อบเจกต์ `HTMLDocument` ที่แสดงถึงหน้าที่เราต้องการบีบอัดเป็น ZIP ในสถานการณ์จริงคุณอาจโหลดจาก URL หรือไฟล์ แต่เพื่อความชัดเจนเราจะสร้างเอกสารขนาดเล็กแบบอินไลน์ + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** +> การเก็บเอกสารในหน่วยความจำช่วยหลีกเลี่ยงการทำ I/O ของไฟล์ระหว่างขั้นตอน ซึ่งทำให้ขั้นตอน **convert html to zip** ต่อมารวดเร็วและปลอดภัยต่อเธรด + +## ขั้นตอนที่ 2: เตรียมสตรีม ZIP ในหน่วยความจำ + +แทนการเขียนไฟล์ `.zip` ชั่วคราวลงดิสก์ เราจะใช้ `MemoryStream` ซึ่งทำให้ทุกอย่างอยู่ใน RAM เหมาะสำหรับเว็บเซอร์วิสหรืองานเบื้องหลังที่ต้องส่งอาร์ไคฟ์โดยตรงให้กับไคลเอนต์ + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **เคล็ดลับ:** คำสั่ง `using` ทำให้สตรีมถูกทำลายโดยอัตโนมัติ ป้องกันการรั่วของหน่วยความจำ + +## ขั้นตอนที่ 3: สร้าง Custom ResourceHandler + +Aspose.HTML จะเรียก `ResourceHandler` สำหรับทุกแอสเซ็ตภายนอกที่มันพบ (ไฟล์ CSS, รูปภาพ, ฟอนต์ ฯลฯ) โดยการสืบทอด `ResourceHandler` เราสามารถกำหนดได้ว่าแต่ละทรัพยากรจะไปอยู่ที่ไหน—ในกรณีของเรา จะเป็นรายการภายในไฟล์ ZIP + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### ทำไมต้องใช้ Custom Handler? + +- **Control over naming** – คุณกำหนดว่าชื่อไฟล์แต่ละไฟล์จะปรากฏอย่างไรในอาร์ไคฟ์ +- **No temporary files** – handler จะเขียนตรงเข้า ZIP ในหน่วยความจำ +- **Reusability** – คุณสามารถนำคลาสนี้ไปใช้ในโครงการใดก็ได้ที่ต้องการ **save html as zip** + +## ขั้นตอนที่ 4: บันทึกเอกสาร HTML ด้วย Handler + +ตอนนี้เราจะเชื่อมทุกอย่างเข้าด้วยกัน เมธอด `Save` จะเรียก `HandleResource` สำหรับทุกแอสเซ็ตที่เชื่อมโยง และ handler จะสตรีมไบต์เหล่านั้นเข้าไปใน ZIP ที่เราสร้างไว้ก่อนหน้า + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **อะไรเกิดขึ้นภายใน?** +> Aspose ทำการพาร์ส HTML, ค้นพบการอ้างอิง ``, ขอสตรีมจาก handler, และ handler สร้างรายการ `logo.png` ภายใน ZIP กระบวนการเดียวกันจะทำซ้ำสำหรับ CSS, ฟอนต์ หรือแอสเซ็ตภายนอกอื่น ๆ + +## ขั้นตอนที่ 5: บันทึก ZIP ลงดิสก์ (หรือส่งกลับ) + +สุดท้ายเราจะเขียนอาร์ไคฟ์ในหน่วยความจำลงไฟล์ ในเว็บ API คุณอาจส่งคืน `zipMemoryStream.ToArray()` เป็นอาร์เรย์ของไบต์แทน + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### ผลลัพธ์ที่คาดหวัง + +เปิด `result.zip` แล้วคุณควรเห็น: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +หากคุณเปิดอาร์ไคฟ์ในตัวสำรวจไฟล์ คุณจะสังเกตว่าไฟล์ HTML ถูกเก็บเป็น `resource.bin` เนื่องจากเราไม่ได้ตั้งชื่อที่เป็นมิตร คุณสามารถปรับปรุงได้ง่ายโดยตรวจสอบ `resourceInfo.ContentType` และกำหนด `.html` เมื่อเหมาะสม + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรมที่พร้อมคัดลอก‑วางครบถ้วนซึ่งรวมทุกขั้นตอนข้างต้น เรียกใช้จากแอปคอนโซลและคุณจะได้ไฟล์ ZIP พร้อมแชร์ + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**การรันโค้ดนี้** จะสร้าง `result.zip` ในไดเรกทอรีทำงานของโปรแกรม เปิดไฟล์และคุณจะพบ `index.html` (หน้าต้นฉบับของเรา) พร้อมกับ `logo.png` หากภาพนั้นมีอยู่บนดิสก์หรือถูกดึงจาก URL + +## ความแปรผันทั่วไปและกรณีขอบ + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/turkish/net/generate-jpg-and-png-images/_index.md index a918363c4..cbc47dcdd 100644 --- a/html/turkish/net/generate-jpg-and-png-images/_index.md +++ b/html/turkish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ HTML belgelerini düzenlemek, HTML'yi resimlere dönüştürmek ve daha fazlası DOCX belgelerini PNG veya JPG formatına dönüştürürken antialiasing'i etkinleştirerek daha net ve pürüzsüz görüntüler elde edin. ### [docx'i png'ye dönüştür – zip arşivi oluşturma C# eğitimi](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# kullanarak docx dosyalarını png formatına dönüştürüp, sonuçları zip arşivi içinde paketlemeyi öğrenin. +### [HTML'den PNG Oluşturun – C# Geliştiricileri için Adım‑Adım Kılavuz](./create-png-from-html-step-by-step-guide-for-c-developers/) +HTML içeriğini PNG formatına dönüştürmek için C# geliştiricilerine yönelik adım adım bir eğitim. ## Çözüm diff --git a/html/turkish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/turkish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..f08fef4f5 --- /dev/null +++ b/html/turkish/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Aspose.HTML ile HTML'den hızlıca PNG oluşturun. HTML'yi PNG'ye nasıl + render edeceğinizi, tuval boyutunu nasıl ayarlayacağınızı, arka plan rengini nasıl + ekleyeceğinizi öğrenin ve render edilen görüntüyü dakikalar içinde kaydedin. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: tr +og_description: Aspose.HTML ile HTML'den PNG oluşturun. Bu kılavuz, HTML'yi PNG'ye + nasıl render edeceğinizi, tuval boyutunu nasıl ayarlayacağınızı, arka plan rengini + nasıl ekleyeceğinizi ve render edilen görüntüyü nasıl kaydedeceğinizi gösterir. +og_title: HTML'den PNG Oluştur – Tam C# Renderleme Öğretisi +tags: +- C# +- Aspose.HTML +- Image Rendering +title: HTML'den PNG Oluşturma – C# Geliştiricileri için Adım Adım Rehber +url: /tr/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'den PNG Oluşturma – Tam C# Render Öğreticisi + +HTML'den **PNG oluşturma** ihtiyacı hiç duydunuz mu ama hangi kütüphanenin net, anti-aliaslı sonuçlar vereceğinden emin değildiniz? Yalnız değilsiniz. Birçok web‑to‑image işlem hattında en büyük sorun, metin ve grafikleri tarayıcıdaki kadar keskin gösterebilmektir. + +İyi haber? Aspose.HTML ile **HTML'yi PNG'ye render** edebilirsiniz, birkaç satır kodla, tuval (canvas) boyutunu kontrol edebilir, katı bir arka plan rengi ekleyebilir ve sonunda **render edilen görüntüyü** diske **kaydedebilirsiniz**—tarayıcıya dokunmadan. Bu öğreticide tüm süreci adım adım inceleyecek, her ayarın neden önemli olduğunu açıklayacak ve çalıştırmaya hazır bir örnek göstereceğiz. + +## Öğrenecekleriniz + +- HTML'yi bir dizeden, dosyadan veya URL'den nasıl yükleyeceğiniz +- **set canvas size** ve **add background color** ayarlarını nasıl yapılandıracağınız, tutarlı çıktı elde etmek için +- Keskin başlıklar için anti-aliasing ve alt‑piksel metin ipuçlarını etkinleştirme +- **render edilen görüntüyü** PNG dosyası olarak **kaydetmek** için kesin adımlar +- Farklı senaryolar için yaygın tuzaklar ve isteğe bağlı ayarlamalar + +Aspose.HTML ile ilgili önceden bir deneyim gerekmez; sadece temel bir C# kurulumu ve Visual Studio (veya tercih ettiğiniz IDE) yeterlidir. + +--- + +## Adım 1: .NET için Aspose.HTML'i Kurun + +Kod yazmadan önce, Aspose.HTML NuGet paketinin projenizde referans edildiğinden emin olun. + +```bash +dotnet add package Aspose.HTML +``` + +> **Pro ipucu:** En yeni render motoru ve hata düzeltmelerini almak için (Nisan 2026 itibarıyla, 23.9.0) en son kararlı sürümü kullanın. + +--- + +## Adım 2: HTML Kaynağını Yükleyin – HTML'den PNG Oluşturma + +Render'a satır içi bir dize, yerel bir dosya veya uzak bir URL besleyebilirsiniz. Bu demo için özel bir font içeren basit bir satır içi dize kullanacağız. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Neden önemli:** `HTMLDocument` içine HTML yüklemek, motorun DOM ayrıştırması, CSS kademesi ve yerleşim hesaplamaları üzerinde tam kontrol sahibi olmasını sağlar. Ayrıca render'ı dış tarayıcı durumlarından izole eder, tekrarlanabilir sonuçlar elde edilmesini garantiler. + +--- + +## Adım 3: Render Seçeneklerini Yapılandırın – Tuval Boyutunu Ayarlayın ve Arka Plan Rengini Ekleyin + +`ImageRenderingOptions` sınıfı, çıktı görüntüsünü ince ayar yapmanıza olanak tanır. Burada anti-aliasing'i etkinleştirecek, beyaz bir arka plan ayarlayacak ve **800 × 600 px** boyutunda bir tuval tanımlayacağız. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Bu değerleri neden değiştirebilirsiniz:** + +- **Canvas size (Tuval boyutu):** Küçük bir önizleme gerekiyorsa boyutları küçültün; **yüksek çözünürlüklü baskılar** için artırın. +- **Background color (Arka plan rengi):** Şeffaf PNG'ler mümkün, ancak birçok sonraki araç (ör. PowerPoint) opak bir **arka plan** bekler. + +--- + +## Adım 4: Render Et ve **Render Edilen Görüntüyü** PNG Olarak **Kaydet** + +Şimdi zor iş gerçekleşiyor. `ImageRenderer`, `HTMLDocument` ve az önce tanımladığımız seçenekleri kullanarak bir PNG akışı oluşturur ve diske yazar. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Programı çalıştırdığınızda, masaüstünüzde `result.png` dosyasını bulacaksınız. Açın ve beyaz bir tuval üzerinde ortalanmış, temiz ve anti-aliaslı bir başlık görmelisiniz. + +> **Beklenen çıktı:** Beyaz arka planlı, 800 × 600 boyutunda bir PNG ve Arial ile render edilmiş “Antialiased Heading” metni, Chrome'da olduğu gibi pürüzsüz görünür. + +--- + +## Adım 5: Sonucu Doğrulayın – Hızlı Kontroller + +1. **Dosya varlığı:** `File.Exists(outputPath)` `true` döndürmelidir. +2. **Boyutlar:** PNG'yi herhangi bir görüntü görüntüleyicide açın; 800 × 600 px rapor etmelidir. +3. **Görsel kalite:** %200 yakınlaştırın – metin kenarları pürüzsüz kalmalı, tırtıklı olmamalıdır. + +Bir şey yanlış görünüyorsa, `UseAntialiasing` ve `UseHinting`'in her ikisinin de `true` olarak ayarlandığını iki kez kontrol edin. Bu iki bayrak yüksek kaliteli render için gizli sosdur. + +--- + +## Yaygın Varyasyonlar ve Kenar Durumları + +| Senaryo | Ne Ayarlanmalı | Neden | +|----------|----------------|-----| +| **Uzak bir web sayfası render et** | `new HTMLDocument(htmlContent)` yerine `new HTMLDocument("https://example.com")` kullanın | HTML'yi manuel olarak kopyalamadan canlı siteleri yakalamanızı sağlar. | +| **Şeffaf arka plan** | `BackgroundColor = Color.Transparent` ayarlayın ve `ImageFormat.Png` kullanın | PNG'yi diğer grafiklerin üzerine bindirmek için faydalıdır. | +| **Farklı görüntü formatı** | `renderer.Save(pngStream, ImageFormat.Jpeg)` olarak değiştirin | JPEG fotoğraf içeriği için daha küçük olabilir, ancak kayıpsız kaliteyi kaybeder. | +| **Dinamik tuval boyutu** | Yerleşim sonrası `imgOptions.Width = htmlDoc.Body.ClientWidth;` kullanın | Görüntünün HTML içeriğinin doğal genişliğine uymasını sağlar. | +| **Yüksek DPI çıktısı** | `Width` ve `Height` değerlerini bir ölçek faktörüyle (ör. 2) çarpın | Modern ekranlar için retina‑hazır varlıklar üretir. | + +--- + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Programı çalıştırın (`dotnet run` veya Visual Studio'da F5 tuşuna basın) ve e-postalar, raporlar veya HTML'nin statik bir görüntüsüne ihtiyaç duyduğunuz herhangi bir yerde kullanıma hazır, mükemmel render edilmiş bir PNG elde edeceksiniz. + +--- + +## Sık Sorulan Sorular + +**S: Bu, flexbox gibi CSS 3 özellikleriyle çalışır mı?** +**C:** Evet. Aspose.HTML çoğu modern CSS'i destekler, flexbox, grid ve media queries dahil. En son kütüphane sürümünü kullandığınızdan emin olun. + +**S: HTML'm dış resimlere referans veriyorsa ne olur?** +**C:** Render, belgenin temel URI'sine göre göreceli URL'leri izler. HTML'yi bir dizeden yüklüyorsanız, `doc.BaseUrl`'i varlıkların bulunduğu klasöre ayarlayın. + +**S: Birden fazla sayfayı tek PNG'ye render edebilir miyim?** +**C:** Doğrudan değil—her `ImageRenderer` çağrısı tek bir raster görüntü üretir. Çok sayfalı çıktı için, her sayfayı ayrı ayrı render edip bir grafik kütüphanesi (ör. ImageSharp) ile birleştirmeniz gerekir. + +--- + +## Sonuç + +Artık Aspose.HTML kullanarak **HTML'den PNG oluşturma** için sağlam, uçtan uca bir çözümünüz var. **render html to png** seçeneklerini—ör. **set canvas size**, **add background color** ve anti-aliasing'i etkinleştirerek—yapılandırarak tarayıcı olmadan profesyonel kalitede görüntüler üretebilirsiniz. + +Bu noktadan itibaren daha yüksek DPI, şeffaf arka planlar veya onlarca HTML snippet'ını toplu işleme deneyebilirsiniz. Aynı desen, bir önizleme hizmeti, PDF üretim hattı veya statik site önizleme aracı oluştururken de geçerlidir. + +Keyifli render'lar, ve herhangi bir sorunla karşılaşırsanız yorum bırakmaktan çekinmeyin! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/turkish/net/html-document-manipulation/_index.md index f736f400d..ed6f123a8 100644 --- a/html/turkish/net/html-document-manipulation/_index.md +++ b/html/turkish/net/html-document-manipulation/_index.md @@ -71,6 +71,7 @@ Aspose.HTML for .NET kullanarak dinamik ve web içerikleri oluşturmayı öğren Aspose.HTML for .NET ile web geliştirmenin potansiyelini açığa çıkarın. HTML belgelerini kolayca oluşturun, dönüştürün ve düzenleyin. ### [C#'ta Dizeden HTML Oluşturma – Özel Kaynak İşleyici Rehberi](./create-html-from-string-in-c-custom-resource-handler-guide/) C# içinde dizeden HTML oluşturmayı ve özel kaynak işleyicisiyle nasıl kullanacağınızı öğrenin. +### [Programlı Olarak Yazı Tipi Stilini Uygulama – Hızlı C# Rehberi](./apply-font-style-programmatically-quick-c-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/turkish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..fddafc9cd --- /dev/null +++ b/html/turkish/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-04-23 +description: Yazı tipi stilini programlı olarak uygulayın ve metinden alt çizgiyi + kaldırmayı, metin stilini değiştirmeyi ve kalın metin ayarlamayı kısa bir öğreticide + öğrenin. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: tr +og_description: Yazı tipi stilini programatik olarak uygulayın ve kısa, pratik bir + öğreticide metinden alt çizgiyi kaldırmayı, metin stilini değiştirmeyi ve kalın + metin ayarlamayı keşfedin. +og_title: Yazı Tipi Stilini Programlı Olarak Uygula – Hızlı C# Rehberi +tags: +- csharp +- ui +- text-formatting +- programming +title: Yazı Tipi Stilini Programatik Olarak Uygula – Hızlı C# Kılavuzu +url: /tr/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Font Stilini Programatik Olarak Uygula – Hızlı C# Rehberi + +Hiç bir UI öğesine **font stili uygulamak** gerektiğinde nereden başlayacağınızı bilemediniz mi? Tek başınıza değilsiniz—çoğu geliştirici, dinamik metin biçimlendirmeye ilk kez dokunduğunda aynı sorunu yaşar. İyi haber? Birkaç dakika içinde bir etiketin görünümünü nasıl değiştireceğinizi, metinden alt çizgiyi nasıl kaldıracağınızı ve **bold** metni programatik olarak nasıl ayarlayacağınızı sonsuz dokümantasyon içinde kaybolmadan öğreneceksiniz. + +Bu **metin biçimlendirme öğreticisinde** tam çalışan bir örnek üzerinden ilerleyecek, her satırın “neden”ini açıklayacak ve WinForms ya da WPF projenize kopyalayıp‑yapıştırabileceğiniz pratik ipuçları sunacağız. Lafı uzatmadan, işi yapan şeylere odaklanacağız. + +--- + +## Öğrenecekleriniz + +- Küçük bir yardımcı sınıf kullanarak **font stili uygulamayı** nasıl yapacağınız. +- Diğer stilleri korurken **metinden alt çizgiyi kaldırma** adımları. +- Metni anlık olarak (**bold**, *italic*, underline) **değiştirme** yolları. +- **Bold** metni programatik olarak **ayarlayan** tam, kopyalanabilir bir kod parçacığı. +- Daha sonra sürpriz yaşamamanız için yaygın tuzaklar ve kenar‑durum yönetimi. + +**Önkoşullar:** .NET 6+ (veya herhangi bir yeni .NET Framework), temel C# bilgisi ve tercih ettiğiniz IDE (Visual Studio, Rider veya VS Code). Hepsi bu—ekstra NuGet paketi gerekmez. + +--- + +## 1. Adım – Kontrolünüze Font Stili Uygulayın + +Her **apply font style** işleminin temelinde bir `FontStyle` enum’u ve bir `Font` nesnesi bulunur. Kodu düzenli tutmak için bu enum mantığını küçük bir `WebFontStyle` sınıfı içinde paketleyeceğiz. Bu sınıf, orijinal snippet’te gördüğünüz (`Bold`, `Italic`, `Underline`) özellikleri yansıtır ve `Font`’a aktarabileceğiniz bir `FontStyle` değeri üretir. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Neden Önemli:** +Bayrak‑oluşturma mantığını izole ederek UI kodunuzda bit‑wise `|` işlemlerini yaymaktan kaçınırsınız. Daha okunaklı, daha test edilebilir ve —en önemlisi— **apply font style** amacını kristal netliğinde gösterir. + +--- + +## 2. Adım – Metinden Alt Çizgiyi Kaldırın (Diğer Stilleri Koruyarak) + +Diyelim ki, zaten altı çizili bir etikete sahipsiniz, ancak tasarım sadece düz **bold** metin istiyor. Alt çizgiyi kaldırırken **bold** özelliğini kaybetmek istemezsiniz. İşte `WebFontStyle` sınıfının devreye girdiği yer. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Ana nokta:** `Underline = false` ayarlamak, yardımcı sınıfa alt çizgi bayrağını *hariç tut* demektir. Bu satırı tamamen atlamış olsaydınız, önceki alt çizgi kalır ve bu, geliştiricilerin yalnızca `Bold` özelliğini değiştirdiğinde sıkça karşılaştığı bir hatadır. + +--- + +## 3. Adım – Metin Stilini Değiştirin: Bold, Italic ve Daha Fazlası + +Şöyle düşünebilirsiniz: “Peki ya italic’i de açmam gerekirse?” Aynı nesne her kombinasyon için çalışır. Aşağıda kod yazarken başvurabileceğiniz hızlı bir matris bulacaksınız. + +| İstenen Stil | `Bold` | `Italic` | `Underline` | +|--------------|--------|----------|-------------| +| **Sadece Bold** | true | false | false | +| *Sadece Italic* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +İhtiyacınız olan özellikleri ayarlayın ve `ToFont`’u çağırın. Yardımcı sınıf ağır işi sizin yerinize yapar, böylece UI mantığınıza odaklanabilirsiniz. + +--- + +## Tam Örnek – Bold Metni Programatik Olarak Ayarlama + +Aşağıda, **tam, çalıştırılabilir bir WinForms** örneği yer alıyor; burada ele aldığımız tüm konular gösteriliyor. Yeni bir console‑style WinForms projesine yapıştırın ve **F5** tuşuna basın. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Beklenen Sonuç + +Programı çalıştırdığınızda, **“Hello, world!”** metni **bold**, *italic* olmayan ve **alt çizgi içermeyen** bir pencerede görüntülenir. Bu görsel onay, **apply font style** mantığının sorunsuz çalıştığını gösterir. + +--- + +## Pro İpuçları & Kenar Durumları + +- **Dinamik güncellemeler:** Form gösterildikten sonra (ör. bir checkbox’a yanıt olarak) stili değiştirmek isterseniz, `WebFontStyle` örneğini yeniden oluşturun ya da özelliklerini değiştirin ve `lbl.Font`’u yeniden atayın. UI anında güncellenir. +- **Yüksek‑DPI dikkate alımı:** Bir `Font` nesnesi değiştirdiğinizde Windows, mevcut DPI’ye göre otomatik ölçeklendirir. Ölçeklemeyi manuel olarak yönetmediğiniz sürece ekstra kod gerekmez. +- **WPF eşdeğeri:** WPF’de `FontWeight`, `FontStyle` ve `TextDecorations` bağlarsınız, `Font` nesnesi takası yerine. Aynı mantıksal ayrım geçerlidir—stil mantığını görünüm katmanından uzak tutun. +- **Bellek sızıntılarını önleme:** `Label.Font`’u yeniden atamak yeni bir `Font` nesnesi oluşturur. Stil sık sık değiştiriliyorsa eski nesneyi dispose edin: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Sonuç + +Artık herhangi bir .NET kontrolüne **font stili uygulamayı**, **metinden alt çizgiyi kaldırmayı** ve **metin stilini anlık olarak değiştirmeyi** kodunuzu temiz ve yeniden kullanılabilir tutarak biliyorsunuz. Küçük `WebFontStyle` yardımcı sınıfı, birkaç boolean bayrağını sağlam, test edilebilir bir bileşene dönüştürüyor ve tam örnek, sadece birkaç satırla **bold metni programatik olarak ayarlayabileceğinizi** kanıtlıyor. + +Sırada ne var? Bu yaklaşımı kullanıcı‑tabanlı ayarlarla birleştirin ya da `Strikeout` gibi diğer `FontStyle` bayraklarıyla deneyler yapın. Hatta teknik olmayan kullanıcıların çalışma zamanında bold, italic veya underline seçebileceği küçük bir UI paneli bile sunabilirsiniz—yeniden derleme gerekmez. + +Bu **metin biçimlendirme öğreticisinden** faydalandıysanız, bir yorum bırakın ya da kendi varyasyonlarınızı paylaşın. İyi kodlamalar, UI’niz her zaman istediğiniz gibi görünsün! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/turkish/net/html-extensions-and-conversions/_index.md index 8dd996b05..6da32ac65 100644 --- a/html/turkish/net/html-extensions-and-conversions/_index.md +++ b/html/turkish/net/html-extensions-and-conversions/_index.md @@ -66,6 +66,8 @@ Aspose.HTML for .NET ile HTML'yi TIFF'e nasıl dönüştüreceğinizi öğrenin. ### [HTML'den PDF Oluşturma – C# Adım Adım Kılavuz](./create-pdf-from-html-c-step-by-step-guide/) Aspose.HTML for .NET kullanarak HTML'den PDF'ye nasıl dönüştüreceğinizi adım adım öğrenin. ### [C#'ta HTML'i Zip Dosyasına Sıkıştırma](./how-to-zip-html-in-c-save-html-to-zip/) +### [C#'ta HTML'i ZIP'e Sıkıştırma – Özel Kaynak İşleyicisi Rehberi](./how-to-zip-html-in-c-custom-resource-handler-guide/) +C#'ta özel kaynak işleyicisi kullanarak HTML dosyalarını ZIP arşivine nasıl sıkıştıracağınızı adım adım öğrenin. ### [Stil Verilmiş Metinle HTML Belgesi Oluşturma ve PDF'ye Dışa Aktarma – Tam Kılavuz](./create-html-document-with-styled-text-and-export-to-pdf-full/) ### [HTML'yi ZIP Olarak Kaydet – Tam C# Öğreticisi](./save-html-as-zip-complete-c-tutorial/) Aspose.HTML for .NET kullanarak HTML dosyalarını ZIP arşivine kaydetmeyi adım adım öğrenin. diff --git a/html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..96c1ec415 --- /dev/null +++ b/html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-23 +description: Özel bir kaynak işleyicisi kullanarak C#'ta HTML'yi zip'lemeyi öğrenin + – HTML'yi zip olarak kaydetmek, HTML'yi zip'e dönüştürmek ve HTML'den zip oluşturmak + için adım adım rehber. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: tr +og_description: 'C#''ta HTML nasıl ziplenir açıklaması: HTML''yi zip olarak kaydetmek + için özel bir kaynak işleyicisi kullanın, HTML''yi zip''e dönüştürün ve dakikalar + içinde HTML''den zip oluşturun.' +og_title: C#'ta HTML nasıl ziplenir – Özel Kaynak İşleyici Rehberi +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: C#'ta HTML nasıl ziplenir – özel kaynak işleyici rehberi +url: /tr/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'i C#'ta zipleme – özel kaynak işleyici rehberi + +C# kodunuzdan doğrudan **HTML'i ziplemeyi** düşündünüz mü, dosyaları önce diske çekmeden? Tek başınıza değilsiniz. Birçok geliştirici, bir HTML sayfasını CSS, görseller ve fontlarla birlikte çevrim dışı dağıtım için paketlemesi gerektiğinde bir duvara çarpar ve hızla bakım kabusuna dönüşen geçici dosya sistemi kodları yazmak zorunda kalır. + +Bu öğreticide, Aspose.HTML'in `ResourceHandler`'ını kullanarak **HTML'i ZIP arşivi olarak kaydetmeyi** gösteren temiz, yeniden kullanılabilir bir yaklaşım sunarak bu sorunu çözeceğiz. Ayrıca **HTML'i ZIP'e dönüştürmeyi** ele alacak ve .NET projesinde **HTML'den ZIP oluşturmayı** yeniden kullanabileceğiniz bir desen göstereceğiz. Harici betikler, geçici klasörler yok — sadece saf C#. + +Kılavuzun sonunda, her bir bağlı kaynağı içeren bir `result.zip` üreten, hemen çalıştırabileceğiniz bir örnek ve kendi projelerinizde uygulayabileceğiniz birkaç pratik ipucu elde edeceksiniz. + +## Önkoşullar + +- .NET 6+ (kod ayrıca .NET Framework 4.7.2'de çalışır, ancak en yeni SDK'yı öneririz) +- .NET için Aspose.HTML NuGet paketi (`Aspose.HTML`) – `dotnet add package Aspose.HTML` komutuyla kurun +- Akışlar ve `System.IO.Compression` isim alanı hakkında temel bilgi +- Seçtiğiniz bir IDE veya editör (Visual Studio, VS Code, Rider…) + +Bu bileşenler zaten kuruluysa harika—kodun içine doğrudan geçelim. Değilse, tek ek adım bir satırlık NuGet kurulumudur; geri kalan her şey kendi içinde çözülmüş. + +## Adım 1: Bellekte Basit bir HTML Belgesi Oluşturma + +İlk olarak, ziplemek istediğimiz sayfayı temsil eden bir `HTMLDocument` nesnesine ihtiyacımız var. Gerçek bir senaryoda bunu bir URL'den ya da dosyadan yükleyebilirsiniz, ancak açıklık olması için küçük bir belgeyi satır içinde oluşturacağız. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Neden önemli:** +> Belgeyi bellekte tutarak ara dosya G/Ç'sinden kaçınırız, bu da sonraki **HTML'i zip'e dönüştür** adımını hızlı ve iş parçacığı güvenli hâle getirir. + +## Adım 2: Bellek İçinde ZIP Akışı Hazırlama + +Geçici bir `.zip` dosyasını diske yazmak yerine bir `MemoryStream` kullanacağız. Bu, her şeyi RAM'de tutar ve arşivi doğrudan bir istemciye döndürmesi gereken web servisleri ya da arka plan görevleri için idealdir. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **İpucu:** `using` ifadesi akışın otomatik olarak dispose edilmesini sağlar, bellek sızıntılarını önler. + +## Adım 3: Özel Bir ResourceHandler Uygulama + +Aspose.HTML, keşfettiği her dış kaynağa (CSS dosyaları, görseller, fontlar vb.) bir `ResourceHandler` çağırır. `ResourceHandler`'ı alt sınıf olarak tanımlayarak her kaynağın tam olarak nereye konulacağını belirleyebiliriz — bizim durumumuzda ZIP arşivindeki bir giriş olarak. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Neden Özel Bir İşleyici? + +- **Control over naming** – arşivde her dosyanın nasıl görüneceğine siz karar verirsiniz. +- **No temporary files** – işleyici doğrudan bellek içi ZIP'e yazar. +- **Reusability** – bu sınıfı **HTML'i zip olarak kaydet** ihtiyacı olan herhangi bir projeye ekleyebilirsiniz. + +## Adım 4: İşleyiciyi Kullanarak HTML Belgesini Kaydetme + +Şimdi her şeyi birleştiriyoruz. `Save` yöntemi, her bağlı varlık için `HandleResource`'u çağıracak ve işleyici bu baytları daha önce oluşturduğumuz ZIP arşivine akıtacak. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **Arka planda ne olur?** +> Aspose HTML'i ayrıştırır, `` referansını bulur, işleyiciden bir akış ister ve işleyici ZIP içinde bir `logo.png` girişi oluşturur. Aynı akış CSS, fontlar veya diğer dış kaynaklar için de tekrarlanır. + +## Adım 5: ZIP Arşivini Diske Kaydetme (veya Döndürme) + +Son olarak, bellek içi arşivi bir dosyaya yazarız. Bir web API'sinde bunun yerine `zipMemoryStream.ToArray()`'ı bir bayt dizisi olarak döndürebilirsiniz. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Beklenen Sonuç + +`result.zip` dosyasını açın ve şunları görmelisiniz: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Arşivi bir dosya gezginiyle açarsanız, HTML dosyasının `resource.bin` olarak depolandığını fark edersiniz çünkü ona dostça bir ad vermedik. Bunu, `resourceInfo.ContentType` kontrol edip uygun olduğunda `.html` atayarak kolayca iyileştirebilirsiniz. + +## Tam Çalışan Örnek + +Aşağıda, yukarıdaki tüm adımları içeren, kopyala‑yapıştır hazır tam program bulunmaktadır. Bir konsol uygulamasından çalıştırın ve paylaşmaya hazır bir ZIP dosyası elde edin. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Bu kodu çalıştırmak**, programın çalışma dizininde `result.zip` oluşturur. Açtığınızda `index.html` (orijinal sayfamız) ve eğer varsa `logo.png` dosyasını bulacaksınız; bu görsel diskte mevcutsa ya da bir URL'den alınmışsa. + +## Yaygın Varyasyonlar ve Kenar Durumları + +| Scenario + +{{< /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/generate-jpg-and-png-images/_index.md b/html/vietnamese/net/generate-jpg-and-png-images/_index.md index 364f75161..6afbbd622 100644 --- a/html/vietnamese/net/generate-jpg-and-png-images/_index.md +++ b/html/vietnamese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Học cách sử dụng Aspose.HTML cho .NET để thao tác với các tài li Hướng dẫn chi tiết cách bật khử răng cưa để cải thiện chất lượng hình ảnh khi chuyển đổi tài liệu DOCX sang PNG hoặc JPG bằng Aspose.HTML. ### [Chuyển đổi DOCX sang PNG – tạo tệp ZIP bằng C# – Hướng dẫn](./convert-docx-to-png-create-zip-archive-c-tutorial/) Hướng dẫn cách chuyển đổi tài liệu DOCX thành hình ảnh PNG và đóng gói chúng vào tệp ZIP bằng C#. +### [Tạo PNG từ HTML – Hướng dẫn từng bước cho nhà phát triển C#](./create-png-from-html-step-by-step-guide-for-c-developers/) +Hướng dẫn chi tiết cách tạo tệp PNG từ HTML bằng Aspose.HTML cho .NET, dành cho lập trình viên C#. ## Phần kết luận diff --git a/html/vietnamese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md b/html/vietnamese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md new file mode 100644 index 000000000..d1ced136c --- /dev/null +++ b/html/vietnamese/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-04-23 +description: Tạo PNG từ HTML nhanh chóng với Aspose.HTML. Tìm hiểu cách chuyển đổi + HTML sang PNG, thiết lập kích thước canvas, thêm màu nền và lưu hình ảnh đã render + trong vài phút. +draft: false +keywords: +- create png from html +- render html to png +- save rendered image +- set canvas size +- add background color +language: vi +og_description: Tạo PNG từ HTML bằng Aspose.HTML. Hướng dẫn này chỉ cách chuyển đổi + HTML sang PNG, thiết lập kích thước canvas, thêm màu nền và lưu ảnh đã render. +og_title: Tạo PNG từ HTML – Hướng dẫn đầy đủ về Render C# +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Tạo PNG từ HTML – Hướng dẫn từng bước cho các nhà phát triển C# +url: /vi/net/generate-jpg-and-png-images/create-png-from-html-step-by-step-guide-for-c-developers/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo PNG từ HTML – Hướng dẫn Kết xuất C# đầy đủ + +Bạn đã bao giờ cần **tạo PNG từ HTML** nhưng không chắc thư viện nào sẽ cho bạn kết quả sắc nét, khử răng cưa? Bạn không phải là người duy nhất. Trong nhiều quy trình chuyển web sang hình ảnh, điểm đau lớn nhất là làm cho văn bản và đồ họa trông sắc nét như trong trình duyệt. + +Tin tốt? Với Aspose.HTML, bạn có thể **kết xuất HTML thành PNG** chỉ trong vài dòng mã, kiểm soát kích thước canvas, thêm màu nền đặc, và cuối cùng **lưu hình ảnh đã kết xuất** vào đĩa—tất cả mà không cần mở trình duyệt. Trong hướng dẫn này, chúng tôi sẽ đi qua toàn bộ quy trình, giải thích lý do mỗi thiết lập quan trọng, và cho bạn một ví dụ sẵn sàng chạy. + +## Những gì bạn sẽ học + +- Cách tải HTML từ chuỗi, tệp hoặc URL +- Cách cấu hình **set canvas size** và **add background color** để có đầu ra dự đoán được +- Bật antialiasing và sub‑pixel text hinting cho các tiêu đề siêu sắc nét +- Các bước chính xác để **save rendered image** dưới dạng tệp PNG +- Các lỗi thường gặp và các điều chỉnh tùy chọn cho các kịch bản khác nhau + +Không cần kinh nghiệm trước với Aspose.HTML; chỉ cần một môi trường C# cơ bản và Visual Studio (hoặc IDE yêu thích của bạn). + +--- + +## Bước 1: Cài đặt Aspose.HTML cho .NET + +Trước khi viết bất kỳ mã nào, hãy chắc chắn rằng gói NuGet Aspose.HTML đã được tham chiếu trong dự án của bạn. + +```bash +dotnet add package Aspose.HTML +``` + +> **Mẹo chuyên nghiệp:** Sử dụng phiên bản ổn định mới nhất (tính đến tháng 4 2026, 23.9.0) để có engine kết xuất mới nhất và các bản sửa lỗi. + +--- + +## Bước 2: Tải nguồn HTML – Tạo PNG từ HTML + +Bạn có thể cung cấp cho bộ kết xuất một chuỗi nội tuyến, một tệp cục bộ, hoặc một URL từ xa. Trong bản demo này, chúng tôi sẽ sử dụng một chuỗi nội tuyến đơn giản chứa tiêu đề với phông chữ tùy chỉnh. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // For Color +using System.IO; // For FileStream + +// Inline HTML – feel free to replace this with your own markup +string htmlContent = @" + + +

Antialiased Heading

+ +"; + +// Create the HTMLDocument object – this is the source for rendering +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Tại sao điều này quan trọng:** Việc tải HTML vào một `HTMLDocument` cho phép engine kiểm soát toàn bộ quá trình phân tích DOM, cascade CSS và tính toán bố cục. Nó cũng tách việc kết xuất khỏi bất kỳ trạng thái trình duyệt bên ngoài nào, đảm bảo kết quả có thể tái tạo. + +--- + +## Bước 3: Cấu hình tùy chọn kết xuất – Đặt kích thước Canvas & Thêm màu nền + +Lớp `ImageRenderingOptions` cho phép bạn tinh chỉnh hình ảnh đầu ra. Ở đây chúng tôi sẽ bật antialiasing, đặt nền trắng, và xác định rõ một canvas có kích thước **800 × 600 px**. + +```csharp +// Step 3: Set up image rendering options +ImageRenderingOptions imgOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // Smoother edges for graphics and text + BackgroundColor = Color.White, // Guarantees a non‑transparent background + Width = 800, // set canvas size – width in pixels + Height = 600 // set canvas size – height in pixels +}; + +// Enable sub‑pixel text hinting for sharper glyphs +TextOptions txtOpts = new TextOptions { UseHinting = true }; +imgOptions.TextOptions = txtOpts; +``` + +**Tại sao bạn có thể thay đổi các giá trị này:** +- **Canvas size:** Nếu bạn cần một hình thu nhỏ, hãy giảm kích thước; đối với bản in độ phân giải cao, hãy tăng chúng. +- **Background color:** PNG trong suốt là khả thi, nhưng nhiều công cụ downstream (ví dụ, PowerPoint) mong đợi nền không trong suốt. + +--- + +## Bước 4: Kết xuất và **Save Rendered Image** dưới dạng PNG + +Bây giờ công việc nặng nhọc diễn ra. `ImageRenderer` tiêu thụ `HTMLDocument` và các tùy chọn chúng ta vừa định nghĩa, sau đó ghi một luồng PNG vào đĩa. + +```csharp +// Step 4: Render HTML to PNG and save it +using (var renderer = new ImageRenderer(htmlDoc, imgOptions)) +{ + // Adjust the path to where you want the file saved + string outputPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var pngStream = new FileStream(outputPath, FileMode.Create)) + { + renderer.Save(pngStream, ImageFormat.Png); + } +} +``` + +Khi bạn chạy chương trình, bạn sẽ thấy `result.png` trên desktop. Mở nó, và bạn sẽ thấy một tiêu đề sạch sẽ, đã được khử răng cưa, nằm ở trung tâm trên nền trắng. + +> **Kết quả mong đợi:** Một PNG 800 × 600 với nền trắng và văn bản “Antialiased Heading” được kết xuất bằng Arial, trông mượt như trong Chrome. + +--- + +## Bước 5: Xác minh kết quả – Kiểm tra nhanh + +1. **File existence:** `File.Exists(outputPath)` nên trả về `true`. +2. **Dimensions:** Mở PNG trong bất kỳ trình xem ảnh nào; nó nên báo 800 × 600 px. +3. **Visual quality:** Phóng to 200 % – các cạnh văn bản phải vẫn mượt, không bị răng cưa. + +Nếu có gì không ổn, hãy kiểm tra lại rằng `UseAntialiasing` và `UseHinting` đều được đặt thành `true`. Hai cờ này là bí quyết cho việc kết xuất chất lượng cao. + +--- + +## Các biến thể phổ biến & Trường hợp đặc biệt + +| Scenario | What to Adjust | Why | +|----------|----------------|-----| +| **Kết xuất một trang web từ xa** | Thay thế `new HTMLDocument(htmlContent)` bằng `new HTMLDocument("https://example.com")` | Cho phép bạn chụp các trang web trực tiếp mà không cần sao chép HTML thủ công. | +| **Nền trong suốt** | Đặt `BackgroundColor = Color.Transparent` và sử dụng `ImageFormat.Png` | Hữu ích khi chồng PNG lên các đồ họa khác. | +| **Định dạng ảnh khác** | Thay đổi `renderer.Save(pngStream, ImageFormat.Jpeg)` | JPEG có thể nhỏ hơn cho nội dung ảnh, nhưng mất chất lượng không mất mát. | +| **Kích thước canvas động** | Sử dụng `imgOptions.Width = htmlDoc.Body.ClientWidth;` sau khi bố trí | Cho phép hình ảnh khớp với chiều rộng tự nhiên của nội dung HTML. | +| **Đầu ra High‑DPI** | Nhân `Width` và `Height` với một hệ số tỷ lệ (ví dụ, 2) | Tạo ra các tài nguyên sẵn sàng cho màn hình retina trên các thiết bị hiện đại. | + +--- + +## Ví dụ Hoạt động đầy đủ (Sẵn sàng sao chép‑dán) + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Load HTML – you can also load from file or URL + string html = @" + + +

Antialiased Heading

+ + "; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Configure rendering – set canvas size & background + ImageRenderingOptions options = new ImageRenderingOptions + { + UseAntialiasing = true, + BackgroundColor = Color.White, + Width = 800, + Height = 600 + }; + options.TextOptions = new TextOptions { UseHinting = true }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var renderer = new ImageRenderer(doc, options)) + { + string outPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + "result.png"); + + using (var stream = new FileStream(outPath, FileMode.Create)) + { + renderer.Save(stream, ImageFormat.Png); + } + + Console.WriteLine($"✅ PNG saved to: {outPath}"); + } + } +} +``` + +Chạy chương trình (`dotnet run` hoặc nhấn F5 trong Visual Studio) và bạn sẽ có một PNG được kết xuất hoàn hảo, sẵn sàng sử dụng trong email, báo cáo, hoặc bất kỳ nơi nào bạn cần một hình ảnh tĩnh của HTML. + +--- + +## Câu hỏi thường gặp + +**Q: Điều này có hoạt động với các tính năng CSS 3 như flexbox không?** +A: Có. Aspose.HTML hỗ trợ hầu hết các CSS hiện đại, bao gồm flexbox, grid và media queries. Chỉ cần đảm bảo bạn đang dùng phiên bản thư viện mới nhất. + +**Q: Nếu HTML của tôi tham chiếu đến hình ảnh bên ngoài thì sao?** +A: Bộ kết xuất sẽ theo các URL tương đối dựa trên base URI của tài liệu. Nếu bạn tải HTML từ một chuỗi, hãy đặt `doc.BaseUrl` thành thư mục chứa các tài nguyên. + +**Q: Tôi có thể kết xuất nhiều trang thành một PNG không?** +A: Không trực tiếp—mỗi lần gọi `ImageRenderer` tạo ra một hình raster duy nhất. Đối với đầu ra đa trang, hãy kết xuất từng trang riêng biệt và ghép chúng lại bằng một thư viện đồ họa (ví dụ, ImageSharp). + +--- + +## Kết luận + +Bạn giờ đã có một giải pháp toàn diện, đầu‑cuối để **tạo PNG từ HTML** bằng Aspose.HTML. Bằng cách cấu hình các tùy chọn **render html to png**—như **set canvas size**, **add background color**, và bật antialiasing—bạn có thể tạo ra các hình ảnh chất lượng chuyên nghiệp mà không cần trình duyệt. + +Từ đây, bạn có thể thử nghiệm với DPI cao hơn, nền trong suốt, hoặc xử lý hàng chục đoạn HTML theo lô. Mẫu tương tự áp dụng cho dù bạn đang xây dựng dịch vụ tạo thumbnail, pipeline tạo PDF, hoặc công cụ xem trước site tĩnh. + +Chúc bạn kết xuất vui vẻ, và đừng ngần ngại để lại bình luận nếu gặp bất kỳ khó khăn nào! 🚀 + +{{< /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/html-document-manipulation/_index.md b/html/vietnamese/net/html-document-manipulation/_index.md index 69f32029f..9c738b327 100644 --- a/html/vietnamese/net/html-document-manipulation/_index.md +++ b/html/vietnamese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Học cách sử dụng Aspose.HTML cho .NET. Nhập không gian tên, hợp nh Mở khóa tiềm năng phát triển web với Aspose.HTML cho .NET. Tạo, chuyển đổi và thao tác tài liệu HTML dễ dàng. ### [Tạo HTML từ chuỗi trong C# – Hướng dẫn Trình xử lý tài nguyên tùy chỉnh](./create-html-from-string-in-c-custom-resource-handler-guide/) Tìm hiểu cách tạo tài liệu HTML từ chuỗi trong C# bằng trình xử lý tài nguyên tùy chỉnh của Aspose.HTML. +### [Áp dụng kiểu phông chữ bằng lập trình – Hướng dẫn nhanh C#](./apply-font-style-programmatically-quick-c-guide/) +Hướng dẫn nhanh cách áp dụng kiểu phông chữ trong tài liệu HTML bằng C# sử dụng Aspose.HTML. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/vietnamese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md b/html/vietnamese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md new file mode 100644 index 000000000..e330b4491 --- /dev/null +++ b/html/vietnamese/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-04-23 +description: Áp dụng kiểu phông chữ bằng lập trình và học cách xóa gạch chân, thay + đổi kiểu chữ và đặt chữ in đậm bằng lập trình trong một hướng dẫn ngắn gọn. +draft: false +keywords: +- apply font style +- remove underline from text +- change text style +- text formatting tutorial +- set bold text programmatically +language: vi +og_description: Áp dụng kiểu phông chữ bằng lập trình và khám phá cách xóa gạch chân + khỏi văn bản, thay đổi kiểu chữ và đặt chữ in đậm bằng lập trình trong một hướng + dẫn ngắn gọn, thực tế. +og_title: Áp dụng kiểu phông chữ bằng lập trình – Hướng dẫn nhanh C# +tags: +- csharp +- ui +- text-formatting +- programming +title: Áp dụng kiểu phông chữ bằng lập trình – Hướng dẫn nhanh C# +url: /vi/net/html-document-manipulation/apply-font-style-programmatically-quick-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Áp dụng kiểu phông chữ bằng mã – Hướng dẫn nhanh C# + +Bạn đã bao giờ cần **áp dụng kiểu phông chữ** cho một phần tử UI nhưng không biết bắt đầu từ đâu? Bạn không phải là người duy nhất—hầu hết các nhà phát triển đều gặp khó khăn này khi lần đầu làm việc với định dạng văn bản động. Tin tốt là gì? Chỉ trong vài phút, bạn sẽ biết chính xác cách thay đổi giao diện của một label, loại bỏ gạch chân khỏi văn bản, và đặt văn bản in đậm bằng mã mà không phải lục lọi tài liệu vô tận. + +Trong **bài hướng dẫn định dạng văn bản** này, chúng tôi sẽ đi qua một ví dụ hoàn chỉnh, có thể chạy được, giải thích “tại sao” mỗi dòng lại cần thiết, và cung cấp các mẹo thực tiễn mà bạn có thể sao chép‑dán vào bất kỳ dự án WinForms hoặc WPF nào. Không có phần thừa, chỉ có những gì giúp bạn hoàn thành công việc. + +--- + +## Những gì bạn sẽ học + +- Cách **áp dụng kiểu phông chữ** bằng một lớp trợ giúp nhỏ. +- Các bước chính xác để **loại bỏ gạch chân khỏi văn bản** trong khi giữ các kiểu khác nguyên vẹn. +- Các cách để **thay đổi kiểu văn bản** (đậm, nghiêng, gạch chân) một cách linh hoạt. +- Một đoạn mã hoàn chỉnh, sẵn sàng sao chép, **đặt văn bản in đậm bằng mã**. +- Những lỗi thường gặp và cách xử lý các trường hợp biên để bạn không bị bất ngờ sau này. + +**Điều kiện tiên quyết:** .NET 6+ (hoặc bất kỳ .NET Framework hiện đại nào), kiến thức cơ bản về C#, và một IDE bạn thích (Visual Studio, Rider, hoặc VS Code). Đó là tất cả—không cần thêm gói NuGet nào. + +--- + +## Bước 1 – Áp dụng kiểu phông chữ cho Control của bạn + +Cốt lõi của bất kỳ thao tác **áp dụng kiểu phông chữ** nào là enum `FontStyle` kết hợp với đối tượng `Font`. Để giữ cho mã gọn gàng, chúng ta sẽ gói logic enum này trong một lớp nhỏ `WebFontStyle`. Lớp này phản ánh các thuộc tính bạn đã thấy trong đoạn mã gốc (`Bold`, `Italic`, `Underline`) và tạo ra giá trị `FontStyle` mà bạn có thể truyền cho `Font`. + +```csharp +using System; +using System.Drawing; + +/// +/// Simple helper that mimics the original WebFontStyle API. +/// It lets you toggle Bold, Italic, and Underline flags and +/// converts the result into a System.Drawing.FontStyle value. +/// +public class WebFontStyle +{ + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + /// + /// Returns a FontStyle that combines the selected flags. + /// + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + /// + /// Creates a new Font based on an existing one but with the + /// updated style. Handy for UI controls that already have a font. + /// + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } +} +``` + +**Tại sao điều này quan trọng:** +Bằng cách tách riêng logic xây dựng cờ, bạn tránh việc rải rác các phép toán bitwise `|` khắp mã UI. Mã sẽ dễ đọc hơn, dễ kiểm thử hơn, và—quan trọng nhất—giúp ý định **áp dụng kiểu phông chữ** trở nên rõ ràng. + +--- + +## Bước 2 – Loại bỏ gạch chân khỏi văn bản (và giữ các kiểu khác) + +Giả sử bạn kế thừa một label đã được gạch chân, nhưng thiết kế yêu cầu chỉ có văn bản in đậm. Bạn không muốn mất độ đậm khi loại bỏ gạch chân. Đây là lúc lớp `WebFontStyle` tỏa sáng. + +```csharp +// Assume we already have a Label named lblSample. +var fontStyle = new WebFontStyle +{ + Bold = true, // Keep bold on. + Italic = false, // No italic needed. + Underline = false // This line **removes underline**. +}; + +// Apply the new Font to the label. +lblSample.Font = fontStyle.ToFont(lblSample.Font); +``` + +**Điểm then chốt:** Đặt `Underline = false` một cách rõ ràng sẽ khiến trợ giúp loại bỏ cờ gạch chân. Nếu bạn bỏ qua dòng này, gạch chân cũ sẽ vẫn tồn tại, đây là nguồn gây lỗi phổ biến khi các nhà phát triển chỉ bật tắt thuộc tính `Bold`. + +--- + +## Bước 3 – Thay đổi kiểu văn bản: Đậm, Nghiêng và hơn thế nữa + +Bạn có thể tự hỏi, “Nếu tôi cần bật/tắt nghiêng thì sao?” Cùng một đối tượng vẫn hoạt động cho bất kỳ tổ hợp nào. Dưới đây là một ma trận nhanh bạn có thể tham khảo khi lập trình. + +| Kiểu mong muốn | `Bold` | `Italic` | `Underline` | +|----------------|--------|----------|-------------| +| **Bold only** | true | false | false | +| *Italic only* | false | true | false | +| **Bold + Italic** | true | true | false | +| **Bold + Underline** | true | false | true | + +Chỉ cần đặt các thuộc tính bạn cần và gọi `ToFont`. Trợ giúp sẽ thực hiện phần nặng cho bạn, để bạn tập trung vào logic UI. + +--- + +## Ví dụ đầy đủ – Đặt văn bản in đậm bằng mã + +Dưới đây là một ví dụ **đầy đủ, có thể chạy** trên WinForms, minh họa mọi thứ chúng ta đã thảo luận. Sao chép nó vào một dự án WinForms kiểu console và nhấn **F5**. + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace FontStyleDemo +{ + static class Program + { + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); // .NET 6+ boilerplate + Application.Run(new DemoForm()); + } + } + + public class DemoForm : Form + { + private readonly Label _sampleLabel; + + public DemoForm() + { + Text = "Apply Font Style Demo"; + Size = new Size(400, 200); + StartPosition = FormStartPosition.CenterScreen; + + _sampleLabel = new Label + { + Text = "Hello, world!", + AutoSize = true, + Location = new Point(20, 30) + }; + Controls.Add(_sampleLabel); + + // STEP: instantiate WebFontStyle and configure it + var fontStyle = new WebFontStyle + { + Bold = true, // set bold text programmatically + Italic = false, // no italic + Underline = false // remove underline from text + }; + + // Apply the new style to the label + _sampleLabel.Font = fontStyle.ToFont(_sampleLabel.Font); + } + } + + // ---- WebFontStyle class from Step 1 (included for completeness) ---- + public class WebFontStyle + { + public bool Bold { get; set; } = false; + public bool Italic { get; set; } = false; + public bool Underline { get; set; } = false; + + public FontStyle ToFontStyle() + { + FontStyle style = FontStyle.Regular; + if (Bold) style |= FontStyle.Bold; + if (Italic) style |= FontStyle.Italic; + if (Underline) style |= FontStyle.Underline; + return style; + } + + public Font ToFont(Font baseFont) + { + return new Font(baseFont, ToFontStyle()); + } + } +} +``` + +### Kết quả mong đợi + +Khi bạn chạy chương trình, một cửa sổ sẽ xuất hiện với văn bản **“Hello, world!”** được hiển thị **đậm**, **không nghiêng**, và **không có gạch chân**. Điều này xác nhận rằng logic **áp dụng kiểu phông chữ** đã hoạt động hoàn hảo. + +--- + +## Mẹo chuyên nghiệp & Các trường hợp biên + +- **Cập nhật động:** Nếu bạn cần thay đổi kiểu sau khi form đã hiển thị (ví dụ, phản hồi một checkbox), chỉ cần tạo lại đối tượng `WebFontStyle` hoặc sửa đổi các thuộc tính và gán lại `lbl.Font`. UI sẽ cập nhật ngay lập tức. +- **Xem xét DPI cao:** Khi bạn thay thế một đối tượng `Font`, Windows sẽ tự động điều chỉnh kích thước dựa trên DPI hiện tại. Không cần mã bổ sung trừ khi bạn tự xử lý scaling. +- **Tương đương WPF:** Trong WPF bạn sẽ bind `FontWeight`, `FontStyle`, và `TextDecorations` thay vì thay đổi đối tượng `Font`. Nguyên tắc tách logic vẫn áp dụng—giữ logic kiểu cách ra khỏi lớp view. +- **Tránh rò rỉ bộ nhớ:** Gán lại `Label.Font` tạo ra một đối tượng `Font` mới. Hãy giải phóng đối tượng cũ nếu bạn thường xuyên thay đổi kiểu: `var oldFont = lbl.Font; lbl.Font = newFont; oldFont.Dispose();` + +--- + +## Kết luận + +Bây giờ bạn đã biết cách **áp dụng kiểu phông chữ** cho bất kỳ control .NET nào, **loại bỏ gạch chân khỏi văn bản**, và **thay đổi kiểu văn bản** một cách linh hoạt—tất cả trong khi giữ mã sạch sẽ và tái sử dụng được. Trợ giúp nhỏ `WebFontStyle` biến một vài cờ boolean thành một thành phần vững chắc, có thể kiểm thử, và ví dụ đầy đủ chứng minh rằng bạn có thể **đặt văn bản in đậm bằng mã** chỉ trong vài dòng. + +Tiếp theo bạn muốn làm gì? Hãy thử kết hợp cách tiếp cận này với các cài đặt do người dùng điều khiển, hoặc khám phá các cờ `FontStyle` khác như `Strikeout`. Bạn thậm chí có thể tạo một panel UI nhỏ cho phép người dùng không chuyên chọn in đậm, nghiêng, hoặc gạch chân tại thời gian chạy—không cần biên dịch lại. + +Nếu bạn thấy **bài hướng dẫn định dạng văn bản** này hữu ích, hãy để lại bình luận hoặc chia sẻ các biến thể của bạn. Chúc lập trình vui vẻ, và mong UI của bạn luôn hiển thị đúng như mong muốn! + +--- + +![Screenshot showing how to apply font style to a label in C#](https://example.com/images/apply-font-style.png + +{{< /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/html-extensions-and-conversions/_index.md b/html/vietnamese/net/html-extensions-and-conversions/_index.md index 169c7624f..11f5236fb 100644 --- a/html/vietnamese/net/html-extensions-and-conversions/_index.md +++ b/html/vietnamese/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Tìm hiểu cách chuyển đổi HTML sang TIFF bằng Aspose.HTML cho .NET. L Khám phá sức mạnh của Aspose.HTML cho .NET: Chuyển đổi HTML sang XPS dễ dàng. Bao gồm các điều kiện tiên quyết, hướng dẫn từng bước và Câu hỏi thường gặp. ### [Cách Nén HTML thành Zip trong C# – Lưu HTML vào Zip](./how-to-zip-html-in-c-save-html-to-zip/) Hướng dẫn chi tiết cách nén HTML thành tệp Zip bằng C# và Aspose.HTML, kèm ví dụ mã và các tùy chọn cấu hình. +### [Cách Nén HTML thành Zip trong C# – Hướng Dẫn Bộ Xử Lý Tài Nguyên Tùy Chỉnh](./how-to-zip-html-in-c-custom-resource-handler-guide/) +Hướng dẫn chi tiết cách nén HTML thành tệp Zip trong C# bằng bộ xử lý tài nguyên tùy chỉnh với Aspose.HTML. ### [Tạo tài liệu HTML với văn bản có kiểu dáng và xuất ra PDF – Hướng dẫn đầy đủ](./create-html-document-with-styled-text-and-export-to-pdf-full/) Hướng dẫn chi tiết cách tạo tài liệu HTML có văn bản định dạng và xuất ra PDF bằng Aspose.HTML cho .NET. ### [Tạo PDF từ HTML – Hướng dẫn từng bước C#](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md b/html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md new file mode 100644 index 000000000..900769c90 --- /dev/null +++ b/html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-04-23 +description: Học cách nén HTML thành ZIP trong C# bằng trình xử lý tài nguyên tùy + chỉnh – hướng dẫn từng bước để lưu HTML dưới dạng ZIP, chuyển đổi HTML sang ZIP + và tạo ZIP từ HTML. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- create zip from html +language: vi +og_description: 'cách nén html thành zip trong C# giải thích: sử dụng trình xử lý + tài nguyên tùy chỉnh để lưu html dưới dạng zip, chuyển đổi html sang zip và tạo + zip từ html trong vài phút.' +og_title: Cách zip HTML trong C# – Hướng dẫn Trình xử lý Tài nguyên Tùy chỉnh +tags: +- Aspose.HTML +- C# +- ZIP +- File I/O +title: Cách nén HTML trong C# – Hướng dẫn trình xử lý tài nguyên tùy chỉnh +url: /vi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách nén HTML trong C# – Hướng dẫn Custom Resource Handler + +Bạn đã bao giờ tự hỏi **cách nén html** trực tiếp từ mã C# của mình mà không cần đưa các tệp lên đĩa trước không? Bạn không phải là người duy nhất. Nhiều nhà phát triển gặp khó khăn khi cần đóng gói một trang HTML cùng với CSS, hình ảnh và phông chữ để phân phối offline, và họ cuối cùng lại viết mã hệ thống tệp tạm thời mà nhanh chóng trở thành cơn ác mộng bảo trì. + +Trong tutorial này chúng tôi sẽ giải quyết vấn đề đó bằng cách giới thiệu một cách tiếp cận sạch sẽ, có thể tái sử dụng để **lưu HTML dưới dạng ZIP archive** bằng `ResourceHandler` của Aspose.HTML. Chúng tôi cũng sẽ đề cập tới cách **chuyển đổi HTML sang ZIP**, và thậm chí minh họa một mẫu bạn có thể tái dùng để **tạo ZIP từ HTML** trong bất kỳ dự án .NET nào. Không có script bên ngoài, không có thư mục tạm—chỉ thuần C#. + +Khi kết thúc hướng dẫn, bạn sẽ có một mẫu sẵn sàng chạy tạo ra file `result.zip` chứa mọi tài nguyên được liên kết, cùng một vài mẹo thực tiễn bạn có thể áp dụng cho dự án của mình. + +## Yêu cầu trước + +- .NET 6+ (mã cũng chạy được trên .NET Framework 4.7.2, nhưng chúng tôi khuyên dùng SDK mới nhất) +- Gói NuGet Aspose.HTML for .NET (`Aspose.HTML`) – cài đặt bằng `dotnet add package Aspose.HTML` +- Kiến thức cơ bản về streams và namespace `System.IO.Compression` +- Một IDE hoặc trình soạn thảo mà bạn thích (Visual Studio, VS Code, Rider…) + +Nếu bạn đã có những thành phần này, tuyệt vời—hãy chuyển ngay sang phần code. Nếu chưa, bước bổ sung duy nhất là một dòng lệnh cài đặt NuGet; mọi thứ còn lại đều tự chứa. + +## Bước 1: Tạo một tài liệu HTML đơn giản trong bộ nhớ + +Đầu tiên chúng ta cần một đối tượng `HTMLDocument` đại diện cho trang muốn nén. Trong thực tế, bạn có thể tải tài liệu này từ URL hoặc file, nhưng để minh bạch chúng ta sẽ xây dựng một tài liệu nhỏ ngay trong code. + +```csharp +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +// Step 1 – build a minimal HTML page +var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); +``` + +> **Why this matters:** +> Bằng cách giữ tài liệu trong bộ nhớ, chúng ta tránh mọi I/O tệp trung gian, giúp bước **convert html to zip** sau này nhanh hơn và an toàn với đa luồng. + +## Bước 2: Chuẩn bị một ZIP Stream trong bộ nhớ + +Thay vì ghi một file `.zip` tạm thời ra đĩa, chúng ta sẽ dùng `MemoryStream`. Cách này giữ mọi thứ trong RAM, lý tưởng cho các dịch vụ web hoặc job nền cần trả về archive trực tiếp cho client. + +```csharp +// Step 2 – allocate a memory stream that will hold the final ZIP +using var zipMemoryStream = new MemoryStream(); +``` + +> **Tip:** Câu lệnh `using` đảm bảo stream được giải phóng tự động, ngăn ngừa rò rỉ bộ nhớ. + +## Bước 3: Triển khai một Custom ResourceHandler + +Aspose.HTML gọi một `ResourceHandler` cho mỗi tài nguyên bên ngoài nó phát hiện (file CSS, hình ảnh, phông chữ, v.v.). Bằng cách kế thừa `ResourceHandler` chúng ta có thể quyết định chính xác nơi mỗi tài nguyên sẽ được lưu—trong trường hợp này, là một entry trong ZIP archive. + +```csharp +// ------------------------------------------------------------ +// Custom ResourceHandler that stores each resource as a ZIP entry +class MyZipResourceHandler : ResourceHandler +{ + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + // Open a ZipArchive in Create mode; leaveOpen lets us read the stream later + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + // Called for every resource (HTML page, CSS, images, fonts, …) + public override Stream HandleResource(ResourceInfo resourceInfo) + { + // Use the URL path as the entry name; fall back to a generic name if missing + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Create the entry with fast compression – you can switch to Optimal if size matters more + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); // Aspose writes the bytes directly into this stream + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); // Flush and close the ZIP archive + + base.Dispose(disposing); + } +} +``` + +### Tại sao cần Custom Handler? + +- **Control over naming** – bạn quyết định mỗi file sẽ xuất hiện như thế nào trong archive. +- **No temporary files** – handler ghi thẳng vào ZIP trong bộ nhớ. +- **Reusability** – bạn có thể đưa lớp này vào bất kỳ dự án nào cần **save html as zip**. + +## Bước 4: Lưu tài liệu HTML bằng Handler + +Bây giờ chúng ta kết nối mọi thứ lại. Phương thức `Save` sẽ gọi `HandleResource` cho mỗi tài nguyên được liên kết, và handler sẽ truyền các byte đó vào ZIP archive mà chúng ta đã tạo trước đó. + +```csharp +// Step 4 – initialise the handler and let Aspose do the heavy lifting +var zipResourceHandler = new MyZipResourceHandler(zipMemoryStream); +htmlDocument.Save(zipResourceHandler); +``` + +> **What happens under the hood?** +> Aspose phân tích HTML, phát hiện tham chiếu ``, yêu cầu handler cung cấp một stream, và handler tạo một entry `logo.png` trong ZIP. Quy trình tương tự lặp lại cho CSS, phông chữ hoặc bất kỳ tài nguyên bên ngoài nào khác. + +## Bước 5: Ghi ZIP Archive ra đĩa (hoặc trả về) + +Cuối cùng chúng ta ghi archive trong bộ nhớ ra file. Trong một Web API, bạn có thể trả về `zipMemoryStream.ToArray()` dưới dạng mảng byte. + +```csharp +// Step 5 – write the ZIP file to disk (you can also return the byte[] directly) +File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); +``` + +### Expected Result + +Mở `result.zip` và bạn sẽ thấy: + +``` +logo.png +resource.bin (the HTML page itself) +``` + +Nếu bạn mở archive trong trình khám phá file, sẽ thấy file HTML được lưu dưới tên `resource.bin` vì chúng ta chưa đặt tên thân thiện. Bạn có thể cải thiện dễ dàng bằng cách kiểm tra `resourceInfo.ContentType` và gán đuôi `.html` khi phù hợp. + +## Ví dụ hoàn chỉnh hoạt động + +Dưới đây là chương trình đầy đủ, sẵn sàng copy‑paste, bao gồm tất cả các bước ở trên. Chạy từ một console app và bạn sẽ nhận được một file ZIP sẵn sàng chia sẻ. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +namespace ZipHtmlDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Build the HTML document in memory + var htmlDocument = new HTMLDocument( + "" + + "

Hello, world!

logo"); + + // 2️⃣ Prepare an in‑memory stream for the ZIP archive + using var zipMemoryStream = new MemoryStream(); + + // 3️⃣ Create our custom handler that writes resources into the ZIP + var zipHandler = new MyZipResourceHandler(zipMemoryStream); + + // 4️⃣ Save – Aspose will call HandleResource for each linked asset + htmlDocument.Save(zipHandler); + + // 5️⃣ Persist the ZIP to disk (or return the byte array from a web API) + File.WriteAllBytes("result.zip", zipMemoryStream.ToArray()); + + Console.WriteLine("✅ result.zip created successfully!"); + } + } + + // ------------------------------------------------------------ + // Custom ResourceHandler that stores each resource as a ZIP entry + class MyZipResourceHandler : ResourceHandler + { + private readonly MemoryStream _zipStream; + private readonly System.IO.Compression.ZipArchive _archive; + + public MyZipResourceHandler(MemoryStream zipStream) + { + _zipStream = zipStream; + _archive = new System.IO.Compression.ZipArchive( + _zipStream, + System.IO.Compression.ZipArchiveMode.Create, + leaveOpen: true); + } + + public override Stream HandleResource(ResourceInfo resourceInfo) + { + var entryName = resourceInfo.Url?.AbsolutePath?.TrimStart('/') ?? "resource.bin"; + + // Give HTML files a proper .html extension for readability + if (resourceInfo.ContentType?.Contains("text/html") == true && !entryName.EndsWith(".html")) + entryName = "index.html"; + + var entry = _archive.CreateEntry(entryName, System.IO.Compression.CompressionLevel.Fastest); + return entry.Open(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _archive.Dispose(); + + base.Dispose(disposing); + } + } +} +``` + +**Running this code** sẽ tạo ra `result.zip` trong thư mục làm việc của chương trình. Mở nó và bạn sẽ thấy `index.html` (trang gốc của chúng ta) cộng với `logo.png` nếu hình ảnh đó tồn tại trên đĩa hoặc được tải về từ URL. + +## Các biến thể phổ biến & Trường hợp góc cạnh + +| Scenario | +|----------| + +{{< /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