From c4a860f7f1552faa9f41405d57e2cba303f12bb2 Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Mon, 3 Aug 2026 14:33:37 +0000 Subject: [PATCH] Add 2 html net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: html-extensions-and-conversions, working-with-html-documents Source: AI Search API Tutorials: - Load html string in C# – complete guide with custom handler - Convert HTML to PDF in C# – set font style programmatically Auto-generated by Professionalize.Tutorials Agent --- .../html-extensions-and-conversions/_index.md | 19 +- .../_index.md | 238 +++++++++++++ .../net/working-with-html-documents/_index.md | 1 + .../_index.md | 331 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 236 +++++++++++++ .../net/working-with-html-documents/_index.md | 3 + .../_index.md | 329 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 239 +++++++++++++ .../net/working-with-html-documents/_index.md | 1 + .../_index.md | 332 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 17 +- .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 3 + .../_index.md | 331 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 241 +++++++++++++ .../og-image.png | Bin 0 -> 48361 bytes .../net/working-with-html-documents/_index.md | 3 + .../_index.md | 333 +++++++++++++++++ .../og-image.png | Bin 0 -> 44588 bytes .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 333 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 38 +- .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 4 + .../_index.md | 334 ++++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 333 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 5 +- .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 3 + .../_index.md | 333 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 236 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 329 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 1 + .../_index.md | 238 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 332 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 +- .../_index.md | 228 ++++++++++++ .../net/working-with-html-documents/_index.md | 5 + .../_index.md | 331 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 1 + .../_index.md | 333 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 3 + .../_index.md | 236 +++++++++++++ .../net/working-with-html-documents/_index.md | 1 + .../_index.md | 329 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 238 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 331 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 331 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 3 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 3 + .../_index.md | 333 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 231 ++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 333 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 332 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 4 + .../_index.md | 332 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 238 +++++++++++++ .../net/working-with-html-documents/_index.md | 2 + .../_index.md | 331 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 3 + .../_index.md | 332 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++ .../net/working-with-html-documents/_index.md | 4 + .../_index.md | 331 +++++++++++++++++ 94 files changed, 13231 insertions(+), 54 deletions(-) create mode 100644 html/arabic/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/arabic/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/chinese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/chinese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/czech/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/czech/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/dutch/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/dutch/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/english/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/english/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/og-image.png create mode 100644 html/english/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/english/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/og-image.png create mode 100644 html/french/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/french/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/german/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/german/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/greek/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/greek/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/hindi/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/hindi/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/hongkong/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/hongkong/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/hungarian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/hungarian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/indonesian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/indonesian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/italian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/italian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/japanese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/japanese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/korean/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/korean/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/polish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/polish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/portuguese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/portuguese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/russian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/russian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/spanish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/spanish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/swedish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/swedish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/thai/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/thai/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/turkish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/turkish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md create mode 100644 html/vietnamese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md create mode 100644 html/vietnamese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md diff --git a/html/arabic/net/html-extensions-and-conversions/_index.md b/html/arabic/net/html-extensions-and-conversions/_index.md index 980eb70131..c10b4a14a9 100644 --- a/html/arabic/net/html-extensions-and-conversions/_index.md +++ b/html/arabic/net/html-extensions-and-conversions/_index.md @@ -38,41 +38,24 @@ url: /ar/net/html-extensions-and-conversions/ ## دروس حول امتدادات HTML وتحويلاتها ### [تحويل HTML إلى PDF في .NET باستخدام Aspose.HTML](./convert-html-to-pdf/) -قم بتحويل HTML إلى PDF بسهولة باستخدام Aspose.HTML for .NET. اتبع دليلنا خطوة بخطوة واكتشف قوة تحويل HTML إلى PDF. +### [تحويل HTML إلى PDF في C# – تعيين نمط الخط برمجيًا](./convert-html-to-pdf-in-c-set-font-style-programmatically/) ### [إنشاء PDF من HTML – دليل خطوة بخطوة بلغة C#](./create-pdf-from-html-c-step-by-step-guide/) -دليل خطوة بخطوة لإنشاء ملف PDF من HTML باستخدام C# ومكتبة Aspose.HTML. ### [إنشاء مستند HTML بنص منسق وتصديره إلى PDF – دليل كامل](./create-html-document-with-styled-text-and-export-to-pdf-full/) -دليل شامل لإنشاء مستند HTML بنص منسق وتصديره إلى PDF باستخدام Aspose.HTML. ### [تحويل EPUB إلى صورة في .NET باستخدام Aspose.HTML](./convert-epub-to-image/) -تعرف على كيفية تحويل EPUB إلى صور باستخدام Aspose.HTML لـ .NET. برنامج تعليمي خطوة بخطوة مع أمثلة التعليمات البرمجية والخيارات القابلة للتخصيص. ### [تحويل EPUB إلى PDF في .NET باستخدام Aspose.HTML](./convert-epub-to-pdf/) -تعرف على كيفية تحويل EPUB إلى PDF باستخدام Aspose.HTML لـ .NET. يغطي هذا الدليل خطوة بخطوة خيارات التخصيص والأسئلة الشائعة والمزيد لتحويل المستندات بسلاسة. ### [تحويل EPUB إلى XPS في .NET باستخدام Aspose.HTML](./convert-epub-to-xps/) -تعرف على كيفية تحويل EPUB إلى XPS في .NET باستخدام Aspose.HTML لـ .NET. اتبع دليلنا خطوة بخطوة لإجراء تحويلات سهلة. ### [تحويل HTML إلى BMP في .NET باستخدام Aspose.HTML](./convert-html-to-bmp/) -تعرف على كيفية تحويل HTML إلى BMP في .NET باستخدام Aspose.HTML for .NET. دليل شامل لمطوري الويب للاستفادة من Aspose.HTML for .NET. ### [تحويل HTML إلى DOC و DOCX في .NET باستخدام Aspose.HTML](./convert-html-to-doc-docx/) -تعرف على كيفية الاستفادة من قوة Aspose.HTML لـ .NET في هذا الدليل التفصيلي. قم بتحويل HTML إلى DOCX بسهولة وارتق بمشاريع .NET الخاصة بك. ابدأ اليوم! ### [تحويل HTML إلى GIF في .NET باستخدام Aspose.HTML](./convert-html-to-gif/) -اكتشف قوة Aspose.HTML لـ .NET: دليل خطوة بخطوة لتحويل HTML إلى GIF. المتطلبات الأساسية وأمثلة التعليمات البرمجية والأسئلة الشائعة والمزيد! قم بتحسين معالجة HTML باستخدام Aspose.HTML. ### [تحويل HTML إلى JPEG في .NET باستخدام Aspose.HTML](./convert-html-to-jpeg/) -تعرف على كيفية تحويل HTML إلى JPEG في .NET باستخدام Aspose.HTML for .NET. دليل خطوة بخطوة لتسخير قوة Aspose.HTML for .NET. قم بتحسين مهام تطوير الويب الخاصة بك دون عناء. ### [تحويل HTML إلى Markdown في .NET باستخدام Aspose.HTML](./convert-html-to-markdown/) -تعرف على كيفية تحويل HTML إلى Markdown في .NET باستخدام Aspose.HTML لمعالجة المحتوى بكفاءة. احصل على إرشادات خطوة بخطوة لعملية تحويل سلسة. ### [تحويل HTML إلى MHTML في .NET باستخدام Aspose.HTML](./convert-html-to-mhtml/) -تحويل HTML إلى MHTML في .NET باستخدام Aspose.HTML - دليل خطوة بخطوة لأرشفة محتوى الويب بكفاءة. تعرف على كيفية استخدام Aspose.HTML لـ .NET لإنشاء أرشيفات MHTML. ### [تحويل HTML إلى PNG في .NET باستخدام Aspose.HTML](./convert-html-to-png/) -اكتشف كيفية استخدام Aspose.HTML for .NET لمعالجة مستندات HTML وتحويلها. دليل خطوة بخطوة لتطوير .NET بشكل فعال. ### [تحويل HTML إلى TIFF في .NET باستخدام Aspose.HTML](./convert-html-to-tiff/) -تعرف على كيفية تحويل HTML إلى TIFF باستخدام Aspose.HTML لـ .NET. اتبع دليلنا خطوة بخطوة لتحسين محتوى الويب بكفاءة. ### [تحويل HTML إلى XPS في .NET باستخدام Aspose.HTML](./convert-html-to-xps/) -اكتشف قوة Aspose.HTML لـ .NET: تحويل HTML إلى XPS بسهولة. المتطلبات الأساسية، ودليل خطوة بخطوة، والأسئلة الشائعة متضمنة. ### [كيفية ضغط HTML في C# – حفظ HTML إلى ملف Zip](./how-to-zip-html-in-c-save-html-to-zip/) -تعلم كيفية ضغط ملفات HTML وحفظها كملف Zip باستخدام C# ومكتبة Aspose.HTML. ### [حفظ HTML كملف ZIP – دليل C# كامل](./save-html-as-zip-complete-c-tutorial/) -تعلم كيفية حفظ مستند HTML كملف ZIP باستخدام Aspose.HTML في C# خطوة بخطوة. ### [حفظ HTML إلى ZIP في C# – مثال كامل في الذاكرة](./save-html-to-zip-in-c-complete-in-memory-example/) -تعلم كيفية حفظ مستند HTML كملف ZIP في الذاكرة باستخدام C# ومكتبة Aspose.HTML. ## خاتمة diff --git a/html/arabic/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/arabic/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..388fdc9517 --- /dev/null +++ b/html/arabic/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-08-03 +description: تحويل HTML إلى PDF باستخدام C# مع تحكم كامل في عملية العرض. تعلّم كيفية + ضبط نمط الخط برمجيًا، وتفعيل تنعيم الحواف، وتحسين وضوح النص. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: ar +lastmod: 2026-08-03 +og_description: تحويل HTML إلى PDF في C# مع خيارات مفصلة. يوضح هذا الدليل كيفية ضبط + نمط الخط برمجيًا، وتمكين التنعيم، وإنتاج ملفات PDF عالية الجودة. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: تحويل HTML إلى PDF في C# – تحكم كامل في العرض +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: تحويل HTML إلى PDF في C# – تعيين نمط الخط برمجياً +url: /ar/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل HTML إلى PDF في C# – تعيين نمط الخط برمجياً + +إذا كنت بحاجة إلى **تحويل HTML إلى PDF** في تطبيق .NET، فإن هذا الدرس يوجهك عبر حل كامل وجاهز للإنتاج. ستتعرف على كيفية **تعيين نمط الخط برمجياً**، تحسين عرض الصور، وتمكين تحسين النص—كل ذلك دون مغادرة كود C# الخاص بك. + +تحويل صفحات الويب إلى ملفات PDF هو طلب شائع للتقارير، الفوترة، والأرشفة. يغطي هذا الدليل كل شيء من إعداد المشروع إلى مثال كامل قابل للتنفيذ. بحلول نهاية المقال يمكنك إنشاء ملفات PDF تحافظ على التخطيط، الطباعة، والدقة البصرية. + +## ما ستتعلمه + +* كيفية إضافة حزمة NuGet المطلوبة واستيراد المساحات الاسمية. +* كيفية تكوين `HtmlConversionOptions` للتحكم في العرض. +* كيفية **تعيين نمط الخط برمجياً** باستخدام علامات `WebFontStyle`. +* كيفية تمكين مضاد التسنين للصور وتحسين النص. +* كيفية استدعاء فئة `Converter` لإنتاج ملف PDF النهائي. + +يفترض الدرس أنك تمتلك Visual Studio 2022 (أو أحدث) و .NET 6 أو أحدث مثبتين. لا توجد أدوات إضافية مطلوبة. + +## المتطلبات المسبقة + +| المتطلب | السبب | +|---|---| +| .NET 6 SDK or later | يوفر بيئة التشغيل لمشروع C#. | +| Visual Studio 2022 (or any IDE) | يسمح بإنشاء المشروع بسهولة وتصحيح الأخطاء. | +| Internet access to restore NuGet packages | مطلوب لتنزيل مكتبة التحويل. | +| A simple HTML file (`input.html`) | يعمل كمستند المصدر للتحويل. | + +> **نصيحة احترافية:** احتفظ بملف HTML في نفس مجلد المشروع لتجنب المشكلات المتعلقة بالمسارات. + +## الخطوة 1: تثبيت مكتبة التحويل + +يستخدم مثال الشيفرة مكتبة **GroupDocs.Conversion for .NET**، التي توفر `HtmlConversionOptions` وفئة `Converter`. قم بتثبيتها عبر مدير حزم NuGet: + +```bash +dotnet add package GroupDocs.Conversion +``` + +تضيف الحزمة الأنواع اللازمة إلى مشروعك وتستورد جميع الاعتمادات. + +## الخطوة 2: إنشاء مشروع كونسول C# + +افتح موجه الأوامر وشغّل: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +هذا ينشئ تطبيق كونسول بسيط باسم `HtmlToPdfDemo`. افتح الملف `Program.cs` الذي تم إنشاؤه؛ ستستبدل محتوياته بالمثال الكامل لاحقًا. + +## الخطوة 3: تكوين خيارات التحويل – تعيين نمط الخط برمجياً + +تتيح لك فئة `HtmlConversionOptions` ضبط دقة كيفية عرض محرك HTML للصفحة. لت **تعيين نمط الخط برمجياً**، اجمع قيم تعداد `WebFontStyle` باستخدام عملية OR البتية: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**لماذا هذا مهم:** +* `WebFontStyle.Bold | WebFontStyle.Italic` يخبر العارض بتطبيق كلا النمطين على أي نص يستخدم الخط الافتراضي. +* مضاد التسنين يقلل الحواف المتعرجة في الصور النقطية، خاصةً عند التكبير. +* تحسين النص يضبط حدود الحروف لتتناسب مع شبكة البكسل، مما يحسن قابلية القراءة على الشاشات منخفضة الدقة وفي ملف PDF الناتج. + +## الخطوة 4: إجراء التحويل + +مع إعداد الخيارات، استدعِ فئة `Converter`. طريقة `Convert` تأخذ ثلاثة معطيات: مسار ملف HTML المصدر، مسار ملف PDF الوجهة، وكائن الخيارات. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +تعمل الطريقة بشكل متزامن وتطرح استثناءً إذا تعذر قراءة ملف المصدر أو كان مسار الإخراج غير صالح. احيط الاستدعاء بكتلة try‑catch للشفرة الإنتاجية. + +## الخطوة 5: التحقق من النتيجة + +بعد انتهاء البرنامج، افتح `output.pdf` بأي عارض PDF. يجب أن ترى: + +* النص معروض بـ **غامق ومائل** (حتى إذا لم يحدد HTML الأصلي هذه الأنماط). +* الصور تظهر أكثر سلاسة بفضل مضاد التسنين. +* وضوح النص محسّن بفضل تحسين النص، خاصةً للأحجام الصغيرة للخط. + +إذا لم يعكس ملف PDF الأنماط المتوقعة، تحقق مرة أخرى من أن ملف HTML يشير إلى خط ويب آمن أو يتضمن قاعدة `@font-face` يمكن للمحول تحميلها. + +## مثال كامل قابل للتنفيذ + +فيما يلي برنامج مستقل يدمج جميع الخطوات السابقة. انسخ الشيفرة إلى `Program.cs`، وضع ملف `input.html` بجواره، وشغّل `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**مخرجات الكونسول المتوقعة** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +افتح ملف PDF الناتج لتأكيد تطبيق الأنماط. + +## معالجة الحالات الشائعة + +| الحالة | النهج الموصى به | +|---|---| +| **CSS أو خطوط خارجية** | ضع ملفات CSS وموارد الخطوط في نفس مجلد `input.html` أو اشِر إليها باستخدام عناوين URL مطلقة يمكن الوصول إليها من الجهاز الذي يجري التحويل. | +| **مستندات HTML الكبيرة** | زد الحد الافتراضي للذاكرة عن طريق تعديل `ConversionConfig` إذا واجهت `OutOfMemoryException`. | +| **محتوى ديناميكي (JavaScript)** | المكتبة لا تنفذ JavaScript. قم بتهيئة الأجزاء الديناميكية على الخادم مسبقًا أو استخدم متصفحًا بدون رأس لإنتاج لقطة HTML ثابتة قبل التحويل. | +| **عدم عرض أحرف Unicode** | تأكد من أن HTML يعلن `` وأن الخطوط المصدرية تحتوي على الحروف المطلوبة. | +| **حجم الصفحة غير صحيح** | عيّن `conversionOptions.PageSize = PageSize.A4` (أو قيمة تعداد أخرى) لفرض أبعاد متسقة. | + +## نصائح الأداء + +* أعد استخدام نسخة واحدة من فئة `Converter` عند تحويل ملفات متعددة؛ يقلل ذلك من عبء بدء التشغيل. +* عطّل ميزات العرض غير الضرورية (مثل `EnableHyperlinks`) إذا لم تكن بحاجة إليها، مما يسرّع المعالجة. +* اكتب ملف PDF إلى تدفق ذاكرة عندما تحتاج لإرساله مباشرة عبر HTTP بدلاً من الكتابة إلى القرص. + +## الخطوات التالية + +الآن بعد أن يمكنك **تحويل HTML إلى PDF** مع إعدادات خطوط مخصصة، استكشف المواضيع ذات الصلة التالية: + +- **تعيين هوامش الصفحة برمجياً** – عدّل `conversionOptions.Margin` للتحكم في المساحات البيضاء. +- **إضافة علامات مائية** – استخدم `PdfConversionOptions` لتراكب نص أو صور. +- **تحويل دفعي** – كرّر عبر مجموعة من ملفات HTML وأعد استخدام نفس كائن الخيارات. + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [Convert HTML to PDF in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convert SVG to PDF in .NET with Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/arabic/net/working-with-html-documents/_index.md index 30c32a306e..a10b4554e0 100644 --- a/html/arabic/net/working-with-html-documents/_index.md +++ b/html/arabic/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ url: /ar/net/working-with-html-documents/ ### [كيفية حفظ HTML في C# – دليل كامل باستخدام معالج موارد مخصص](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [كيفية جعل العنوان غامقًا باستخدام CSS و C# – دليل خطوة بخطوة كامل](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [تحميل سلسلة HTML في C# – دليل كامل مع معالج مخصص](./load-html-string-in-c-complete-guide-with-custom-handler/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/arabic/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/arabic/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..fb7dff8de4 --- /dev/null +++ b/html/arabic/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-03 +description: تحميل سلسلة HTML في C# وإنشاء معالج مخصص لحفظ HTMLDocument. تعلم كيفية + حفظ HTMLDocument مع معالجة موارد مخصصة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: ar +lastmod: 2026-08-03 +og_description: تحميل سلسلة HTML في C# واستخدام معالج مخصص لحفظ HTMLDocument. يعرض + هذا البرنامج التعليمي التنفيذ الكامل وأفضل الممارسات. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: تحميل سلسلة HTML في C# – دليل مخصص خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: تحميل سلسلة HTML في C# – دليل شامل مع معالج مخصص +url: /ar/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحميل سلسلة HTML في C# – دليل كامل مع معالج مخصص + +إذا كنت بحاجة إلى **load html string** في تطبيق C#، فإن هذا الدرس يوضح لك بالضبط كيفية القيام بذلك وكيفية **create custom handler** لإدارة الموارد. ستتعلم أيضًا **how to save htmldocument** باستخدام **custom resource handling** بحيث يتم كتابة كل صورة أو ملف CSS أو سكريبت في المكان الذي تريده بالضبط. + +سنتناول العملية بالكامل — من تحويل سلسلة HTML الخام إلى كائن `HTMLDocument`، إلى تنفيذ فئة فرعية `ResourceHandler` التي تتحكم في مكان تخزين كل مورد. في النهاية ستحصل على مثال مستقل وجاهز للإنتاج يمكنك إدراجه في أي مشروع .NET. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يعمل أيضًا على .NET Framework 4.7+) +- إشارة إلى المكتبة التي توفر `HTMLDocument` و `ResourceHandler` و `ResourceInfo` (مثال: *HtmlRenderer* أو مكتبة مماثلة لتحويل HTML إلى PDF/DOM) +- معرفة أساسية بصياغة C# وتدفقات البيانات + +> **نصيحة احترافية:** إذا كنت تستخدم Visual Studio، فعّل *nullable reference types* (`enable`) لاكتشاف الأخطاء المتعلقة بـ null مبكرًا. + +## كيفية تحميل سلسلة HTML إلى HTMLDocument + +الخطوة الأولى هي تحويل سلسلة HTML عادية إلى كائن `HTMLDocument` يمكن للمكتبة العمل معه. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**لماذا هذا مهم:** +`HTMLDocument` يحلل العلامات، يبني شجرة DOM، ويجهز الموارد (الصور، ملفات الأنماط، إلخ) للحفظ لاحقًا. تمرير السلسلة مباشرةً يتجنب الحاجة إلى ملفات مؤقتة ويحافظ على سير العمل في الذاكرة. + +### الأخطاء الشائعة + +| المشكلة | سبب حدوثها | الحل | +|-------|----------------|-----| +| `htmlContent` is `null` | متغير السلسلة لم يتم تعيينه أبداً. | تحقق قبل إنشاء المستند: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | المكتبة تفترض UTF‑8 لكن المصدر يستخدم ترميزًا آخر. | وفر نسخة `Encoding` صريحة إذا كانت متاحة، أو تأكد من أن السلسلة تم فك ترميزها بشكل صحيح. | + +## إنشاء معالج مخصص لمعالجة الموارد + +يمنحك **custom resource handler** تحكمًا كاملاً في كيفية كتابة المكتبة للموارد الخارجية (الصور، CSS، الخطوط). أدناه تنفيذ بسيط يكتب كل مورد إلى `MemoryStream`. يمكنك استبدال الجسم بمنطق نظام الملفات، التخزين السحابي، أو أي وجهة أخرى. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**لماذا تحتاج إلى معالج مخصص:** +المعالج الافتراضي غالبًا ما يكتب الموارد إلى مجلد مؤقت، وهو ما قد يكون غير مرغوب فيه لأسباب أمنية أو أداء. من خلال تجاوز `HandleResource`، تقرر بالضبط أين وكيف يتم تخزين كل بايت. + +### توسيع المعالج لإخراج الملفات + +إذا كنت تفضل كتابة كل مورد إلى مجلد محدد، عدل الطريقة كما يلي: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## كيفية حفظ htmldocument باستخدام المعالج المخصص + +الآن بعد أن لدينا كل من كائن `HTMLDocument` وتنفيذ `MyHandler`، يمكننا حفظ المستند. طريقة `Save` تقبل أي فئة فرعية من `ResourceHandler`، مما يتيح لك إدخال المنطق المخصص الخاص بك. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +عند تشغيل `Save`، ستقوم المكتبة بـ: + +1. استعراض شجرة DOM. +2. اكتشاف الموارد الخارجية (مثال: ``). +3. استدعاء `handler.HandleResource` لكل مورد. +4. كتابة بيانات المورد في الدفق المُرجع. +5. إنهاء إخراج HTML الرئيسي (غالبًا كملف منفصل أو دفق). + +### التحقق من النتيجة + +إذا استخدمت نسخة نظام الملفات من `MyHandler`، يجب أن ترى مجلد `output` يحتوي على ملف HTML الأصلي وأي أصول مُشار إليها. بالنسبة للنسخة التي تستخدم `MemoryStream`، يمكنك فحص طول الدفق للتأكد من كتابة البيانات: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## مثال كامل قابل للتنفيذ + +فيما يلي برنامج واحد جاهز للنسخ واللصق يوضح التدفق الكامل. يتضمن معالجة الأخطاء، إغلاق التدفقات، وتعليقات تشرح كل خطوة. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**الناتج المتوقع** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +بعد تشغيل البرنامج، يحتوي دليل `output` على: + +- `index.html` (المستند الرئيسي) +- أي ملفات إضافية أنشأتها المكتبة (مثل الصور، CSS) + +## تنويعات متقدمة وحالات حافة + +### الحفظ إلى `MemoryStream` للمعالجة داخل الذاكرة + +إذا كنت بحاجة إلى HTML النهائي كسلسلة أو تريد إرساله عبر HTTP دون كتابة إلى القرص، استبدل `MyHandler` بنسخة تُعيد `MemoryStream` مشترك: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +بعد `htmlDoc.Save(handler)`، يمكنك قراءة HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### معالجة الموارد الكبيرة بأمان + +عند التعامل مع صور أو ملفات PDF كبيرة، تجنّب تحميل الملف بالكامل إلى الذاكرة. بدلاً من ذلك، أعد `FileStream` يكتب مباشرةً إلى القرص، كما هو موضح سابقًا. هذا يمنع حدوث `OutOfMemoryException` في سيناريوهات ذات تدفق عالي. + +### اعتبارات أمان الخيوط + +كائنات `HTMLDocument` **غير** آمنة للاستخدام المتعدد الخيوط. إذا كنت بحاجة لمعالجة عدة سلاسل HTML بشكل متزامن، أنشئ `HTMLDocument` و `MyHandler` منفصلين لكل خيط، أو قم بمزامنة الوصول باستخدام `lock`. + +### إغلاق التدفقات + +كل من `HTMLDocument.Save` و `ResourceHandler.HandleResource` قد يعيدان تدفقات تحتاج إلى إغلاق. في الأمثلة أعلاه، تقوم المكتبة بإغلاق التدفقات تلقائيًا بعد الكتابة. إذا كنت تدير التدفقات بنفسك (مثال: فتح `FileStream` قبل استدعاء `Save`)، غلفها بعبارات `using`. + +## الملخص + +هذا الدرس أظهر لك كيفية **load html string** إلى `HTMLDocument`، **create custom handler** لتحديد تخزين الموارد، و**how to save htmldocument** باستخدام **custom resource handling**. لديك الآن: + +1. طريقة واضحة لتحويل HTML الخام إلى كائن DOM. +2. فئة `ResourceHandler` قابلة لإعادة الاستخدام يمكنها كتابة الموارد إلى الذاكرة أو القرص أو التخزين السحابي. +3. برنامج كامل قابل للتنفيذ يوضح سير العمل بالكامل. + +## الخطوات التالية + +- استكشف تجاوزات `ResourceHandler` الأخرى مثل `HandleCss` أو `HandleFont` إذا كانت مكتبتك توفرها. +- اجمع هذا النهج مع خطوة تحويل إلى PDF لإنشاء ملفات PDF من HTML مع الحفاظ على التحكم الكامل في الأصول المدمجة. +- راجع وثائق المكتبة للحصول على خيارات إضافية مثل *compression*، *caching*، أو الحفظ *asynchronous*. + +لا تتردد في تجربة استراتيجيات تخزين مختلفة، ومشاركة ما توصلت إليه في التعليقات أو في مجتمع المطورين المفضل لديك. برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 a6c24babf2..a8732c1f5d 100644 --- a/html/chinese/net/html-extensions-and-conversions/_index.md +++ b/html/chinese/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET 不仅仅是一个库;它是 Web 开发领域的变革者 ## HTML 扩展和转换教程 ### [使用 Aspose.HTML 在 .NET 中将 HTML 转换为 PDF](./convert-html-to-pdf/) 使用 Aspose.HTML for .NET 轻松将 HTML 转换为 PDF。按照我们的分步指南,释放 HTML 到 PDF 转换的强大功能。 +### [在 C# 中将 HTML 转换为 PDF – 以编程方式设置字体样式](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +演示如何在 C# 中使用 Aspose.HTML 设置字体样式并将 HTML 转换为 PDF 的完整步骤。 ### [使用 Aspose.HTML 在 .NET 中将 EPUB 转换为图像](./convert-epub-to-image/) 了解如何使用 Aspose.HTML for .NET 将 EPUB 转换为图像。带有代码示例和可自定义选项的分步教程。 ### [使用 Aspose.HTML 在 .NET 中将 EPUB 转换为 PDF](./convert-epub-to-pdf/) diff --git a/html/chinese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/chinese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..4223a5f943 --- /dev/null +++ b/html/chinese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-08-03 +description: 在 C# 中将 HTML 转换为 PDF,全面控制渲染。了解如何以编程方式设置字体样式、启用抗锯齿并提升文本清晰度。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: zh +lastmod: 2026-08-03 +og_description: 在 C# 中将 HTML 转换为 PDF,提供详细选项。本指南展示如何以编程方式设置字体样式、启用抗锯齿并生成高质量的 PDF。 +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: 在 C# 中将 HTML 转换为 PDF – 完全渲染控制 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: 在 C# 中将 HTML 转换为 PDF – 以编程方式设置字体样式 +url: /zh/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 HTML 转换为 PDF(C#)– 以编程方式设置字体样式 + +如果您需要在 .NET 应用程序中 **将 HTML 转换为 PDF**,本教程将带您完成一个完整的、可投入生产的解决方案。您将了解如何 **以编程方式设置字体样式**、改进图像渲染以及启用文本 hinting——全部在 C# 代码中完成。 + +将网页转换为 PDF 是报告、开票和归档等场景的常见需求。本指南涵盖从项目设置到完整可运行示例的全部内容。阅读完本文后,您即可生成在布局、排版和视觉保真度上都得到保留的 PDF。 + +## 您将学习 + +* 如何添加所需的 NuGet 包并导入命名空间。 +* 如何配置 `HtmlConversionOptions` 以控制渲染。 +* 如何使用 `WebFontStyle` 标志 **以编程方式设置字体样式**。 +* 如何为图像启用抗锯齿以及为文本启用 hinting。 +* 如何调用 `Converter` 类生成最终的 PDF 文件。 + +本教程假设您已安装 Visual Studio 2022(或更高版本)和 .NET 6 或更高版本。无需其他工具。 + +## 前提条件 + +| 需求 | 原因 | +|---|---| +| .NET 6 SDK 或更高版本 | 为 C# 项目提供运行时。 | +| Visual Studio 2022(或任何 IDE) | 便于项目创建和调试。 | +| 网络访问以恢复 NuGet 包 | 用于下载转换库。 | +| 一个简单的 HTML 文件(`input.html`) | 作为转换的源文档。 | + +> **技巧提示:** 将 HTML 文件放在与项目相同的文件夹中,以避免路径相关的问题。 + +## 步骤 1:安装转换库 + +代码示例使用 **GroupDocs.Conversion for .NET** 库,该库提供 `HtmlConversionOptions` 和 `Converter` 类。通过 NuGet 包管理器进行安装: + +```bash +dotnet add package GroupDocs.Conversion +``` + +该包会向您的项目添加必要的类型并引入所有依赖项。 + +## 步骤 2:创建 C# 控制台项目 + +打开命令提示符并运行: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +这将创建一个名为 `HtmlToPdfDemo` 的最小控制台应用程序。打开生成的 `Program.cs` 文件;稍后您将用完整示例替换其内容。 + +## 步骤 3:配置转换选项 – 以编程方式设置字体样式 + +`HtmlConversionOptions` 类允许您细致调节 HTML 引擎渲染页面的方式。要 **以编程方式设置字体样式**,请使用按位或将 `WebFontStyle` 枚举值组合起来: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**为什么这很重要:** +* `WebFontStyle.Bold | WebFontStyle.Italic` 告诉渲染器对使用默认字体的任何文本同时应用粗体和斜体。 +* 抗锯齿可以降低光栅图像的锯齿边缘,尤其在缩放时。 +* Hinting 将字形轮廓对齐到像素网格,提升低分辨率屏幕和生成的 PDF 中的可读性。 + +## 步骤 4:执行转换 + +准备好选项后,调用 `Converter` 类。`Convert` 方法接受三个参数:源 HTML 文件路径、目标 PDF 文件路径以及选项对象。 + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +该方法同步执行,如果无法读取源文件或输出路径无效会抛出异常。请在生产代码中使用 try‑catch 块包装调用。 + +## 步骤 5:验证结果 + +程序执行完毕后,使用任意 PDF 查看器打开 `output.pdf`。您应当看到: + +* 文本以 **粗体和斜体** 渲染(即使原始 HTML 未指定这些样式)。 +* 由于抗锯齿,图像更平滑。 +* 文本清晰度因 hinting 而提升,尤其是小字号时。 + +如果 PDF 未体现预期的样式,请再次确认 HTML 文件引用了 Web 安全字体或包含转换器能够加载的 `@font-face` 规则。 + +## 完整、可运行的示例 + +下面是一个包含所有前述步骤的独立程序。将代码复制到 `Program.cs`,在同目录放置 `input.html` 文件,然后运行 `dotnet run`。 + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**预期的控制台输出** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +打开生成的 PDF 以确认已应用的样式。 + +## 处理常见边缘情况 + +| 情况 | 推荐做法 | +|---|---| +| **外部 CSS 或字体** | 将 CSS 文件和字体资源放在与 `input.html` 相同的文件夹中,或使用可从运行转换的机器访问的绝对 URL 引用它们。 | +| **大型 HTML 文档** | 如果遇到 `OutOfMemoryException`,通过调整 `ConversionConfig` 增加默认内存限制。 | +| **动态内容(JavaScript)** | 该库不执行 JavaScript。请在服务器端预渲染动态部分,或使用无头浏览器在转换前生成静态 HTML 快照。 | +| **Unicode 字符未显示** | 确保 HTML 声明了 ``,并且源字体包含所需的字形。 | +| **页面尺寸不正确** | 设置 `conversionOptions.PageSize = PageSize.A4`(或其他枚举值)以确保尺寸一致。 | + +## 性能技巧 + +* 在转换多个文件时复用同一个 `Converter` 实例,可减少启动开销。 +* 如果不需要,禁用不必要的渲染功能(例如 `EnableHyperlinks`),可加快处理速度。 +* 当需要直接通过 HTTP 发送 PDF 时,将其写入内存流而不是磁盘。 + +## 后续步骤 + +现在您已经能够使用自定义字体设置 **将 HTML 转换为 PDF**,可以进一步探索以下相关主题: + +* **以编程方式设置页面边距** – 调整 `conversionOptions.Margin` 以控制空白。 +* **添加水印** – 使用 `PdfConversionOptions` 覆盖文本或图像。 +* **批量转换** – 遍历 HTML 文件集合并复用同一选项对象。 + +## 接下来您应该学习什么? + +以下教程涵盖与本指南紧密相关的主题,基于所示技术进行扩展。每个资源都包含完整的可运行代码示例和逐步说明,帮助您掌握更多 API 功能并在项目中探索替代实现方案。 + +- [在 .NET 中使用 Aspose.HTML 将 HTML 转换为 PDF](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [创建带样式文本的 HTML 文档并导出为 PDF – 完整指南](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [在 .NET 中使用 Aspose.HTML 将 SVG 转换为 PDF](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/chinese/net/working-with-html-documents/_index.md index fcca91c844..8daf415354 100644 --- a/html/chinese/net/working-with-html-documents/_index.md +++ b/html/chinese/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ HTML 文档是 Web 的支柱,能够有效地创建和操作 HTML 文档是任 现在,让我们将您的技能提升到一个新的水平。编辑 HTML 文档是 Web 开发人员的常见任务,而 Aspose.HTML 大大简化了此过程。在本节中,我们将介绍文档创建、操作和样式。您将了解如何增强 Web 内容的外观和功能,使其更具吸引力且用户友好。 ### [如何在 C# 中保存 HTML – 使用自定义资源处理程序的完整指南](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [在 C# 中加载 HTML 字符串 – 使用自定义处理程序的完整指南](./load-html-string-in-c-complete-guide-with-custom-handler/) + ### [使用 CSS 和 C# 加粗标题 – 完整分步指南](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/chinese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/chinese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..01dd41c425 --- /dev/null +++ b/html/chinese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,329 @@ +--- +category: general +date: 2026-08-03 +description: 在 C# 中加载 HTML 字符串并创建自定义处理程序以保存 HTMLDocument。了解如何使用自定义资源处理来保存 HTMLDocument。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: zh +lastmod: 2026-08-03 +og_description: 在 C# 中加载 HTML 字符串并使用自定义处理程序保存 HTMLDocument。本教程展示了完整实现和最佳实践。 +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: 在 C# 中加载 HTML 字符串——一步一步的自定义处理程序指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: 在 C# 中加载 HTML 字符串——完整指南及自定义处理程序 +url: /zh/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中加载 HTML 字符串 – 使用自定义处理程序的完整指南 + +如果您需要在 C# 应用程序中 **加载 html 字符串**,本教程将准确展示如何操作以及如何 **创建自定义处理程序** 来进行资源管理。您还将学习 **如何使用自定义资源处理** 来 **保存 htmldocument**,从而使每个图像、CSS 文件或脚本都写入您指定的位置。 + +我们将逐步演示整个过程——从将原始 HTML 字符串转换为 `HTMLDocument` 对象,到实现一个控制资源存储位置的 `ResourceHandler` 子类。完成后,您将拥有一个自包含、可直接用于生产环境的示例,能够直接嵌入任何 .NET 项目中。 + +## 前置条件 + +- .NET 6.0 或更高(代码同样适用于 .NET Framework 4.7+) +- 对提供 `HTMLDocument`、`ResourceHandler` 和 `ResourceInfo` 的库的引用(例如 *HtmlRenderer* 或类似的 HTML‑to‑PDF/DOM 库) +- 基本的 C# 语法和流(streams)知识 + +> **专业提示:** 如果您使用 Visual Studio,请启用 *可空引用类型* (`enable`) 以提前捕获与 null 相关的错误。 + +## 如何将 html 字符串加载到 HTMLDocument 中 + +第一步是将普通的 HTML 字符串转换为库能够处理的 `HTMLDocument` 对象。 + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**为什么这很重要:** +`HTMLDocument` 解析标记,构建 DOM 树,并为后续保存准备资源(图像、样式表等)。直接传入字符串可以避免使用临时文件,并保持工作流在内存中进行。 + +### 常见陷阱 + +| 问题 | 原因 | 解决方案 | +|------|------|----------| +| `htmlContent` 为 `null` | 字符串变量从未被赋值。 | 在创建文档之前进行验证:`if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| 编码问题 | 库默认假设使用 UTF‑8,但源字符串使用了其他编码。 | 如果可用,请提供显式的 `Encoding` 重载,或确保字符串已正确解码。 | + +## 创建自定义资源处理程序 + +**自定义资源处理程序** 为您提供对库写入外部资源(图像、CSS、字体)的完整控制。下面是一个最小实现,它将每个资源写入 `MemoryStream`。您可以将其主体替换为文件系统逻辑、云存储或其他任何目标。 + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**为什么需要自定义处理程序:** +默认处理程序通常会将资源写入临时文件夹,这在安全性或性能方面可能不理想。通过重写 `HandleResource`,您可以精确决定每个字节的存储位置和方式。 + +### 扩展处理程序以输出到文件 + +如果您希望将每个资源写入特定文件夹,请按如下方式修改方法: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## 如何使用自定义处理程序保存 htmldocument + +现在我们已经拥有 `HTMLDocument` 实例和 `MyHandler` 实现,可以持久化文档。`Save` 方法接受任意 `ResourceHandler` 子类,允许您插入自定义逻辑。 + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +当 `Save` 执行时,库将会: + +1. 遍历 DOM 树。 +2. 检测外部资源(例如 ``)。 +3. 为每个资源调用 `handler.HandleResource`。 +4. 将资源数据写入返回的流中。 +5. 完成主 HTML 输出(通常为单独的文件或流)。 + +### 验证结果 + +如果您使用了 `MyHandler` 的文件系统版本,您应该会看到一个包含原始 HTML 文件和所有引用资源的 `output` 文件夹。对于 `MemoryStream` 版本,您可以检查流的长度以确认数据已写入: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## 完整、可运行的示例 + +下面是一个可直接复制粘贴的完整程序,演示整个流程。它包含错误处理、流的释放以及解释每一步的注释。 + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**预期输出** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +运行程序后,`output` 目录包含: + +- `index.html`(主文档) +- 库生成的任何其他文件(例如图像、CSS) + +## 高级变体和边缘情况 + +### 将保存到 `MemoryStream` 以进行内存内处理 + +如果您需要将最终的 HTML 作为字符串,或希望在不触及磁盘的情况下通过 HTTP 发送它,请将 `MyHandler` 替换为返回共享 `MemoryStream` 的版本: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +在调用 `htmlDoc.Save(handler)` 后,您可以读取 HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### 安全处理大资源 + +处理大型图像或 PDF 时,避免将整个文件加载到内存中。相反,返回一个直接写入磁盘的 `FileStream`,如前所示。这可以防止在高吞吐场景下出现 `OutOfMemoryException`。 + +### 线程安全注意事项 + +`HTMLDocument` 实例 **不是** 线程安全的。如果需要并发处理多个 HTML 字符串,请为每个线程创建单独的 `HTMLDocument` 和 `MyHandler`,或使用 `lock` 进行同步。 + +### 释放流 + +`HTMLDocument.Save` 和 `ResourceHandler.HandleResource` 可能返回需要释放的流。在上述示例中,库在写入后会自动释放这些流。如果您自行管理流(例如在调用 `Save` 前打开 `FileStream`),请使用 `using` 语句进行包装。 + +## 总结 + +本指南展示了如何 **加载 html 字符串** 到 `HTMLDocument`,如何 **创建自定义处理程序** 来决定资源存储位置,以及 **如何使用自定义资源处理** 来 **保存 htmldocument**。您现在拥有: + +1. 将原始 HTML 转换为 DOM 对象的明确方法。 +2. 可复用的 `ResourceHandler` 子类,可将资源写入内存、磁盘或云存储。 +3. 完整、可运行的示例程序,演示完整工作流。 + +## 下一步 + +- 探索其他 `ResourceHandler` 的重写方法,例如 `HandleCss` 或 `HandleFont`(如果您的库提供这些)。 +- 将此方法与 PDF 转换步骤结合,以在保持对嵌入资源完整控制的同时,从 HTML 生成 PDF。 +- 查看库的文档,了解诸如 *压缩*、*缓存* 或 *异步* 保存等额外选项。 + +欢迎尝试不同的存储策略,并在评论或您喜欢的开发者社区中分享您的发现。祝编码愉快! + +## 接下来应该学习什么? + +以下教程涵盖与本指南技术密切相关的主题,帮助您进一步学习。每个资源都包含完整的可运行代码示例和逐步解释,帮助您掌握更多 API 功能并在项目中探索替代实现方案。 + +- [如何在 C# 中保存 HTML – 使用自定义资源处理程序的完整指南](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [在 C# 中从字符串创建 HTML – 自定义资源处理程序指南](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [如何在 C# 中压缩 HTML – 将 HTML 保存为 Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 dc8f6f072d..a9bbf9517c 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#. +### [Převod HTML do PDF v C# – nastavení stylu písma programově](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Naučte se, jak programově nastavit styl písma při převodu HTML do PDF v C# pomocí Aspose.HTML. ## Závěr diff --git a/html/czech/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/czech/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..a09d8b23eb --- /dev/null +++ b/html/czech/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-08-03 +description: Převod HTML do PDF v C# s úplnou kontrolou vykreslování. Naučte se, jak + programově nastavit styl písma, povolit antialiasing a zlepšit čitelnost textu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: cs +lastmod: 2026-08-03 +og_description: Převod HTML do PDF v C# s podrobnými možnostmi. Tento průvodce ukazuje, + jak programově nastavit styl písma, povolit antialiasing a vytvořit vysoce kvalitní + PDF. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Převod HTML do PDF v C# – plná kontrola vykreslování +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Převod HTML na PDF v C# – nastavení stylu písma programově +url: /cs/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod HTML do PDF v C# – nastavení stylu písma programově + +Pokud potřebujete **převést HTML do PDF** v .NET aplikaci, tento tutoriál vás provede kompletním, připraveným řešením pro produkci. Ukážeme si, jak **nastavit styl písma programově**, vylepšit vykreslování obrázků a povolit hintování textu — vše bez opuštění vašeho C# kódu. + +Převod webových stránek do PDF je běžná potřeba pro reportování, fakturaci a archivaci. Tento průvodce pokrývá vše od nastavení projektu až po kompletní spustitelný příklad. Na konci článku budete schopni generovat PDF, které zachovávají rozvržení, typografii a vizuální věrnost. + +## Co se naučíte + +* Jak přidat požadovaný NuGet balíček a importovat jmenné prostory. +* Jak nakonfigurovat `HtmlConversionOptions` pro řízení vykreslování. +* Jak **nastavit styl písma programově** pomocí příznaků `WebFontStyle`. +* Jak povolit antialiasing pro obrázky a hintování pro text. +* Jak zavolat třídu `Converter` pro vytvoření finálního PDF souboru. + +Tutoriál předpokládá, že máte nainstalovaný Visual Studio 2022 (nebo novější) a .NET 6 nebo novější. Žádné další nástroje nejsou vyžadovány. + +## Požadavky + +| Požadavek | Důvod | +|---|---| +| .NET 6 SDK nebo novější | Poskytuje runtime pro C# projekt. | +| Visual Studio 2022 (nebo jakékoli IDE) | Umožňuje snadné vytvoření projektu a ladění. | +| Přístup k internetu pro obnovení NuGet balíčků | Potřebné pro stažení knihovny pro konverzi. | +| Jednoduchý HTML soubor (`input.html`) | Slouží jako zdrojový dokument pro konverzi. | + +> **Tip:** Uchovávejte HTML soubor ve stejné složce jako projekt, aby se předešlo problémům s cestami. + +## Krok 1: Instalace knihovny pro konverzi + +Ukázkový kód používá knihovnu **GroupDocs.Conversion for .NET**, která poskytuje `HtmlConversionOptions` a třídu `Converter`. Nainstalujte ji pomocí NuGet Package Manageru: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Balíček přidá potřebné typy do vašeho projektu a stáhne všechny závislosti. + +## Krok 2: Vytvoření C# konzolového projektu + +Otevřete příkazový řádek a spusťte: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Tím se vytvoří minimální konzolová aplikace pojmenovaná `HtmlToPdfDemo`. Otevřete vygenerovaný soubor `Program.cs`; později nahradíte jeho obsah kompletním příkladem. + +## Krok 3: Konfigurace možností konverze – nastavení stylu písma programově + +`HtmlConversionOptions` třída vám umožní jemně doladit, jak HTML engine vykresluje stránku. Pro **nastavení stylu písma programově** kombinujte hodnoty výčtu `WebFontStyle` pomocí bitového OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Proč je to důležité:** +* `WebFontStyle.Bold | WebFontStyle.Italic` říká rendereru, aby aplikoval oba styly na jakýkoli text používající výchozí písmo. +* Antialiasing snižuje zubaté hrany u rastrových obrázků, zejména při škálování. +* Hinting zarovnává obrysy glifů k pixelovým mřížkám, což zlepšuje čitelnost na nízkých rozlišeních obrazovek i v výsledném PDF. + +## Krok 4: Provedení konverze + +Po přípravě možností zavolejte třídu `Converter`. Metoda `Convert` přijímá tři argumenty: cestu ke zdrojovému HTML souboru, cestu k výstupnímu PDF souboru a objekt možností. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Metoda běží synchronně a vyhodí výjimku, pokud nelze zdrojový soubor přečíst nebo je výstupní cesta neplatná. Pro produkční kód obalte volání do try‑catch bloku. + +## Krok 5: Ověření výsledku + +Po dokončení programu otevřete `output.pdf` v libovolném PDF prohlížeči. Měli byste vidět: + +* Text vykreslený v **tučném a kurzívním** stylu (i když původní HTML tyto styly nespecifikovalo). +* Obrázky vypadají hladší díky antialiasingu. +* Čitelnost textu zlepšena hintingem, zejména u malých velikostí písma. + +Pokud PDF neodráží očekávané styly, zkontrolujte, že HTML soubor odkazuje na web‑safe font nebo obsahuje pravidlo `@font-face`, které může konvertor načíst. + +## Kompletní, spustitelný příklad + +Níže je samostatný program, který zahrnuje všechny předchozí kroky. Zkopírujte kód do `Program.cs`, umístěte soubor `input.html` vedle něj a spusťte `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Očekávaný výstup v konzoli** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Otevřete vygenerované PDF a potvrďte aplikované styly. + +## Řešení běžných okrajových případů + +| Situace | Doporučený přístup | +|---|---| +| **Externí CSS nebo fonty** | Umístěte CSS soubory a fontové zdroje do stejné složky jako `input.html` nebo na ně odkazujte pomocí absolutních URL, které jsou přístupné ze stroje provádějícího konverzi. | +| **Velké HTML dokumenty** | Zvyšte výchozí limit paměti úpravou `ConversionConfig`, pokud narazíte na `OutOfMemoryException`. | +| **Dynamický obsah (JavaScript)** | Knihovna neprovádí JavaScript. Předrenderujte dynamické části na serveru nebo použijte headless prohlížeč k vytvoření statického HTML snímku před konverzí. | +| **Unicode znaky se nezobrazují** | Ujistěte se, že HTML deklaruje `` a že zdrojové fonty obsahují požadované glyfy. | +| **Nesprávná velikost stránky** | Nastavte `conversionOptions.PageSize = PageSize.A4` (nebo jinou hodnotu výčtu) pro vynucení konzistentních rozměrů. | + +## Tipy pro výkon + +* Znovu použijte jedinou instanci `Converter` při konverzi mnoha souborů; snižuje to režii při spouštění. +* Zakázat zbytečné funkce vykreslování (např. `EnableHyperlinks`), pokud je nepotřebujete, což urychlí zpracování. +* Zapisujte PDF do paměťového proudu, pokud jej potřebujete poslat přímo přes HTTP místo zápisu na disk. + +## Další kroky + +Nyní, když můžete **převést HTML do PDF** s vlastními nastaveními písma, prozkoumejte tato související témata: + +* **Nastavte okraje stránky programově** – upravte `conversionOptions.Margin` pro kontrolu bílého prostoru. +* **Přidejte vodoznaky** – použijte `PdfConversionOptions` k překrytí textu nebo obrázků. +* **Dávková konverze** – projděte kolekci HTML souborů a znovu použijte stejný objekt možností. + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Převod HTML do PDF v .NET s Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Vytvoření HTML dokumentu se stylovaným textem a export do PDF – kompletní průvodce](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Převod SVG do PDF v .NET s Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/czech/net/working-with-html-documents/_index.md b/html/czech/net/working-with-html-documents/_index.md index c00dc46971..6cf86fb4a6 100644 --- a/html/czech/net/working-with-html-documents/_index.md +++ b/html/czech/net/working-with-html-documents/_index.md @@ -37,6 +37,7 @@ Jakmile pochopíte základy, ponoříme se hlouběji do procesu tvorby. V této Nyní posuňte vaše dovednosti na další úroveň. Úpravy HTML dokumentů jsou běžným úkolem webových vývojářů a Aspose.HTML tento proces výrazně zjednodušuje. V této části se budeme zabývat tvorbou dokumentu, manipulací s ním a stylováním. Zjistíte, jak vylepšit vzhled a funkčnost vašeho webového obsahu, aby byl poutavý a uživatelsky přívětivý. ### [Jak uložit HTML v C# – Kompletní průvodce pomocí vlastního resource handleru](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +### [Načtení HTML řetězce v C# – kompletní průvodce s vlastním handlerem](./load-html-string-in-c-complete-guide-with-custom-handler/) ### [Jak zvýraznit nadpis tučným písmem pomocí CSS a C# – Kompletní průvodce krok za krokem](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/czech/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/czech/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..d70c6cd300 --- /dev/null +++ b/html/czech/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-03 +description: Načtěte řetězec HTML v C# a vytvořte vlastní obslužný mechanismus pro + uložení HTMLDocument. Naučte se, jak uložit HTMLDocument s vlastním zpracováním + zdrojů. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: cs +lastmod: 2026-08-03 +og_description: Načtěte řetězec HTML v C# a použijte vlastní handler pro uložení HTMLDocument. + Tento tutoriál ukazuje kompletní implementaci a osvědčené postupy. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Načtení HTML řetězce v C# – krok za krokem průvodce vlastním handlerem +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Načíst HTML řetězec v C# – kompletní průvodce s vlastním handlerem +url: /cs/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Načtení HTML řetězce v C# – kompletní průvodce s vlastním handlerem + +Pokud potřebujete **načíst html řetězec** v aplikaci C#, tento tutoriál vám přesně ukáže, jak to provést a jak **vytvořit vlastní handler** pro správu zdrojů. Také se naučíte **jak uložit htmldocument** pomocí **vlastní manipulace se zdroji**, takže každý obrázek, CSS soubor nebo skript bude zapsán přesně tam, kde chcete. + +Provedeme vás celým procesem — od převodu surového HTML řetězce na objekt `HTMLDocument` až po implementaci podtřídy `ResourceHandler`, která řídí, kam se každý zdroj uloží. Na konci budete mít samostatný, připravený pro produkci příklad, který můžete vložit do libovolného .NET projektu. + +## Požadavky + +- .NET 6.0 nebo novější (kód také funguje na .NET Framework 4.7+) +- Reference na knihovnu, která poskytuje `HTMLDocument`, `ResourceHandler` a `ResourceInfo` (např. *HtmlRenderer* nebo podobná HTML‑to‑PDF/DOM knihovna) +- Základní znalost syntaxe C# a streamů + +> **Tip:** Pokud používáte Visual Studio, povolte *nullable reference types* (`enable`), abyste včas zachytili chyby související s null. + +## Jak načíst html řetězec do HTMLDocument + +Prvním krokem je převést prostý HTML řetězec na objekt `HTMLDocument`, se kterým může knihovna pracovat. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Proč je to důležité:** +`HTMLDocument` parsuje značkování, vytváří strom DOM a připravuje zdroje (obrázky, styly atd.) pro pozdější uložení. Přímé předání řetězce eliminuje potřebu dočasných souborů a udržuje tok práce v paměti. + +### Časté úskalí + +| Problém | Proč k tomu dochází | Řešení | +|-------|----------------|-----| +| `htmlContent` je `null` | Proměnná řetězce nebyla nikdy přiřazena. | Ověřte před vytvořením dokumentu: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Problémy s kódováním | Knihovna předpokládá UTF‑8, ale zdroj používá jiné kódování. | Poskytněte explicitní přetížení `Encoding`, pokud je k dispozici, nebo zajistěte správné dekódování řetězce. | + +## Vytvoření vlastního handleru pro správu zdrojů + +**Vlastní handler zdrojů** vám dává plnou kontrolu nad tím, jak knihovna zapisuje externí zdroje (obrázky, CSS, fonty). Níže je minimální implementace, která zapisuje každý zdroj do `MemoryStream`. Tělo můžete nahradit logikou souborového systému, cloudovým úložištěm nebo jakýmkoli jiným cílem. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Proč potřebujete vlastní handler:** +Výchozí handler často zapisuje zdroje do dočasné složky, což může být z bezpečnostních nebo výkonnostních důvodů nežádoucí. Přepsáním `HandleResource` určíte přesně, kde a jak je každý bajt uložen. + +### Rozšíření handleru pro výstup do souboru + +Pokud dáváte přednost zápisu každého zdroje do konkrétní složky, upravte metodu následovně: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Jak uložit htmldocument pomocí vlastního handleru + +Nyní, když máme jak instanci `HTMLDocument`, tak implementaci `MyHandler`, můžeme dokument uložit. Metoda `Save` přijímá libovolnou podtřídu `ResourceHandler`, což vám umožní vložit vlastní logiku. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Když se spustí `Save`, knihovna provede: + +1. Projde strom DOM. +2. Detekuje externí zdroje (např. ``). +3. Zavolá `handler.HandleResource` pro každý zdroj. +4. Zapíše data zdroje do vráceného streamu. +5. Dokončí hlavní HTML výstup (často jako samostatný soubor nebo stream). + +### Ověření výsledku + +Pokud jste použili verzi `MyHandler` pro souborový systém, měli byste vidět složku `output` s původním HTML souborem a všemi odkazovanými assety. Pro verzi `MemoryStream` můžete zkontrolovat délku streamu, abyste potvrdili, že data byla zapsána: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Kompletní, spustitelný příklad + +Níže je jeden program připravený ke zkopírování a vložení, který demonstruje celý tok. Obsahuje zpracování chyb, uvolňování streamů a komentáře vysvětlující každý krok. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Očekávaný výstup** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Po spuštění programu adresář `output` obsahuje: + +- `index.html` (hlavní dokument) +- Jakékoli další soubory vygenerované knihovnou (např. obrázky, CSS) + +## Pokročilé varianty a okrajové případy + +### Ukládání do `MemoryStream` pro zpracování v paměti + +Pokud potřebujete finální HTML jako řetězec nebo jej chcete odeslat přes HTTP, aniž byste se dotkli disku, nahraďte `MyHandler` verzí, která vrací sdílený `MemoryStream`: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Po `htmlDoc.Save(handler)` můžete HTML přečíst: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Bezpečná manipulace s velkými zdroji + +Při práci s velkými obrázky nebo PDF se vyhněte načítání celého souboru do paměti. Místo toho vraťte `FileStream`, který zapisuje přímo na disk, jak bylo ukázáno dříve. To zabraňuje `OutOfMemoryException` v scénářích s vysokou propustností. + +### Úvahy o vláknové bezpečnosti + +Instance `HTMLDocument` **nejsou** vlákny‑bezpečné. Pokud potřebujete zpracovávat více HTML řetězců současně, vytvořte pro každé vlákno samostatný `HTMLDocument` a `MyHandler`, nebo synchronizujte přístup pomocí `lock`. + +### Uvolňování streamů + +Jak `HTMLDocument.Save`, tak `ResourceHandler.HandleResource` mohou vracet streamy, které je třeba uvolnit. V uvedených příkladech knihovna po zápisu streamy automaticky uvolní. Pokud spravujete streamy sami (např. otevřením `FileStream` před voláním `Save`), zabalte je do `using` bloků. + +## Shrnutí + +Tento průvodce vám ukázal, jak **načíst html řetězec** do `HTMLDocument`, **vytvořit vlastní handler** pro určení uložení zdrojů a **jak uložit htmldocument** s **vlastní manipulací se zdroji**. Nyní máte: + +1. Jasný způsob, jak převést surové HTML na DOM objekt. +2. Znovupoužitelnou podtřídu `ResourceHandler`, která může zapisovat zdroje do paměti, na disk nebo do cloudového úložiště. +3. Kompletní, spustitelný program, který demonstruje celý workflow. + +## Další kroky + +- Prozkoumejte další přepsání `ResourceHandler`, jako jsou `HandleCss` nebo `HandleFont`, pokud je vaše knihovna poskytuje. +- Kombinujte tento přístup s krokem konverze do PDF, abyste generovali PDF z HTML při zachování plné kontroly nad vloženými assety. +- Projděte dokumentaci knihovny pro další možnosti jako *komprese*, *caching* nebo *asynchronní* ukládání. + +Neváhejte experimentovat s různými strategiemi ukládání a sdílet své poznatky v komentářích nebo ve vaší oblíbené vývojářské komunitě. Šťastné programování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Jak uložit HTML v C# – Kompletní průvodce s použitím vlastního resource handleru](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Vytvoření HTML ze řetězce v C# – Průvodce vlastním resource handlerem](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Jak zipovat HTML v C# – Uložit HTML do Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 fd924a78c2..b03c74bf9a 100644 --- a/html/dutch/net/html-extensions-and-conversions/_index.md +++ b/html/dutch/net/html-extensions-and-conversions/_index.md @@ -38,37 +38,22 @@ Aspose.HTML voor .NET is niet zomaar een bibliotheek; het is een game-changer in ## HTML-extensies en conversiehandleidingen ### [Converteer HTML naar PDF in .NET met Aspose.HTML](./convert-html-to-pdf/) -Converteer moeiteloos HTML naar PDF met Aspose.HTML voor .NET. Volg onze stapsgewijze handleiding en ontketen de kracht van HTML-naar-PDF-conversie. +### [Converteer HTML naar PDF in C# – stel lettertype stijl in via code](./convert-html-to-pdf-in-c-set-font-style-programmatically/) ### [Converteer EPUB naar afbeelding in .NET met Aspose.HTML](./convert-epub-to-image/) -Leer hoe u EPUB naar afbeeldingen converteert met Aspose.HTML voor .NET. Stapsgewijze tutorial met codevoorbeelden en aanpasbare opties. ### [Converteer EPUB naar PDF in .NET met Aspose.HTML](./convert-epub-to-pdf/) -Leer hoe u EPUB naar PDF converteert met Aspose.HTML voor .NET. Deze stapsgewijze handleiding behandelt aanpassingsopties, veelgestelde vragen en meer voor naadloze documentconversie. ### [Converteer EPUB naar XPS in .NET met Aspose.HTML](./convert-epub-to-xps/) -Leer hoe u EPUB naar XPS converteert in .NET met Aspose.HTML voor .NET. Volg onze stapsgewijze handleiding voor moeiteloze conversies. ### [Converteer HTML naar BMP in .NET met Aspose.HTML](./convert-html-to-bmp/) -Leer hoe u HTML naar BMP converteert in .NET met Aspose.HTML voor .NET. Uitgebreide handleiding voor webontwikkelaars voor het benutten van Aspose.HTML voor .NET. ### [Converteer HTML naar DOC en DOCX in .NET met Aspose.HTML](./convert-html-to-doc-docx/) -Leer hoe u de kracht van Aspose.HTML voor .NET kunt benutten in deze stapsgewijze handleiding. Converteer moeiteloos HTML naar DOCX en breng uw .NET-projecten naar een hoger niveau. Ga vandaag nog aan de slag! ### [Converteer HTML naar GIF in .NET met Aspose.HTML](./convert-html-to-gif/) -Ontdek de kracht van Aspose.HTML voor .NET: een stapsgewijze handleiding voor het converteren van HTML naar GIF. Vereisten, codevoorbeelden, FAQ's en meer! Optimaliseer uw HTML-manipulatie met Aspose.HTML. ### [Converteer HTML naar JPEG in .NET met Aspose.HTML](./convert-html-to-jpeg/) -Leer hoe u HTML naar JPEG converteert in .NET met Aspose.HTML voor .NET. Een stapsgewijze handleiding om de kracht van Aspose.HTML voor .NET te benutten. Optimaliseer uw webontwikkelingstaken moeiteloos. ### [Converteer HTML naar Markdown in .NET met Aspose.HTML](./convert-html-to-markdown/) -Leer hoe u HTML naar Markdown converteert in .NET met Aspose.HTML voor efficiënte contentmanipulatie. Krijg stapsgewijze begeleiding voor een naadloos conversieproces. ### [Converteer HTML naar MHTML in .NET met Aspose.HTML](./convert-html-to-mhtml/) -Converteer HTML naar MHTML in .NET met Aspose.HTML - Een stapsgewijze handleiding voor efficiënte archivering van webinhoud. Leer hoe u Aspose.HTML voor .NET gebruikt om MHTML-archieven te maken. ### [Converteer HTML naar PNG in .NET met Aspose.HTML](./convert-html-to-png/) -Ontdek hoe u Aspose.HTML voor .NET kunt gebruiken om HTML-documenten te manipuleren en converteren. Stapsgewijze handleiding voor effectieve .NET-ontwikkeling. ### [Converteer HTML naar TIFF in .NET met Aspose.HTML](./convert-html-to-tiff/) -Leer hoe u HTML naar TIFF converteert met Aspose.HTML voor .NET. Volg onze stapsgewijze handleiding voor efficiënte optimalisatie van webinhoud. ### [Converteer HTML naar XPS in .NET met Aspose.HTML](./convert-html-to-xps/) -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. ### [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/) -Leer hoe u met Aspose.HTML voor .NET PDF's genereert vanuit HTML met een duidelijke C# stap‑voor‑stap handleiding. ### [HTML opslaan als ZIP – Complete C#-tutorial](./save-html-as-zip-complete-c-tutorial/) ### [HTML opslaan naar ZIP in C# – Volledig In‑Memory voorbeeld](./save-html-to-zip-in-c-complete-in-memory-example/) Leer hoe u HTML-inhoud in het geheugen comprimeert en opslaat als ZIP-bestand met Aspose.HTML voor .NET in C#. diff --git a/html/dutch/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/dutch/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..93a6d9f6d0 --- /dev/null +++ b/html/dutch/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Converteer HTML naar PDF in C# met volledige renderingscontrole. Leer + hoe je de lettertype‑stijl programmeermatig instelt, antialiasing inschakelt en + de teksthelderheid verbetert. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: nl +lastmod: 2026-08-03 +og_description: Converteer HTML naar PDF in C# met gedetailleerde opties. Deze gids + laat zien hoe je de lettertype‑stijl via code kunt instellen, antialiasing kunt + inschakelen en PDF's van hoge kwaliteit kunt produceren. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: HTML naar PDF converteren in C# – volledige renderingscontrole +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: HTML naar PDF converteren in C# – lettertype stijl via code instellen +url: /nl/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML naar PDF converteren in C# – lettertype stijl programmatically instellen + +Als je **HTML naar PDF moet converteren** in een .NET‑applicatie, leidt deze tutorial je door een volledige, productie‑klare oplossing. Je ziet hoe je **lettertype stijl programmatically instelt**, de weergave van afbeeldingen verbetert en tekst‑hinting inschakelt — alles zonder je C#‑code te verlaten. + +Webpagina's naar PDF converteren is een veelvoorkomende behoefte voor rapportage, facturering en archivering. Deze gids behandelt alles van projectopzet tot een volledig uitvoerbaar voorbeeld. Aan het einde van het artikel kun je PDF's genereren die de lay-out, typografie en visuele getrouwheid behouden. + +## Wat je zult leren + +* Hoe je het vereiste NuGet‑pakket toevoegt en namespaces importeert. +* Hoe je `HtmlConversionOptions` configureert om de rendering te regelen. +* Hoe je **lettertype stijl programmatically instelt** met behulp van de `WebFontStyle`‑vlaggen. +* Hoe je antialiasing inschakelt voor afbeeldingen en hinting voor tekst. +* Hoe je de `Converter`‑klasse aanroept om het uiteindelijke PDF‑bestand te produceren. + +De tutorial gaat ervan uit dat je Visual Studio 2022 (of later) en .NET 6 of nieuwer geïnstalleerd hebt. Er is geen extra tooling vereist. + +## Vereisten + +| Vereiste | Reden | +|---|---| +| .NET 6 SDK or later | Levert de runtime voor het C#‑project. | +| Visual Studio 2022 (or any IDE) | Maakt eenvoudige projectcreatie en debugging mogelijk. | +| Internet access to restore NuGet packages | Nodig om de conversiebibliotheek te downloaden. | +| A simple HTML file (`input.html`) | Dient als bronbestand voor de conversie. | + +> **Pro tip:** Houd het HTML‑bestand in dezelfde map als het project om pad‑gerelateerde problemen te voorkomen. + +## Stap 1: Installeer de conversiebibliotheek + +De code‑voorbeeld gebruikt de **GroupDocs.Conversion for .NET**‑bibliotheek, die `HtmlConversionOptions` en een `Converter`‑klasse biedt. Installeer deze via de NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Het pakket voegt de benodigde types toe aan je project en haalt alle afhankelijkheden binnen. + +## Stap 2: Maak een C# console‑project + +Open een opdrachtprompt en voer uit: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Dit maakt een minimale console‑applicatie genaamd `HtmlToPdfDemo`. Open het gegenereerde `Program.cs`‑bestand; je zult later de inhoud vervangen door het volledige voorbeeld. + +## Stap 3: Configureer conversie‑opties – lettertype stijl programmatically instellen + +De `HtmlConversionOptions`‑klasse stelt je in staat om fijn af te stemmen hoe de HTML‑engine de pagina rendert. Om **lettertype stijl programmatically in te stellen**, combineer je de `WebFontStyle`‑enumeratiewaarden met een bitwise OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Waarom dit belangrijk is:** +* `WebFontStyle.Bold | WebFontStyle.Italic` vertelt de renderer beide stijlen toe te passen op elke tekst die het standaardlettertype gebruikt. +* Antialiasing vermindert gekartelde randen op raster‑afbeeldingen, vooral bij schalen. +* Hinting zorgt ervoor dat glyph‑contouren op pixel‑rasters worden uitgelijnd, waardoor de leesbaarheid op lage‑resolutie schermen en in de resulterende PDF verbetert. + +## Stap 4: Voer de conversie uit + +Met de opties voorbereid, roep je de `Converter`‑klasse aan. De `Convert`‑methode neemt drie argumenten: het pad naar het bron‑HTML‑bestand, het pad naar het doel‑PDF‑bestand, en het opties‑object. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +De methode wordt synchroon uitgevoerd en gooit een uitzondering als het bronbestand niet gelezen kan worden of het uitvoerpad ongeldig is. Omhul de aanroep met een try‑catch‑blok voor productiecodel. + +## Stap 5: Verifieer het resultaat + +Na het beëindigen van het programma, open `output.pdf` met een PDF‑viewer. Je zou moeten zien: + +* Tekst gerenderd in **vet en cursief** (zelfs als de oorspronkelijke HTML die stijlen niet specificeerde). +* Afbeeldingen verschijnen vloeiender dankzij antialiasing. +* Teksthelderheid verbeterd door hinting, vooral bij kleine lettergroottes. + +Als de PDF niet de verwachte stijlen weergeeft, controleer dan of het HTML‑bestand een web‑safe lettertype verwijst of een `@font-face`‑regel bevat die de converter kan laden. + +## Volledig, uitvoerbaar voorbeeld + +Hieronder staat een zelfstandig programma dat alle voorgaande stappen bevat. Kopieer de code naar `Program.cs`, plaats een `input.html`‑bestand ernaast, en voer `dotnet run` uit. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Verwachte console‑output** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Open de gegenereerde PDF om de toegepaste stijlen te bevestigen. + +## Veelvoorkomende randgevallen afhandelen + +| Situatie | Aanbevolen aanpak | +|---|---| +| **External CSS or fonts** | Plaats CSS‑bestanden en lettertype‑bronnen in dezelfde map als `input.html` of verwijs ernaar met absolute URL's die bereikbaar zijn vanaf de machine die de conversie uitvoert. | +| **Large HTML documents** | Verhoog de standaard geheugenlimiet door `ConversionConfig` aan te passen als je een `OutOfMemoryException` tegenkomt. | +| **Dynamic content (JavaScript)** | De bibliotheek voert geen JavaScript uit. Render dynamische delen vooraf server‑side of gebruik een headless browser om een statisch HTML‑snapshot te maken vóór de conversie. | +| **Unicode characters not displaying** | Zorg ervoor dat de HTML `` declareert en dat de bronlettertypen de benodigde glyphs bevatten. | +| **Incorrect page size** | Stel `conversionOptions.PageSize = PageSize.A4` (of een andere enum‑waarde) in om consistente afmetingen af te dwingen. | + +## Prestatie‑tips + +* Hergebruik een enkele `Converter`‑instantie bij het converteren van veel bestanden; dit vermindert de opstart‑overhead. +* Schakel onnodige render‑functies uit (bijv. `EnableHyperlinks`) als je ze niet nodig hebt, wat de verwerking versnelt. +* Schrijf de PDF naar een memory stream wanneer je deze direct via HTTP wilt verzenden in plaats van naar schijf te schrijven. + +## Volgende stappen + +Nu je **HTML naar PDF kunt converteren** met aangepaste lettertype‑instellingen, verken deze gerelateerde onderwerpen: + +* **Pagina‑marges programmatically instellen** – pas `conversionOptions.Margin` aan om de witruimte te regelen. +* **Watermerken toevoegen** – gebruik `PdfConversionOptions` om tekst of afbeeldingen te overleggen. +* **Batch‑conversie** – loop over een collectie HTML‑bestanden en hergebruik hetzelfde opties‑object. + +* [HTML naar PDF converteren in .NET met Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +* [HTML‑document maken met gestylede tekst en exporteren naar PDF – volledige gids](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +* [SVG naar PDF converteren in .NET met Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-pdf/) + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap‑uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/dutch/net/working-with-html-documents/_index.md b/html/dutch/net/working-with-html-documents/_index.md index 36eb73e4af..1f4c9474d4 100644 --- a/html/dutch/net/working-with-html-documents/_index.md +++ b/html/dutch/net/working-with-html-documents/_index.md @@ -37,8 +37,11 @@ Zodra u de basis onder de knie hebt, gaan we dieper in op het creatieproces. In Laten we nu uw vaardigheden naar een hoger niveau tillen. Het bewerken van HTML-documenten is een veelvoorkomende taak voor webontwikkelaars, en Aspose.HTML vereenvoudigt dit proces aanzienlijk. In deze sectie behandelen we het maken, manipuleren en stylen van documenten. U ontdekt hoe u het uiterlijk en de functionaliteit van uw webcontent kunt verbeteren, waardoor deze aantrekkelijk en gebruiksvriendelijk wordt. ### [HTML opslaan in C# – Complete gids met een aangepaste resourcehandler](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + ### [Koptekst vet maken met CSS & C# – Complete stapsgewijze handleiding](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [HTML-string laden in C# – Complete gids met een aangepaste handler](./load-html-string-in-c-complete-guide-with-custom-handler/) + Leer hoe u met CSS en C# kopteksten vet maakt in een .NET‑applicatie, stap voor stap met voorbeeldcode. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/dutch/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/dutch/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..fa677d655a --- /dev/null +++ b/html/dutch/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-03 +description: Laad html‑string in C# en maak een aangepaste handler om HTMLDocument + op te slaan. Leer hoe je HTMLDocument kunt opslaan met aangepaste resource‑afhandeling. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: nl +lastmod: 2026-08-03 +og_description: Laad html‑string in C# en gebruik een aangepaste handler om HTMLDocument + op te slaan. Deze tutorial toont de volledige implementatie en best practices. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: HTML-string laden in C# – stapsgewijze handleiding voor aangepaste handler +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: HTML-string laden in C# – volledige gids met aangepaste handler +url: /nl/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML-string laden in C# – volledige gids met aangepaste handler + +Als je een **html-string** moet laden in een C#-applicatie, laat deze tutorial je precies zien hoe je dat doet en hoe je een **aangepaste handler** maakt voor resource‑beheer. Je leert ook **hoe je een htmldocument opslaat** met **aangepaste resource‑afhandeling**, zodat elke afbeelding, CSS‑bestand of script precies wordt weggeschreven waar je wilt. + +We lopen het volledige proces door – van het omzetten van een ruwe HTML‑string naar een `HTMLDocument`‑object, tot het implementeren van een `ResourceHandler`‑subklasse die bepaalt waar elke resource wordt opgeslagen. Aan het einde heb je een zelf‑containend, productie‑klaar voorbeeld dat je in elk .NET‑project kunt gebruiken. + +## Vereisten + +- .NET 6.0 of later (de code werkt ook op .NET Framework 4.7+) +- Een referentie naar de bibliotheek die `HTMLDocument`, `ResourceHandler` en `ResourceInfo` levert (bijv. *HtmlRenderer* of een vergelijkbare HTML‑naar‑PDF/DOM‑bibliotheek) +- Basiskennis van C#‑syntaxis en streams + +> **Pro tip:** Als je Visual Studio gebruikt, schakel *nullable reference types* (`enable`) in om null‑gerelateerde bugs vroegtijdig te detecteren. + +## Hoe een html-string laden in HTMLDocument + +De eerste stap is het omzetten van een gewone HTML‑string naar een `HTMLDocument`‑object dat de bibliotheek kan verwerken. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Waarom dit belangrijk is:** +`HTMLDocument` parseert de markup, bouwt een DOM‑boom en bereidt resources (afbeeldingen, stylesheets, enz.) voor op later opslaan. Een string direct doorgeven voorkomt de noodzaak van tijdelijke bestanden en houdt de workflow in het geheugen. + +### Veelvoorkomende valkuilen + +| Probleem | Waarom het gebeurt | Oplossing | +|----------|--------------------|-----------| +| `htmlContent` is `null` | De stringvariabele is nooit toegewezen. | Valideer vóór het aanmaken van het document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Coderingproblemen | De bibliotheek gaat uit van UTF‑8 maar de bron gebruikt een andere codering. | Geef een expliciete `Encoding`‑overload op indien beschikbaar, of zorg dat de string correct gedecodeerd is. | + +## Aangepaste handler maken voor resource‑afhandeling + +Een **custom resource handler** geeft je volledige controle over hoe de bibliotheek externe resources (afbeeldingen, CSS, fonts) wegschrijft. Hieronder staat een minimale implementatie die elke resource naar een `MemoryStream` schrijft. Je kunt de body vervangen door logica voor het bestandssysteem, cloud‑opslag of een andere bestemming. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Waarom je een aangepaste handler nodig hebt:** +De standaardhandler schrijft resources vaak naar een tijdelijke map, wat om veiligheids‑ of prestatie‑redenen ongewenst kan zijn. Door `HandleResource` te overschrijven bepaal je exact waar en hoe elk byte‑blok wordt opgeslagen. + +### Handler uitbreiden voor bestandsuitvoer + +Als je elke resource liever naar een specifieke map schrijft, pas je de methode als volgt aan: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Hoe een htmldocument opslaan met de aangepaste handler + +Nu we zowel de `HTMLDocument`‑instantie als de `MyHandler`‑implementatie hebben, kunnen we het document persisteren. De `Save`‑methode accepteert elke `ResourceHandler`‑subklasse, zodat je je eigen logica kunt injecteren. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Wanneer `Save` wordt uitgevoerd, doet de bibliotheek het volgende: + +1. Doorloopt de DOM‑boom. +2. Detecteert externe resources (bijv. ``). +3. Roept `handler.HandleResource` aan voor elke resource. +4. Schrijft de resource‑data naar de geretourneerde stream. +5. Finaliseert de hoofd‑HTML‑output (meestal als een apart bestand of stream). + +### Het resultaat verifiëren + +Als je de bestands‑systeemversie van `MyHandler` hebt gebruikt, zie je een `output`‑map met het oorspronkelijke HTML‑bestand en alle refererende assets. Voor de `MemoryStream`‑versie kun je de stream‑lengte inspecteren om te bevestigen dat er data is geschreven: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Volledig, uitvoerbaar voorbeeld + +Hieronder staat een enkel, copy‑paste‑klaar programma dat de volledige flow demonstreert. Het bevat foutafhandeling, het vrijgeven van streams en commentaar dat elke stap uitlegt. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Verwachte output** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Na het uitvoeren van het programma bevat de `output`‑directory: + +- `index.html` (het hoofd‑document) +- Eventuele extra bestanden die de bibliotheek heeft gegenereerd (bijv. afbeeldingen, CSS) + +## Geavanceerde variaties en randgevallen + +### Opslaan naar een `MemoryStream` voor in‑memory verwerking + +Als je de uiteindelijke HTML als string nodig hebt of wilt versturen via HTTP zonder schijf‑toegang, vervang je `MyHandler` door een versie die een gedeelde `MemoryStream` retourneert: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Na `htmlDoc.Save(handler)` kun je de HTML lezen: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Grote resources veilig verwerken + +Bij grote afbeeldingen of PDF‑bestanden moet je vermijden het volledige bestand in het geheugen te laden. Retourneer in plaats daarvan een `FileStream` die direct naar schijf schrijft, zoals eerder getoond. Dit voorkomt `OutOfMemoryException` in scenario's met hoge doorvoersnelheid. + +### Overwegingen voor thread‑veiligheid + +`HTMLDocument`‑instanties zijn **niet** thread‑safe. Als je meerdere HTML‑strings gelijktijdig moet verwerken, maak dan een aparte `HTMLDocument` en `MyHandler` per thread, of synchroniseer de toegang met een `lock`. + +### Streams vrijgeven + +Zowel `HTMLDocument.Save` als `ResourceHandler.HandleResource` kunnen streams teruggeven die moeten worden vrijgegeven. In de bovenstaande voorbeelden wordt de stream automatisch door de bibliotheek gesloten na het schrijven. Als je zelf streams beheert (bijv. een `FileStream` opent vóór het aanroepen van `Save`), wikkel ze dan in `using`‑blokken. + +## Samenvatting + +Deze gids heeft je laten zien hoe je **html-string** laadt in een `HTMLDocument`, **een aangepaste handler** maakt om resource‑opslag te bepalen, en **hoe je htmldocument opslaat** met **aangepaste resource‑afhandeling**. Je hebt nu: + +1. Een duidelijke manier om ruwe HTML om te zetten naar een DOM‑object. +2. Een herbruikbare `ResourceHandler`‑subklasse die resources naar geheugen, schijf of cloud‑opslag kan schrijven. +3. Een compleet, uitvoerbaar programma dat de volledige workflow demonstreert. + +## Volgende stappen + +- Verken andere `ResourceHandler`‑overrides zoals `HandleCss` of `HandleFont` als je bibliotheek die biedt. +- Combineer deze aanpak met een PDF‑conversiestap om PDF’s uit HTML te genereren terwijl je volledige controle houdt over ingebedde assets. +- Bekijk de documentatie van de bibliotheek voor extra opties zoals *compressie*, *caching* of *asynchrone* opslag. + +Voel je vrij om met verschillende opslagstrategieën te experimenteren en deel je bevindingen in de reacties of op je favoriete ontwikkelaarscommunity. Veel programmeerplezier! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 a50bc9ccba..d776f4b7be 100644 --- a/html/english/net/html-extensions-and-conversions/_index.md +++ b/html/english/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET is not just a library; it's a game-changer in the world of ## HTML Extensions and Conversions Tutorials ### [Convert HTML to PDF in .NET with Aspose.HTML](./convert-html-to-pdf/) Convert HTML to PDF effortlessly with Aspose.HTML for .NET. Follow our step-by-step guide and unleash the power of HTML-to-PDF conversion. +### [Convert HTML to PDF in C# – set font style programmatically](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Learn how to set font styles programmatically when converting HTML to PDF using Aspose.HTML in C#. ### [Create PDF from HTML – C# Step‑by‑Step Guide](./create-pdf-from-html-c-step-by-step-guide/) Learn how to generate PDF files from HTML using Aspose.HTML for .NET with a detailed C# step‑by‑step guide. ### [Convert EPUB to Image in .NET with Aspose.HTML](./convert-epub-to-image/) diff --git a/html/english/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/english/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..3a6212c572 --- /dev/null +++ b/html/english/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-08-03 +description: Convert HTML to PDF in C# with full rendering control. Learn how to set + font style programmatically, enable antialiasing, and improve text clarity. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: en +lastmod: 2026-08-03 +og_description: Convert HTML to PDF in C# with detailed options. This guide shows + how to set font style programmatically, enable antialiasing, and produce high‑quality + PDFs. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Convert HTML to PDF in C# – full rendering control +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Convert HTML to PDF in C# – set font style programmatically +url: /net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert HTML to PDF in C# – set font style programmatically + +If you need to **convert HTML to PDF** in a .NET application, this tutorial walks you through a complete, production‑ready solution. You will see how to **set font style programmatically**, improve image rendering, and enable text hinting—all without leaving your C# code. + +Converting web pages to PDFs is a common requirement for reporting, invoicing, and archival. This guide covers everything from project setup to a full, runnable example. By the end of the article you can generate PDFs that preserve layout, typography, and visual fidelity. + +## What you will learn + +* How to add the required NuGet package and import namespaces. +* How to configure `HtmlConversionOptions` to control rendering. +* How to **set font style programmatically** using the `WebFontStyle` flags. +* How to enable antialiasing for images and hinting for text. +* How to invoke the `Converter` class to produce the final PDF file. + +The tutorial assumes you have Visual Studio 2022 (or later) and .NET 6 or newer installed. No additional tooling is required. + +## Prerequisites + +| Requirement | Reason | +|---|---| +| .NET 6 SDK or later | Provides the runtime for the C# project. | +| Visual Studio 2022 (or any IDE) | Enables easy project creation and debugging. | +| Internet access to restore NuGet packages | Needed to download the conversion library. | +| A simple HTML file (`input.html`) | Serves as the source document for conversion. | + +> **Pro tip:** Keep the HTML file in the same folder as the project to avoid path‑related issues. + +## Step 1: Install the conversion library + +The code sample uses the **GroupDocs.Conversion for .NET** library, which offers `HtmlConversionOptions` and a `Converter` class. Install it via the NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +The package adds the necessary types to your project and pulls in all dependencies. + +## Step 2: Create a C# console project + +Open a command prompt and run: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +This creates a minimal console application named `HtmlToPdfDemo`. Open the generated `Program.cs` file; you will replace its contents with the full example later. + +## Step 3: Configure conversion options – set font style programmatically + +The `HtmlConversionOptions` class lets you fine‑tune how the HTML engine renders the page. To **set font style programmatically**, combine the `WebFontStyle` enumeration values using a bitwise OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Why this matters:** +* `WebFontStyle.Bold | WebFontStyle.Italic` tells the renderer to apply both styles to any text that uses the default font. +* Antialiasing reduces jagged edges on raster images, especially when scaling. +* Hinting aligns glyph outlines to pixel grids, improving readability on low‑resolution screens and in the resulting PDF. + +## Step 4: Perform the conversion + +With the options prepared, call the `Converter` class. The `Convert` method takes three arguments: the source HTML file path, the destination PDF file path, and the options object. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +The method runs synchronously and throws an exception if the source file cannot be read or the output path is invalid. Wrap the call in a try‑catch block for production code. + +## Step 5: Verify the result + +After the program finishes, open `output.pdf` with any PDF viewer. You should see: + +* Text rendered in **bold and italic** (even if the original HTML did not specify those styles). +* Images appear smoother thanks to antialiasing. +* Text clarity improved by hinting, especially for small font sizes. + +If the PDF does not reflect the expected styles, double‑check that the HTML file references a web‑safe font or includes a `@font-face` rule that the converter can load. + +## Full, runnable example + +Below is a self‑contained program that incorporates all previous steps. Copy the code into `Program.cs`, place an `input.html` file beside it, and run `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Expected console output** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Open the generated PDF to confirm the applied styles. + +## Handling common edge cases + +| Situation | Recommended approach | +|---|---| +| **External CSS or fonts** | Place CSS files and font resources in the same folder as `input.html` or reference them with absolute URLs reachable from the machine running the conversion. | +| **Large HTML documents** | Increase the default memory limit by adjusting `ConversionConfig` if you encounter `OutOfMemoryException`. | +| **Dynamic content (JavaScript)** | The library does not execute JavaScript. Pre‑render dynamic parts server‑side or use a headless browser to produce a static HTML snapshot before conversion. | +| **Unicode characters not displaying** | Ensure the HTML declares `` and that the source fonts contain the required glyphs. | +| **Incorrect page size** | Set `conversionOptions.PageSize = PageSize.A4` (or another enum value) to enforce consistent dimensions. | + +## Performance tips + +* Reuse a single `Converter` instance when converting many files; it reduces startup overhead. +* Disable unnecessary rendering features (e.g., `EnableHyperlinks`) if you do not need them, which speeds up processing. +* Write the PDF to a memory stream when you need to send it directly over HTTP instead of writing to disk. + +## Next steps + +Now that you can **convert HTML to PDF** with custom font settings, explore these related topics: + +* **Set page margins programmatically** – adjust `conversionOptions.Margin` to control white space. +* **Add watermarks** – use `PdfConversionOptions` to overlay text or images. +* **Batch conversion** – loop over a collection of HTML files and reuse the same options object. + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Convert HTML to PDF in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convert SVG to PDF in .NET with Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/english/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/og-image.png b/html/english/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/og-image.png new file mode 100644 index 0000000000000000000000000000000000000000..43d3e563624a4658cc32ecb97d21c403a781489c GIT binary patch literal 48361 zcmb5V1yq#Z_cw|Oh=hoAhzQb13kXPqbeDj1cehGOi*)x;0@6K5E8PtvARR*wFu>e{ z-|z2T_paal-}k=HnziOx6X%>~?|pWB_UD8uDM(>IAbo&_hK4O8Ev|xwcK16P+HE(C z+u)NQ&vvlT(3-!?h>NIs%ddx{uq3?4BCMPG$E^*0|XqYW(=*+q5_B^C$UMbyf ztYPBh%(CV4Vdia!o$0n99*|W|9OA&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-string-in-c-complete-guide-with-custom-handler/_index.md b/html/english/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..3764dcdcc4 --- /dev/null +++ b/html/english/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-08-03 +description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: en +lastmod: 2026-08-03 +og_description: Load html string in C# and use a custom handler to save HTMLDocument. + This tutorial shows the full implementation and best practices. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Load html string in C# – step‑by‑step custom handler guide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Load html string in C# – complete guide with custom handler +url: /net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Load html string in C# – complete guide with custom handler + +If you need to **load html string** in a C# application, this tutorial shows you exactly how to do it and how to **create custom handler** for resource management. You’ll also learn **how to save htmldocument** using **custom resource handling** so that every image, CSS file, or script is written exactly where you want. + +We'll walk through the entire process—from turning a raw HTML string into an `HTMLDocument` object, to implementing a `ResourceHandler` subclass that controls where each resource is stored. By the end you’ll have a self‑contained, production‑ready example you can drop into any .NET project. + +## Prerequisites + +- .NET 6.0 or later (the code also works on .NET Framework 4.7+) +- A reference to the library that provides `HTMLDocument`, `ResourceHandler`, and `ResourceInfo` (e.g., *HtmlRenderer* or a similar HTML‑to‑PDF/DOM library) +- Basic knowledge of C# syntax and streams + +> **Pro tip:** If you use Visual Studio, enable *nullable reference types* (`enable`) to catch null‑related bugs early. + +## How to load html string into HTMLDocument + +The first step is converting a plain HTML string into an `HTMLDocument` object that the library can work with. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Why this matters:** +`HTMLDocument` parses the markup, builds a DOM tree, and prepares resources (images, stylesheets, etc.) for later saving. Passing a string directly avoids the need for temporary files and keeps the workflow in memory. + +### Common pitfalls + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| `htmlContent` is `null` | The string variable was never assigned. | Validate before creating the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | The library assumes UTF‑8 but the source uses another encoding. | Provide an explicit `Encoding` overload if available, or ensure the string is correctly decoded. | + +## Create custom handler for resource handling + +A **custom resource handler** gives you full control over how the library writes external resources (images, CSS, fonts). Below is a minimal implementation that writes each resource to a `MemoryStream`. You can replace the body with file‑system logic, cloud storage, or any other destination. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Why you need a custom handler:** +The default handler often writes resources to a temporary folder, which can be undesirable for security or performance reasons. By overriding `HandleResource`, you decide exactly where and how each byte is stored. + +### Extending the handler for file output + +If you prefer to write each resource to a specific folder, modify the method as follows: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## How to save htmldocument using the custom handler + +Now that we have both the `HTMLDocument` instance and the `MyHandler` implementation, we can persist the document. The `Save` method accepts any `ResourceHandler` subclass, allowing you to plug in your custom logic. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +When `Save` runs, the library will: + +1. Walk the DOM tree. +2. Detect external resources (e.g., ``). +3. Call `handler.HandleResource` for each resource. +4. Write the resource data into the returned stream. +5. Finalize the main HTML output (often as a separate file or stream). + +### Verifying the result + +If you used the file‑system version of `MyHandler`, you should see an `output` folder with the original HTML file and any referenced assets. For the `MemoryStream` version, you can inspect the stream length to confirm data was written: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Full, runnable example + +Below is a single, copy‑paste‑ready program that demonstrates the entire flow. It includes error handling, disposal of streams, and comments that explain each step. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Expected output** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +After running the program, the `output` directory contains: + +- `index.html` (the main document) +- Any additional files the library generated (e.g., images, CSS) + +## Advanced variations and edge cases + +### Saving to a `MemoryStream` for in‑memory processing + +If you need the final HTML as a string or want to send it over HTTP without touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +After `htmlDoc.Save(handler)`, you can read the HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Handling large resources safely + +When dealing with large images or PDFs, avoid loading the entire file into memory. Instead, return a `FileStream` that writes directly to disk, as shown earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + +### Thread‑safety considerations + +`HTMLDocument` instances are **not** thread‑safe. If you need to process multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` per thread, or synchronize access with a `lock`. + +### Disposing streams + +Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return streams that need disposal. In the examples above, the library disposes the streams automatically after writing. If you manage streams yourself (e.g., opening a `FileStream` before calling `Save`), wrap them in `using` statements. + +## Summary + +This guide showed you how to **load html string** into an `HTMLDocument`, **create custom handler** to dictate resource storage, and **how to save htmldocument** with **custom resource handling**. You now have: + +1. A clear way to turn raw HTML into a DOM object. +2. A reusable `ResourceHandler` subclass that can write resources to memory, disk, or cloud storage. +3. A complete, runnable program that demonstrates the full workflow. + +## Next steps + +- Explore other `ResourceHandler` overrides such as `HandleCss` or `HandleFont` if your library provides them. +- Combine this approach with a PDF conversion step to generate PDFs from HTML while keeping full control over embedded assets. +- Review the library’s documentation for additional options like *compression*, *caching*, or *asynchronous* saving. + +Feel free to experiment with different storage strategies, and share your findings in the comments or on your favorite developer community. Happy coding! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/english/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/og-image.png b/html/english/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/og-image.png new file mode 100644 index 0000000000000000000000000000000000000000..5c082fea019499842acbc55f4e40e5be89f83a62 GIT binary patch literal 44588 zcmcfocT`hd^froOLj(~O5d{Gi6#)^Irc@ifw;)|WYA7Ov&;lw=q^UINO?nBvg%Ih| zdnZJCC$s>8B%Fos@7!^}JHBzx_t)9(k%aBe&MI@wIiF`fD^N{EmY$Y{mWqmsUS96C z1{KxmLMp10E;J{>mEX5l>8Pmkx8+~I&~hDH#ll>#$a4JNtf~}y{jrkqv&^~mD{!k6 zzM+$_y{KwBKEg>R1-jC7wfhg{X)YT0+>^Wc`U?ts*wR}g`vG2snvljM1!SsLqeR4x z4@{)4{N#D56uB1f?K9xVsFDd!l4*`VeEfLv`0e@ge}CP)dHVRTix-buL`6e$;`r^f z@9`_u$(R4$PTV?vOLh}TJ^sc`Mk~ajeckA18;yJB8urTEybWx}_f7ON<`YD?!=G?h z>_nV9eonHzs#XPA{oie4|6TfDA3cyI_SvtXx%8&F#=W@=<(PjBizUdy#u@MacS-lm zaVPu)L@9BqCI8x+e+~YxjsFL|;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AX*cz;R z<pr5DJ+i(eD$GVQ*LN>#!cy`UaC7?03#4! zeGFevBsWkAg(oH^I?~WUdq2Ce%ndxQ^pcmK!;Q?-5;oW7gIR(6icB$Vxs-X@e*RFu z(#hA1+rWbA`hPfp;gPl-C9swz-Avbshk=V!R%u zat<6~2$90e<=d~tx3-4$^ehG?rdHcKt89N+8Rf8*^gjyl-?%|mTOZOMqugAnLgq+4 z5f9yB!%LW`O3bdIfj6`c0On>PAhA$_Tnqwqd*%JG6b;C1F|nW^9CRKVEImIh(9j%% zVqeYX;AQXVP9<)mo3seJtY_*fvHpcggFpow3kVPA14_%YPE{F}+Zn!U2c|q+l|3qE zt`7Wk+M7*V_CaD0)yo++B59RXH=r4muC6Bf&b<%h5>yx0 z&{4wQV3i3E9OcbyQfRIkw`IG#pn8HJL9`n>`}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir HTML en PDF en C# – définir le style de police par programme + +Si vous devez **convertir HTML en PDF** dans une application .NET, ce tutoriel vous guide à travers une solution complète, prête pour la production. Vous verrez comment **définir le style de police par programme**, améliorer le rendu des images et activer le hinting du texte — le tout sans quitter votre code C#. + +Convertir des pages web en PDF est une exigence courante pour les rapports, la facturation et l’archivage. Ce guide couvre tout, de la configuration du projet à un exemple complet et exécutable. À la fin de l’article, vous pourrez générer des PDF qui conservent la mise en page, la typographie et la fidélité visuelle. + +## Ce que vous allez apprendre + +* Comment ajouter le package NuGet requis et importer les espaces de noms. +* Comment configurer `HtmlConversionOptions` pour contrôler le rendu. +* Comment **définir le style de police par programme** à l’aide des drapeaux `WebFontStyle`. +* Comment activer l’antialiasing pour les images et le hinting pour le texte. +* Comment invoquer la classe `Converter` pour produire le fichier PDF final. + +Le tutoriel suppose que vous avez Visual Studio 2022 (ou une version ultérieure) et .NET 6 ou plus installé. Aucun outil supplémentaire n’est requis. + +## Prérequis + +| Exigence | Raison | +|---|---| +| .NET 6 SDK ou version ultérieure | Fournit le runtime pour le projet C#. | +| Visual Studio 2022 (ou tout IDE) | Permet une création de projet et un débogage faciles. | +| Accès Internet pour restaurer les packages NuGet | Nécessaire pour télécharger la bibliothèque de conversion. | +| Un fichier HTML simple (`input.html`) | Sert de document source pour la conversion. | + +> **Astuce pro :** Conservez le fichier HTML dans le même dossier que le projet pour éviter les problèmes liés aux chemins. + +## Étape 1 : Installer la bibliothèque de conversion + +L’exemple de code utilise la bibliothèque **GroupDocs.Conversion for .NET**, qui propose `HtmlConversionOptions` et une classe `Converter`. Installez‑la via le Gestionnaire de packages NuGet : + +```bash +dotnet add package GroupDocs.Conversion +``` + +Le package ajoute les types nécessaires à votre projet et récupère toutes les dépendances. + +## Étape 2 : Créer un projet console C# + +Ouvrez une invite de commande et exécutez : + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Cela crée une application console minimale nommée `HtmlToPdfDemo`. Ouvrez le fichier `Program.cs` généré ; vous remplacerez son contenu par l’exemple complet plus tard. + +## Étape 3 : Configurer les options de conversion – définir le style de police par programme + +La classe `HtmlConversionOptions` vous permet d’ajuster finement la façon dont le moteur HTML rend la page. Pour **définir le style de police par programme**, combinez les valeurs de l’énumération `WebFontStyle` à l’aide d’un OU binaire : + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Pourquoi c’est important :** +* `WebFontStyle.Bold | WebFontStyle.Italic` indique au moteur d’appliquer les deux styles à tout texte utilisant la police par défaut. +* L’antialiasing réduit les bords dentelés des images raster, surtout lors du redimensionnement. +* Le hinting aligne les contours des glyphes sur la grille de pixels, améliorant la lisibilité sur les écrans basse résolution et dans le PDF résultant. + +## Étape 4 : Effectuer la conversion + +Une fois les options préparées, appelez la classe `Converter`. La méthode `Convert` prend trois arguments : le chemin du fichier HTML source, le chemin du fichier PDF de destination et l’objet d’options. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +La méthode s’exécute de façon synchrone et lève une exception si le fichier source ne peut pas être lu ou si le chemin de sortie est invalide. Enveloppez l’appel dans un bloc try‑catch pour le code de production. + +## Étape 5 : Vérifier le résultat + +Après la fin du programme, ouvrez `output.pdf` avec n’importe quel lecteur PDF. Vous devriez voir : + +* Du texte rendu en **gras et italique** (même si le HTML d’origine ne spécifiait pas ces styles). +* Des images plus lisses grâce à l’antialiasing. +* Une meilleure netteté du texte grâce au hinting, notamment pour les petites tailles de police. + +Si le PDF ne reflète pas les styles attendus, vérifiez que le fichier HTML référence une police web‑safe ou inclut une règle `@font-face` que le convertisseur peut charger. + +## Exemple complet et exécutable + +Voici un programme autonome qui intègre toutes les étapes précédentes. Copiez le code dans `Program.cs`, placez un fichier `input.html` à côté et exécutez `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Sortie console attendue** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Ouvrez le PDF généré pour confirmer l’application des styles. + +## Gestion des cas limites courants + +| Situation | Approche recommandée | +|---|---| +| **CSS ou polices externes** | Placez les fichiers CSS et les ressources de police dans le même dossier que `input.html` ou référencez‑les avec des URL absolues accessibles depuis la machine qui effectue la conversion. | +| **Documents HTML volumineux** | Augmentez la limite de mémoire par défaut en ajustant `ConversionConfig` si vous rencontrez une `OutOfMemoryException`. | +| **Contenu dynamique (JavaScript)** | La bibliothèque n’exécute pas JavaScript. Rendu pré‑serveur des parties dynamiques ou utilisez un navigateur sans tête pour produire un instantané HTML statique avant la conversion. | +| **Caractères Unicode non affichés** | Assurez‑vous que le HTML déclare `` et que les polices sources contiennent les glyphes requis. | +| **Taille de page incorrecte** | Définissez `conversionOptions.PageSize = PageSize.A4` (ou une autre valeur d’énumération) pour imposer des dimensions cohérentes. | + +## Conseils de performance + +* Réutilisez une seule instance de `Converter` lors de la conversion de nombreux fichiers ; cela réduit le temps de démarrage. +* Désactivez les fonctionnalités de rendu inutiles (par ex., `EnableHyperlinks`) si vous n’en avez pas besoin, ce qui accélère le traitement. +* Écrivez le PDF dans un flux mémoire lorsque vous devez l’envoyer directement via HTTP au lieu de l’enregistrer sur disque. + +## Prochaines étapes + +Maintenant que vous pouvez **convertir HTML en PDF** avec des paramètres de police personnalisés, explorez les sujets connexes suivants : + +* **Définir les marges de page par programme** – ajustez `conversionOptions.Margin` pour contrôler les espaces blancs. +* **Ajouter des filigranes** – utilisez `PdfConversionOptions` pour superposer du texte ou des images. +* **Conversion par lots** – parcourez une collection de fichiers HTML et réutilisez le même objet d’options. + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques présentées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et à explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Convert HTML to PDF in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convert SVG to PDF in .NET with Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/french/net/working-with-html-documents/_index.md b/html/french/net/working-with-html-documents/_index.md index e18bb71d72..f5c9324748 100644 --- a/html/french/net/working-with-html-documents/_index.md +++ b/html/french/net/working-with-html-documents/_index.md @@ -41,6 +41,8 @@ Maintenant, passons à un niveau supérieur de compétences. L'édition de docum Apprenez à enregistrer du HTML en C# en utilisant un gestionnaire de ressources personnalisé pour contrôler le flux de sortie et les ressources liées. ### [Comment mettre en gras un titre avec CSS & C# – Guide complet étape par étape](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Charger une chaîne HTML en C# – guide complet avec gestionnaire personnalisé](./load-html-string-in-c-complete-guide-with-custom-handler/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/french/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/french/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..05f9c7ba45 --- /dev/null +++ b/html/french/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-08-03 +description: Charger une chaîne HTML en C# et créer un gestionnaire personnalisé pour + enregistrer le HTMLDocument. Apprenez comment enregistrer le HTMLDocument avec une + gestion personnalisée des ressources. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: fr +lastmod: 2026-08-03 +og_description: Charger une chaîne HTML en C# et utiliser un gestionnaire personnalisé + pour enregistrer HTMLDocument. Ce tutoriel montre l’implémentation complète et les + meilleures pratiques. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Charger une chaîne HTML en C# – guide pas à pas du gestionnaire personnalisé +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Charger une chaîne HTML en C# – guide complet avec gestionnaire personnalisé +url: /fr/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Charger une chaîne HTML en C# – guide complet avec gestionnaire personnalisé + +Si vous devez **charger une chaîne HTML** dans une application C#, ce tutoriel vous montre exactement comment le faire et comment **créer un gestionnaire personnalisé** pour la gestion des ressources. Vous apprendrez également **comment enregistrer un htmldocument** en utilisant **une gestion des ressources personnalisée** afin que chaque image, fichier CSS ou script soit écrit exactement où vous le souhaitez. + +Nous parcourrons l’ensemble du processus — de la transformation d’une chaîne HTML brute en objet `HTMLDocument`, à la mise en œuvre d’une sous‑classe `ResourceHandler` qui contrôle l’endroit où chaque ressource est stockée. À la fin, vous disposerez d’un exemple autonome, prêt pour la production, que vous pourrez intégrer à n’importe quel projet .NET. + +## Prérequis + +- .NET 6.0 ou ultérieur (le code fonctionne également avec .NET Framework 4.7+) +- Une référence à la bibliothèque qui fournit `HTMLDocument`, `ResourceHandler` et `ResourceInfo` (par ex. *HtmlRenderer* ou une bibliothèque similaire HTML‑to‑PDF/DOM) +- Connaissances de base en syntaxe C# et flux + +> **Astuce :** Si vous utilisez Visual Studio, activez les *types de référence nullable* (`enable`) pour détecter les bugs liés aux nulls dès le départ. + +## Comment charger une chaîne HTML dans HTMLDocument + +La première étape consiste à convertir une chaîne HTML simple en objet `HTMLDocument` que la bibliothèque peut exploiter. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Pourquoi c’est important :** +`HTMLDocument` analyse le balisage, construit un arbre DOM et prépare les ressources (images, feuilles de style, etc.) pour un enregistrement ultérieur. Passer directement une chaîne évite l’utilisation de fichiers temporaires et maintient le flux de travail en mémoire. + +### Pièges courants + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| `htmlContent` est `null` | La variable chaîne n’a jamais été assignée. | Validez avant de créer le document : `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Problèmes d’encodage | La bibliothèque suppose UTF‑8 alors que la source utilise un autre encodage. | Fournissez une surcharge `Encoding` explicite si disponible, ou assurez‑vous que la chaîne est correctement décodée. | + +## Créer un gestionnaire personnalisé pour la gestion des ressources + +Un **gestionnaire de ressources personnalisé** vous donne un contrôle total sur la façon dont la bibliothèque écrit les ressources externes (images, CSS, polices). Voici une implémentation minimale qui écrit chaque ressource dans un `MemoryStream`. Vous pouvez remplacer le corps par une logique de système de fichiers, de stockage cloud ou toute autre destination. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Pourquoi vous avez besoin d’un gestionnaire personnalisé :** +Le gestionnaire par défaut écrit souvent les ressources dans un dossier temporaire, ce qui peut être indésirable pour des raisons de sécurité ou de performances. En surchargeant `HandleResource`, vous décidez exactement où et comment chaque octet est stocké. + +### Étendre le gestionnaire pour une sortie fichier + +Si vous préférez écrire chaque ressource dans un dossier spécifique, modifiez la méthode comme suit : + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Comment enregistrer htmldocument en utilisant le gestionnaire personnalisé + +Maintenant que nous disposons à la fois de l’instance `HTMLDocument` et de l’implémentation `MyHandler`, nous pouvons persister le document. La méthode `Save` accepte n’importe quelle sous‑classe `ResourceHandler`, vous permettant d’y brancher votre logique personnalisée. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Lorsque `Save` s’exécute, la bibliothèque : + +1. Parcourt l’arbre DOM. +2. Détecte les ressources externes (ex. : ``). +3. Appelle `handler.HandleResource` pour chaque ressource. +4. Écrit les données de la ressource dans le flux retourné. +5. Finalise la sortie HTML principale (souvent sous forme de fichier ou de flux séparé). + +### Vérifier le résultat + +Si vous avez utilisé la version système de fichiers de `MyHandler`, vous devriez voir un dossier `output` contenant le fichier HTML d’origine et toutes les ressources référencées. Pour la version `MemoryStream`, vous pouvez inspecter la longueur du flux pour confirmer que les données ont été écrites : + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Exemple complet, exécutable + +Voici un programme autonome, prêt à copier‑coller, qui illustre l’ensemble du flux. Il inclut la gestion des erreurs, la libération des flux et des commentaires expliquant chaque étape. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Sortie attendue** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Après l’exécution du programme, le répertoire `output` contient : + +- `index.html` (le document principal) +- Tous les fichiers supplémentaires générés par la bibliothèque (ex. : images, CSS) + +## Variantes avancées et cas limites + +### Enregistrement dans un `MemoryStream` pour un traitement en mémoire + +Si vous avez besoin du HTML final sous forme de chaîne ou que vous souhaitez l’envoyer via HTTP sans toucher au disque, remplacez `MyHandler` par une version qui renvoie un `MemoryStream` partagé : + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Après `htmlDoc.Save(handler)`, vous pouvez lire le HTML : + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Gestion sécurisée de ressources volumineuses + +Lorsque vous traitez de grandes images ou PDF, évitez de charger le fichier entier en mémoire. Retournez plutôt un `FileStream` qui écrit directement sur le disque, comme montré précédemment. Cela prévient les `OutOfMemoryException` dans les scénarios à fort débit. + +### Considérations de thread‑safety + +Les instances `HTMLDocument` ne sont **pas** thread‑safe. Si vous devez traiter plusieurs chaînes HTML simultanément, créez un `HTMLDocument` et un `MyHandler` distincts par thread, ou synchronisez l’accès avec un `lock`. + +### Libération des flux + +Tant `HTMLDocument.Save` que `ResourceHandler.HandleResource` peuvent retourner des flux nécessitant d’être libérés. Dans les exemples ci‑dessus, la bibliothèque libère automatiquement les flux après écriture. Si vous gérez vous‑même les flux (par ex. en ouvrant un `FileStream` avant d’appeler `Save`), encapsulez‑les dans des blocs `using`. + +## Résumé + +Ce guide vous a montré comment **charger une chaîne HTML** dans un `HTMLDocument`, **créer un gestionnaire personnalisé** pour définir le stockage des ressources, et **enregistrer htmldocument** avec **une gestion des ressources personnalisée**. Vous disposez maintenant de : + +1. Une méthode claire pour transformer du HTML brut en objet DOM. +2. Une sous‑classe réutilisable `ResourceHandler` capable d’écrire les ressources en mémoire, sur disque ou dans le cloud. +3. Un programme complet, exécutable, démontrant le flux complet. + +## Prochaines étapes + +- Explorez d’autres surcharges de `ResourceHandler` comme `HandleCss` ou `HandleFont` si votre bibliothèque les propose. +- Combinez cette approche avec une étape de conversion PDF pour générer des PDF à partir de HTML tout en gardant le contrôle total sur les actifs incorporés. +- Consultez la documentation de la bibliothèque pour des options supplémentaires telles que *compression*, *caching* ou enregistrement *asynchrone*. + +N’hésitez pas à expérimenter différentes stratégies de stockage, et partagez vos découvertes dans les commentaires ou sur votre communauté de développeurs préférée. Bon codage ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques présentées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités d’API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 607896d28b..133a0db413 100644 --- a/html/german/net/html-extensions-and-conversions/_index.md +++ b/html/german/net/html-extensions-and-conversions/_index.md @@ -30,49 +30,51 @@ Bei der Webentwicklung müssen HTML-Dokumente häufig in verschiedene Formate ko ## Erste Schritte mit Aspose.HTML -Sind Sie bereit, loszulegen? Die Tutorials von Aspose.HTML für .NET richten sich sowohl an Anfänger als auch an erfahrene Entwickler. Egal, ob Sie neu bei HTML-Erweiterungen und -Konvertierungen sind oder fortgeschrittene Tipps suchen, unsere Schritt-für-Schritt-Anleitungen sind auf Ihre Bedürfnisse zugeschnitten. +Sind Sie bereit, loszulegen? Die Tutorials von Aspose.HTML für .NET richten sich sowohl an Anfänger als auch an erfahrene Entwickler. Egal, ob Sie neu bei HTML-Erweiterungen und -Konvertierungen sind oder fortgeschrittene Tipps suchen, unsere Schritt‑für‑Schritt‑Anleitungen sind auf Ihre Bedürfnisse zugeschnitten. ## Warum Aspose.HTML für .NET? -Aspose.HTML für .NET ist nicht nur eine Bibliothek; es verändert die Welt der Webentwicklung grundlegend. Es bietet eine umfassende Palette an Funktionen und Tools, die Ihre HTML-bezogenen Aufgaben rationalisieren. Am Ende dieser Tutorials verfügen Sie über das Wissen und die Fähigkeiten, um das Potenzial von Aspose.HTML für .NET optimal zu nutzen. +Aspose.HTML für .NET ist nicht nur eine Bibliothek; es verändert die Welt der Webentwicklung grundlegend. Es bietet eine umfassende Palette an Funktionen und Tools, die Ihre HTML‑bezogenen Aufgaben rationalisieren. Am Ende dieser Tutorials verfügen Sie über das Wissen und die Fähigkeiten, um das Potenzial von Aspose.HTML für .NET optimal zu nutzen. ## 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. +### [HTML in PDF konvertieren in C# – Schriftstil programmgesteuert festlegen](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET den Schriftstil beim HTML‑zu‑PDF‑Export in C# programmgesteuert festlegen. ### [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‑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/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/german/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..9e40c54d9d --- /dev/null +++ b/html/german/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: HTML in PDF mit C# konvertieren und die vollständige Rendersteuerung + nutzen. Erfahren Sie, wie Sie den Schriftstil programmgesteuert festlegen, Antialiasing + aktivieren und die Textklarheit verbessern. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: de +lastmod: 2026-08-03 +og_description: HTML in PDF mit C# konvertieren mit detaillierten Optionen. Dieser + Leitfaden zeigt, wie man Schriftstil programmgesteuert festlegt, Antialiasing aktiviert + und hochwertige PDFs erzeugt. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: HTML in PDF konvertieren in C# – vollständige Rendering‑Steuerung +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: HTML in PDF konvertieren in C# – Schriftstil programmgesteuert festlegen +url: /de/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML in PDF konvertieren in C# – Schriftstil programmgesteuert festlegen + +Wenn Sie **HTML in PDF** in einer .NET‑Anwendung konvertieren müssen, führt Sie dieses Tutorial durch eine vollständige, produktionsreife Lösung. Sie sehen, wie Sie **Schriftstil programmgesteuert festlegen**, die Bilddarstellung verbessern und Text‑Hinting aktivieren – alles, ohne Ihren C#‑Code zu verlassen. + +Das Konvertieren von Webseiten zu PDFs ist eine häufige Anforderung für Berichte, Rechnungen und Archivierung. Dieser Leitfaden deckt alles von der Projekt‑Einrichtung bis zu einem vollständigen, ausführbaren Beispiel ab. Am Ende des Artikels können Sie PDFs erzeugen, die Layout, Typografie und visuelle Treue bewahren. + +## Was Sie lernen werden + +* Wie Sie das erforderliche NuGet‑Paket hinzufügen und Namespaces importieren. +* Wie Sie `HtmlConversionOptions` konfigurieren, um das Rendering zu steuern. +* Wie Sie **Schriftstil programmgesteuert** mit den `WebFontStyle`‑Flags festlegen. +* Wie Sie Antialiasing für Bilder und Hinting für Text aktivieren. +* Wie Sie die `Converter`‑Klasse aufrufen, um die endgültige PDF‑Datei zu erzeugen. + +Das Tutorial geht davon aus, dass Sie Visual Studio 2022 (oder neuer) und .NET 6 oder neuer installiert haben. Es wird kein zusätzliches Werkzeug benötigt. + +## Voraussetzungen + +| Anforderung | Grund | +|---|---| +| .NET 6 SDK oder neuer | Stellt die Laufzeit für das C#‑Projekt bereit. | +| Visual Studio 2022 (oder jede IDE) | Ermöglicht einfache Projekterstellung und Debugging. | +| Internetzugang zum Wiederherstellen von NuGet‑Paketen | Wird benötigt, um die Konvertierungsbibliothek herunterzuladen. | +| Eine einfache HTML‑Datei (`input.html`) | Dient als Quelldokument für die Konvertierung. | + +> **Profi‑Tipp:** Bewahren Sie die HTML‑Datei im selben Ordner wie das Projekt auf, um pfadbezogene Probleme zu vermeiden. + +## Schritt 1: Installieren der Konvertierungsbibliothek + +Das Code‑Beispiel verwendet die **GroupDocs.Conversion for .NET**‑Bibliothek, die `HtmlConversionOptions` und eine `Converter`‑Klasse bereitstellt. Installieren Sie sie über den NuGet‑Paket‑Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Das Paket fügt Ihrem Projekt die erforderlichen Typen hinzu und zieht alle Abhängigkeiten nach. + +## Schritt 2: Erstellen eines C#‑Konsolenprojekts + +Öffnen Sie ein Befehlsfenster und führen Sie aus: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Dies erstellt eine minimale Konsolenanwendung namens `HtmlToPdfDemo`. Öffnen Sie die erzeugte Datei `Program.cs`; Sie werden deren Inhalt später durch das vollständige Beispiel ersetzen. + +## Schritt 3: Konvertierungsoptionen konfigurieren – Schriftstil programmgesteuert festlegen + +Die Klasse `HtmlConversionOptions` ermöglicht es Ihnen, das Rendering der HTML‑Engine fein abzustimmen. Um **Schriftstil programmgesteuert festzulegen**, kombinieren Sie die Aufzählungswerte von `WebFontStyle` mittels eines bitweisen OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Warum das wichtig ist:** +* `WebFontStyle.Bold | WebFontStyle.Italic` weist den Renderer an, beide Stile auf jeden Text anzuwenden, der die Standardschrift verwendet. +* Antialiasing reduziert gezackte Kanten bei Rasterbildern, insbesondere beim Skalieren. +* Hinting richtet Glyphen‑Konturen an Pixelgittern aus, verbessert die Lesbarkeit auf niedrigauflösenden Bildschirmen und im resultierenden PDF. + +## Schritt 4: Durchführung der Konvertierung + +Nachdem die Optionen vorbereitet sind, rufen Sie die `Converter`‑Klasse auf. Die Methode `Convert` erwartet drei Argumente: den Pfad zur Quell‑HTML‑Datei, den Pfad zur Ziel‑PDF‑Datei und das Options‑Objekt. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Die Methode läuft synchron und wirft eine Ausnahme, wenn die Quelldatei nicht gelesen werden kann oder der Ausgabepfad ungültig ist. Umgeben Sie den Aufruf in Produktionscode mit einem try‑catch‑Block. + +## Schritt 5: Ergebnis überprüfen + +Nachdem das Programm beendet ist, öffnen Sie `output.pdf` mit einem beliebigen PDF‑Betrachter. Sie sollten sehen: + +* Text, der in **fett und kursiv** gerendert wird (auch wenn das ursprüngliche HTML diese Stile nicht angegeben hat). +* Bilder erscheinen dank Antialiasing glatter. +* Die Textklarheit wird durch Hinting verbessert, insbesondere bei kleinen Schriftgrößen. + +Falls das PDF die erwarteten Stile nicht widerspiegelt, prüfen Sie, ob die HTML‑Datei eine web‑sichere Schrift referenziert oder eine `@font-face`‑Regel enthält, die der Converter laden kann. + +## Vollständiges, ausführbares Beispiel + +Unten finden Sie ein eigenständiges Programm, das alle vorherigen Schritte integriert. Kopieren Sie den Code in `Program.cs`, legen Sie eine `input.html`‑Datei daneben und führen Sie `dotnet run` aus. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Erwartete Konsolenausgabe** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Öffnen Sie das erzeugte PDF, um die angewendeten Stile zu bestätigen. + +## Umgang mit häufigen Sonderfällen + +| Situation | Empfohlener Ansatz | +|---|---| +| **Externe CSS‑ oder Schriftdateien** | Platzieren Sie CSS‑Dateien und Schriftressourcen im selben Ordner wie `input.html` oder referenzieren Sie sie mit absoluten URLs, die vom ausführenden Rechner erreichbar sind. | +| **Große HTML‑Dokumente** | Erhöhen Sie das Standard‑Speicherlimit, indem Sie `ConversionConfig` anpassen, falls Sie eine `OutOfMemoryException` erhalten. | +| **Dynamischer Inhalt (JavaScript)** | Die Bibliothek führt kein JavaScript aus. Rendern Sie dynamische Teile serverseitig vor oder verwenden Sie einen Headless‑Browser, um vor der Konvertierung einen statischen HTML‑Snapshot zu erzeugen. | +| **Unicode‑Zeichen werden nicht angezeigt** | Stellen Sie sicher, dass das HTML `` deklariert und die Quellschriften die benötigten Glyphen enthalten. | +| **Falsche Seitengröße** | Setzen Sie `conversionOptions.PageSize = PageSize.A4` (oder einen anderen Enum‑Wert), um konsistente Abmessungen zu erzwingen. | + +## Leistungstipps + +* Verwenden Sie eine einzelne `Converter`‑Instanz beim Konvertieren vieler Dateien; dies reduziert den Start‑Overhead. +* Deaktivieren Sie unnötige Rendering‑Funktionen (z. B. `EnableHyperlinks`), wenn Sie sie nicht benötigen, was die Verarbeitung beschleunigt. +* Schreiben Sie das PDF in einen Memory‑Stream, wenn Sie es direkt über HTTP senden müssen, anstatt es auf die Festplatte zu schreiben. + +## Nächste Schritte + +Jetzt, da Sie **HTML in PDF** mit benutzerdefinierten Schriftarteinstellungen konvertieren können, erkunden Sie diese verwandten Themen: + +- **Seitenränder programmgesteuert festlegen** – passen Sie `conversionOptions.Margin` an, um den Weißraum zu steuern. +- **Wasserzeichen hinzufügen** – verwenden Sie `PdfConversionOptions`, um Text oder Bilder zu überlagern. +- **Batch‑Konvertierung** – iterieren Sie über eine Sammlung von HTML‑Dateien und verwenden Sie dasselbe Options‑Objekt erneut. + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [HTML in PDF konvertieren in .NET mit Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [HTML‑Dokument mit formatiertem Text erstellen und nach PDF exportieren – Vollständige Anleitung](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [SVG in PDF konvertieren in .NET mit Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/german/net/working-with-html-documents/_index.md b/html/german/net/working-with-html-documents/_index.md index 20ea4c9d75..8cfc32a8e0 100644 --- a/html/german/net/working-with-html-documents/_index.md +++ b/html/german/net/working-with-html-documents/_index.md @@ -41,6 +41,10 @@ Lassen Sie uns nun Ihre Fähigkeiten auf die nächste Ebene bringen. Das Bearbei Erfahren Sie, wie Sie HTML in C# mit einem benutzerdefinierten Ressourcen-Handler speichern können. ### [Überschrift mit CSS & C# fett formatieren – Komplett‑Schritt‑für‑Schritt‑Anleitung](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [HTML-String in C# laden – vollständige Anleitung mit benutzerdefiniertem Handler](./load-html-string-in-c-complete-guide-with-custom-handler/) + +Erfahren Sie, wie Sie HTML-Strings in C# mit einem benutzerdefinierten Handler laden können. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/german/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/german/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..2c078eb3bd --- /dev/null +++ b/html/german/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-08-03 +description: HTML-String in C# laden und benutzerdefinierten Handler erstellen, um + HTMLDocument zu speichern. Erfahren Sie, wie Sie HTMLDocument mit benutzerdefinierter + Ressourcenverwaltung speichern. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: de +lastmod: 2026-08-03 +og_description: Lade HTML-String in C# und verwende einen benutzerdefinierten Handler, + um das HTMLDocument zu speichern. Dieses Tutorial zeigt die vollständige Implementierung + und bewährte Vorgehensweisen. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: HTML-String in C# laden – Schritt‑für‑Schritt-Anleitung für benutzerdefinierten + Handler +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: HTML-String in C# laden – vollständige Anleitung mit benutzerdefiniertem Handler +url: /de/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML-String in C# laden – vollständige Anleitung mit benutzerdefiniertem Handler + +Wenn Sie **HTML-String laden** in einer C#‑Anwendung müssen, zeigt Ihnen dieses Tutorial genau, wie Sie das tun und wie Sie einen **benutzerdefinierten Handler** für die Ressourcenverwaltung **erstellen**. Sie lernen außerdem **wie man htmldocument speichert** mit **benutzerdefinierter Ressourcenverwaltung**, sodass jedes Bild, jede CSS‑Datei oder jedes Skript genau dort geschrieben wird, wo Sie es wünschen. + +Wir gehen den gesamten Prozess durch – vom Umwandeln eines rohen HTML‑Strings in ein `HTMLDocument`‑Objekt bis hin zur Implementierung einer `ResourceHandler`‑Unterklasse, die steuert, wo jede Ressource gespeichert wird. Am Ende haben Sie ein eigenständiges, produktionsreifes Beispiel, das Sie in jedes .NET‑Projekt einbinden können. + +## Voraussetzungen + +- .NET 6.0 oder höher (der Code funktioniert auch mit .NET Framework 4.7+) +- Ein Verweis auf die Bibliothek, die `HTMLDocument`, `ResourceHandler` und `ResourceInfo` bereitstellt (z. B. *HtmlRenderer* oder eine ähnliche HTML‑zu‑PDF/DOM‑Bibliothek) +- Grundlegende Kenntnisse der C#‑Syntax und von Streams + +> **Profi‑Tipp:** Wenn Sie Visual Studio verwenden, aktivieren Sie *nullable reference types* (`enable`), um Null‑bezogene Fehler frühzeitig zu erkennen. + +## Wie man HTML‑String in HTMLDocument lädt + +Der erste Schritt besteht darin, einen einfachen HTML‑String in ein `HTMLDocument`‑Objekt zu konvertieren, mit dem die Bibliothek arbeiten kann. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Warum das wichtig ist:** +`HTMLDocument` analysiert das Markup, baut einen DOM‑Baum auf und bereitet Ressourcen (Bilder, Stylesheets usw.) für das spätere Speichern vor. Das direkte Übergeben eines Strings vermeidet temporäre Dateien und hält den Arbeitsablauf im Speicher. + +### Häufige Fallstricke + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| `htmlContent` ist `null` | Die String‑Variable wurde nie zugewiesen. | Vor dem Erstellen des Dokuments prüfen: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Kodierungsprobleme | Die Bibliothek geht von UTF‑8 aus, aber die Quelle verwendet eine andere Kodierung. | Ein explizites `Encoding`‑Überladung bereitstellen, falls verfügbar, oder sicherstellen, dass der String korrekt dekodiert ist. | + +## Benutzerdefinierten Handler für die Ressourcenverwaltung erstellen + +Ein **benutzerdefinierter Ressourcen‑Handler** gibt Ihnen die volle Kontrolle darüber, wie die Bibliothek externe Ressourcen (Bilder, CSS, Schriften) schreibt. Unten steht eine minimale Implementierung, die jede Ressource in einen `MemoryStream` schreibt. Sie können den Body durch Dateisystem‑Logik, Cloud‑Speicher oder ein anderes Ziel ersetzen. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Warum Sie einen benutzerdefinierten Handler benötigen:** +Der Standard‑Handler schreibt Ressourcen häufig in einen temporären Ordner, was aus Sicherheits‑ oder Leistungsgründen unerwünscht sein kann. Durch das Überschreiben von `HandleResource` entscheiden Sie genau, wo und wie jedes Byte gespeichert wird. + +### Erweiterung des Handlers für Dateiausgabe + +Wenn Sie jede Ressource in einen bestimmten Ordner schreiben möchten, passen Sie die Methode wie folgt an: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Wie man htmldocument mit dem benutzerdefinierten Handler speichert + +Jetzt, wo wir sowohl die `HTMLDocument`‑Instanz als auch die `MyHandler`‑Implementierung haben, können wir das Dokument speichern. Die `Save`‑Methode akzeptiert jede `ResourceHandler`‑Unterklasse, sodass Sie Ihre benutzerdefinierte Logik einbinden können. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Wenn `Save` ausgeführt wird, führt die Bibliothek Folgendes aus: + +1. Den DOM‑Baum durchlaufen. +2. Externe Ressourcen erkennen (z. B. ``). +3. `handler.HandleResource` für jede Ressource aufrufen. +4. Die Ressourcendaten in den zurückgegebenen Stream schreiben. +5. Den Haupt‑HTML‑Ausgabe abschließen (oft als separate Datei oder Stream). + +### Ergebnis überprüfen + +Wenn Sie die Dateisystem‑Version von `MyHandler` verwendet haben, sollten Sie einen `output`‑Ordner mit der ursprünglichen HTML‑Datei und allen referenzierten Assets sehen. Für die `MemoryStream`‑Version können Sie die Stream‑Länge prüfen, um zu bestätigen, dass Daten geschrieben wurden: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Vollständiges, ausführbares Beispiel + +Unten steht ein einzelnes, sofort kopier‑fertiges Programm, das den gesamten Ablauf demonstriert. Es enthält Fehlerbehandlung, das Freigeben von Streams und Kommentare, die jeden Schritt erklären. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Erwartete Ausgabe** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Nach dem Ausführen des Programms enthält das Verzeichnis `output`: + +- `index.html` (das Hauptdokument) +- Alle zusätzlichen Dateien, die die Bibliothek erzeugt hat (z. B. Bilder, CSS) + +## Erweiterte Varianten und Sonderfälle + +### Speichern in einen `MemoryStream` für In‑Memory‑Verarbeitung + +Wenn Sie das finale HTML als String benötigen oder es per HTTP senden wollen, ohne die Festplatte zu berühren, ersetzen Sie `MyHandler` durch eine Version, die einen gemeinsamen `MemoryStream` zurückgibt: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Nach `htmlDoc.Save(handler)` können Sie das HTML lesen: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Große Ressourcen sicher verarbeiten + +Beim Umgang mit großen Bildern oder PDFs sollten Sie vermeiden, die gesamte Datei in den Speicher zu laden. Stattdessen geben Sie einen `FileStream` zurück, der direkt auf die Festplatte schreibt, wie zuvor gezeigt. Das verhindert `OutOfMemoryException` in Szenarien mit hohem Durchsatz. + +### Überlegungen zur Thread‑Sicherheit + +`HTMLDocument`‑Instanzen sind **nicht** thread‑sicher. Wenn Sie mehrere HTML‑Strings gleichzeitig verarbeiten müssen, erstellen Sie für jeden Thread ein separates `HTMLDocument` und `MyHandler` oder synchronisieren Sie den Zugriff mit einem `lock`. + +### Streams freigeben + +Sowohl `HTMLDocument.Save` als auch `ResourceHandler.HandleResource` können Streams zurückgeben, die freigegeben werden müssen. In den obigen Beispielen gibt die Bibliothek die Streams nach dem Schreiben automatisch frei. Wenn Sie Streams selbst verwalten (z. B. einen `FileStream` öffnen, bevor Sie `Save` aufrufen), wickeln Sie sie in `using`‑Anweisungen ein. + +## Zusammenfassung + +Dieses Handbuch zeigte Ihnen, wie Sie **HTML‑String laden** in ein `HTMLDocument`, **einen benutzerdefinierten Handler erstellen**, um die Ressourcenspeicherung zu steuern, und **wie Sie htmldocument speichern** mit **benutzerdefinierter Ressourcenverwaltung**. Sie haben jetzt: + +1. Eine klare Methode, rohes HTML in ein DOM‑Objekt zu verwandeln. +2. Eine wiederverwendbare `ResourceHandler`‑Unterklasse, die Ressourcen in Speicher, Festplatte oder Cloud‑Speicher schreiben kann. +3. Ein vollständiges, ausführbares Programm, das den gesamten Workflow demonstriert. + +## Nächste Schritte + +- Untersuchen Sie weitere `ResourceHandler`‑Überschreibungen wie `HandleCss` oder `HandleFont`, falls Ihre Bibliothek diese bereitstellt. +- Kombinieren Sie diesen Ansatz mit einem PDF‑Konvertierungsschritt, um PDFs aus HTML zu erzeugen, während Sie die volle Kontrolle über eingebettete Assets behalten. +- Überprüfen Sie die Dokumentation der Bibliothek für zusätzliche Optionen wie *Kompression*, *Caching* oder *asynchrones* Speichern. + +Fühlen Sie sich frei, mit verschiedenen Speicherstrategien zu experimentieren, und teilen Sie Ihre Erkenntnisse in den Kommentaren oder in Ihrer Lieblings‑Entwickler‑Community. Viel Spaß beim Coden! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man HTML in C# speichert – Vollständige Anleitung mit benutzerdefiniertem Ressourcen‑Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [HTML aus String in C# erstellen – Leitfaden für benutzerdefinierten Ressourcen‑Handler](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Wie man HTML in C# zippt – HTML in Zip speichern](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 013b0ec4b6..8ba201288d 100644 --- a/html/greek/net/html-extensions-and-conversions/_index.md +++ b/html/greek/net/html-extensions-and-conversions/_index.md @@ -73,6 +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 σε PDF σε C# – ορισμός στυλ γραμματοσειράς προγραμματιστικά](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Μάθετε πώς να ορίσετε το στυλ γραμματοσειράς κατά τη μετατροπή HTML σε PDF με C# χρησιμοποιώντας το Aspose.HTML. ## Σύναψη diff --git a/html/greek/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/greek/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..dcdfba3c13 --- /dev/null +++ b/html/greek/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Μετατρέψτε HTML σε PDF σε C# με πλήρη έλεγχο απόδοσης. Μάθετε πώς να + ορίζετε το στυλ γραμματοσειράς προγραμματιστικά, να ενεργοποιείτε την εξομάλυνση + και να βελτιώνετε την καθαρότητα του κειμένου. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: el +lastmod: 2026-08-03 +og_description: Μετατρέψτε HTML σε PDF σε C# με λεπτομερείς επιλογές. Αυτός ο οδηγός + δείχνει πώς να ορίσετε το στυλ γραμματοσειράς προγραμματιστικά, να ενεργοποιήσετε + την εξομάλυνση και να παράγετε PDF υψηλής ποιότητας. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Μετατροπή HTML σε PDF σε C# – πλήρης έλεγχος απόδοσης +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Μετατροπή HTML σε PDF σε C# – ορισμός στυλ γραμματοσειράς προγραμματιστικά +url: /el/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μετατροπή HTML σε PDF σε C# – ορισμός στυλ γραμματοσειράς προγραμματιστικά + +Αν χρειάζεστε **μετατροπή HTML σε PDF** σε μια εφαρμογή .NET, αυτό το tutorial σας οδηγεί βήμα‑βήμα σε μια πλήρη, έτοιμη για παραγωγή λύση. Θα δείτε πώς να **ορίσετε το στυλ γραμματοσειράς προγραμματιστικά**, να βελτιώσετε την απόδοση των εικόνων και να ενεργοποιήσετε το hinting κειμένου—όλα χωρίς να αφήσετε τον κώδικα C#. + +Η μετατροπή ιστοσελίδων σε PDF είναι συχνή απαίτηση για αναφορές, τιμολόγηση και αρχειοθέτηση. Αυτός ο οδηγός καλύπτει τα πάντα, από τη ρύθμιση του έργου μέχρι ένα πλήρες, εκτελέσιμο παράδειγμα. Στο τέλος του άρθρου θα μπορείτε να δημιουργείτε PDF που διατηρούν τη διάταξη, την τυπογραφία και την οπτική πιστότητα. + +## Τι θα μάθετε + +* Πώς να προσθέσετε το απαιτούμενο πακέτο NuGet και να εισάγετε namespaces. +* Πώς να διαμορφώσετε το `HtmlConversionOptions` για έλεγχο της απόδοσης. +* Πώς να **ορίσετε το στυλ γραμματοσειράς προγραμματιστικά** χρησιμοποιώντας τις σημαίες `WebFontStyle`. +* Πώς να ενεργοποιήσετε το antialiasing για εικόνες και το hinting για κείμενο. +* Πώς να καλέσετε την κλάση `Converter` για να παραγάγετε το τελικό αρχείο PDF. + +Το tutorial υποθέτει ότι έχετε εγκατεστημένο το Visual Studio 2022 (ή νεότερο) και το .NET 6 ή νεότερο. Δεν απαιτείται πρόσθετο εργαλείο. + +## Προαπαιτούμενα + +| Απαίτηση | Λόγος | +|---|---| +| .NET 6 SDK ή νεότερο | Παρέχει το runtime για το έργο C#. | +| Visual Studio 2022 (ή οποιοδήποτε IDE) | Διευκολύνει τη δημιουργία και την αποσφαλμάτωση του έργου. | +| Πρόσβαση στο Internet για αποκατάσταση πακέτων NuGet | Απαιτείται για λήψη της βιβλιοθήκης μετατροπής. | +| Ένα απλό αρχείο HTML (`input.html`) | Λειτουργεί ως το πηγαίο έγγραφο για τη μετατροπή. | + +> **Pro tip:** Κρατήστε το αρχείο HTML στον ίδιο φάκελο με το έργο για να αποφύγετε προβλήματα σχετιζόμενα με διαδρομές. + +## Βήμα 1: Εγκατάσταση της βιβλιοθήκης μετατροπής + +Το δείγμα κώδικα χρησιμοποιεί τη βιβλιοθήκη **GroupDocs.Conversion for .NET**, η οποία προσφέρει `HtmlConversionOptions` και μια κλάση `Converter`. Εγκαταστήστε την μέσω του NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Το πακέτο προσθέτει τους απαραίτητους τύπους στο έργο σας και φέρνει όλες τις εξαρτήσεις. + +## Βήμα 2: Δημιουργία έργου κονσόλας C# + +Ανοίξτε μια γραμμή εντολών και εκτελέστε: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Αυτό δημιουργεί μια ελάχιστη εφαρμογή κονσόλας με όνομα `HtmlToPdfDemo`. Ανοίξτε το παραγόμενο αρχείο `Program.cs`; θα αντικαταστήσετε το περιεχόμενό του με το πλήρες παράδειγμα αργότερα. + +## Βήμα 3: Διαμόρφωση επιλογών μετατροπής – ορισμός στυλ γραμματοσειράς προγραμματιστικά + +Η κλάση `HtmlConversionOptions` σας επιτρέπει να ρυθμίσετε λεπτομερώς πώς η μηχανή HTML αποδίδει τη σελίδα. Για **ορισμό στυλ γραμματοσειράς προγραμματιστικά**, συνδυάστε τις τιμές της απαρίθμησης `WebFontStyle` χρησιμοποιώντας bitwise OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Γιατί είναι σημαντικό:** +* `WebFontStyle.Bold | WebFontStyle.Italic` λέει στον renderer να εφαρμόσει και τα δύο στυλ σε οποιοδήποτε κείμενο χρησιμοποιεί την προεπιλεγμένη γραμματοσειρά. +* Το antialiasing μειώνει τις γωνιές σκαλισμού σε raster εικόνες, ειδικά κατά την κλιμάκωση. +* Το hinting ευθυγραμμίζει τα περιγράμματα των glyphs σε πλέγματα pixel, βελτιώνοντας την αναγνωσιμότητα σε οθόνες χαμηλής ανάλυσης και στο παραγόμενο PDF. + +## Βήμα 4: Εκτέλεση της μετατροπής + +Με τις επιλογές έτοιμες, καλέστε την κλάση `Converter`. Η μέθοδος `Convert` δέχεται τρία ορίσματα: τη διαδρομή του πηγαίου αρχείου HTML, τη διαδρομή του προορισμού PDF και το αντικείμενο επιλογών. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Η μέθοδος εκτελείται συγχρονισμένα και ρίχνει εξαίρεση εάν το πηγαίο αρχείο δεν μπορεί να διαβαστεί ή η διαδρομή εξόδου είναι άκυρη. Τυλίξτε την κλήση σε block try‑catch για κώδικα παραγωγής. + +## Βήμα 5: Επαλήθευση του αποτελέσματος + +Αφού ολοκληρωθεί το πρόγραμμα, ανοίξτε το `output.pdf` με οποιονδήποτε προβολέα PDF. Θα πρέπει να δείτε: + +* Κείμενο αποδοθέν σε **bold and italic** (ακόμη και αν το αρχικό HTML δεν καθόριζε αυτά τα στυλ). +* Οι εικόνες να εμφανίζονται πιο ομαλές χάρη στο antialiasing. +* Η καθαρότητα του κειμένου να έχει βελτιωθεί με το hinting, ειδικά για μικρά μεγέθη γραμματοσειράς. + +Εάν το PDF δεν αντανακλά τα αναμενόμενα στυλ, ελέγξτε ξανά ότι το αρχείο HTML αναφέρει μια web‑safe γραμματοσειρά ή περιλαμβάνει έναν κανόνα `@font-face` που μπορεί να φορτώσει ο μετατροπέας. + +## Πλήρες, εκτελέσιμο παράδειγμα + +Παρακάτω υπάρχει ένα αυτόνομο πρόγραμμα που ενσωματώνει όλα τα προηγούμενα βήματα. Αντιγράψτε τον κώδικα στο `Program.cs`, τοποθετήστε ένα αρχείο `input.html` δίπλα του και τρέξτε `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Αναμενόμενη έξοδος κονσόλας** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Ανοίξτε το παραγόμενο PDF για να επιβεβαιώσετε τα εφαρμοσμένα στυλ. + +## Διαχείριση κοινών περιπτώσεων άκρων + +| Κατάσταση | Προτεινόμενη προσέγγιση | +|---|---| +| **External CSS or fonts** | Τοποθετήστε τα αρχεία CSS και τους πόρους γραμματοσειρών στον ίδιο φάκελο με το `input.html` ή αναφερθείτε σε απόλυτες URL που είναι προσβάσιμες από το μηχάνημα που εκτελεί τη μετατροπή. | +| **Large HTML documents** | Αυξήστε το προεπιλεγμένο όριο μνήμης προσαρμόζοντας το `ConversionConfig` εάν αντιμετωπίσετε `OutOfMemoryException`. | +| **Dynamic content (JavaScript)** | Η βιβλιοθήκη δεν εκτελεί JavaScript. Προ‑αποδώστε τα δυναμικά τμήματα στο server‑side ή χρησιμοποιήστε έναν headless browser για να δημιουργήσετε ένα στατικό στιγμιότυπο HTML πριν τη μετατροπή. | +| **Unicode characters not displaying** | Βεβαιωθείτε ότι το HTML δηλώνει `` και ότι οι πηγαίες γραμματοσειρές περιέχουν τα απαιτούμενα glyphs. | +| **Incorrect page size** | Ορίστε `conversionOptions.PageSize = PageSize.A4` (ή άλλη τιμή enum) για να εξασφαλίσετε συνεπείς διαστάσεις. | + +## Συμβουλές απόδοσης + +* Επαναχρησιμοποιήστε ένα μόνο αντικείμενο `Converter` όταν μετατρέπετε πολλά αρχεία· μειώνει το κόστος εκκίνησης. +* Απενεργοποιήστε περιττές λειτουργίες απόδοσης (π.χ., `EnableHyperlinks`) εάν δεν τις χρειάζεστε, κάτι που επιταχύνει την επεξεργασία. +* Γράψτε το PDF σε ροή μνήμης (memory stream) όταν χρειάζεται να το στείλετε απευθείας μέσω HTTP αντί να το αποθηκεύσετε σε δίσκο. + +## Επόμενα βήματα + +Τώρα που μπορείτε να **μετατρέψετε HTML σε PDF** με προσαρμοσμένες ρυθμίσεις γραμματοσειράς, εξερευνήστε τα παρακάτω σχετικά θέματα: + +* **Set page margins programmatically** – προσαρμόστε το `conversionOptions.Margin` για έλεγχο του λευκού χώρου. +* **Add watermarks** – χρησιμοποιήστε το `PdfConversionOptions` για επικάλυψη κειμένου ή εικόνων. +* **Batch conversion** – επαναλάβετε τη διαδικασία για μια συλλογή αρχείων HTML και επαναχρησιμοποιήστε το ίδιο αντικείμενο επιλογών. + +## Τι Θα Μάθετε Στη Σύντομη Μελλοντική + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Convert HTML to PDF in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convert SVG to PDF in .NET with Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/greek/net/working-with-html-documents/_index.md b/html/greek/net/working-with-html-documents/_index.md index 1990362d06..be744936a5 100644 --- a/html/greek/net/working-with-html-documents/_index.md +++ b/html/greek/net/working-with-html-documents/_index.md @@ -41,6 +41,8 @@ url: /el/net/working-with-html-documents/ Μάθετε πώς να αποθηκεύετε HTML σε C# χρησιμοποιώντας έναν προσαρμοσμένο διαχειριστή πόρων, βήμα-βήμα οδηγός. ### [Πώς να κάνετε έντονο τίτλο με CSS & C# – Πλήρης οδηγός βήμα‑βήμα](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Φόρτωση συμβολοσειράς HTML σε C# – πλήρης οδηγός με προσαρμοσμένο διαχειριστή](./load-html-string-in-c-complete-guide-with-custom-handler/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/greek/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/greek/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..21864fc54e --- /dev/null +++ b/html/greek/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-08-03 +description: Φορτώστε συμβολοσειρά HTML σε C# και δημιουργήστε προσαρμοσμένο χειριστή + για αποθήκευση του HTMLDocument. Μάθετε πώς να αποθηκεύετε το HTMLDocument με προσαρμοσμένη + διαχείριση πόρων. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: el +lastmod: 2026-08-03 +og_description: Φορτώστε μια συμβολοσειρά HTML σε C# και χρησιμοποιήστε έναν προσαρμοσμένο + χειριστή για να αποθηκεύσετε το HTMLDocument. Αυτό το σεμινάριο δείχνει την πλήρη + υλοποίηση και τις βέλτιστες πρακτικές. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Φόρτωση συμβολοσειράς HTML σε C# – οδηγός προσαρμοσμένου χειριστή βήμα‑βήμα +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Φόρτωση συμβολοσειράς HTML σε C# – πλήρης οδηγός με προσαρμοσμένο χειριστή +url: /el/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Φόρτωση συμβολοσειράς HTML σε C# – πλήρης οδηγός με προσαρμοσμένο χειριστή + +Αν χρειάζεστε **φόρτωση συμβολοσειράς HTML** σε μια εφαρμογή C#, αυτό το tutorial σας δείχνει ακριβώς πώς να το κάνετε και πώς να **δημιουργήσετε προσαρμοσμένο χειριστή** για τη διαχείριση πόρων. Θα μάθετε επίσης **πώς να αποθηκεύσετε το htmldocument** χρησιμοποιώντας **προσαρμοσμένη διαχείριση πόρων**, ώστε κάθε εικόνα, αρχείο CSS ή script να γράφεται ακριβώς όπου θέλετε. + +Θα περάσουμε από όλη τη διαδικασία — από τη μετατροπή μιας ακατέργαστης συμβολοσειράς HTML σε αντικείμενο `HTMLDocument`, μέχρι την υλοποίηση μιας υποκλάσης `ResourceHandler` που ελέγχει πού αποθηκεύεται κάθε πόρος. Στο τέλος θα έχετε ένα αυτόνομο, έτοιμο για παραγωγή παράδειγμα που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο .NET. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7+) +- Αναφορά στη βιβλιοθήκη που παρέχει `HTMLDocument`, `ResourceHandler` και `ResourceInfo` (π.χ., *HtmlRenderer* ή παρόμοια βιβλιοθήκη HTML‑to‑PDF/DOM) +- Βασικές γνώσεις σύνταξης C# και ροών (streams) + +> **Pro tip:** Αν χρησιμοποιείτε Visual Studio, ενεργοποιήστε τους *nullable reference types* (`enable`) για να εντοπίζετε σφάλματα σχετιζόμενα με null νωρίς. + +## Πώς να φορτώσετε συμβολοσειρά HTML σε HTMLDocument + +Το πρώτο βήμα είναι η μετατροπή μιας απλής συμβολοσειράς HTML σε αντικείμενο `HTMLDocument` που η βιβλιοθήκη μπορεί να επεξεργαστεί. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Γιατί είναι σημαντικό:** +`HTMLDocument` αναλύει το markup, δημιουργεί ένα δέντρο DOM και προετοιμάζει τους πόρους (εικόνες, φύλλα στυλ κ.λπ.) για μεταγενέστερη αποθήκευση. Η άμεση μεταβίβαση μιας συμβολοσειράς αποφεύγει την ανάγκη για προσωρινά αρχεία και διατηρεί τη ροή εργασίας στη μνήμη. + +### Συνηθισμένες παγίδες + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| `htmlContent` είναι `null` | Η μεταβλητή συμβολοσειράς δεν είχε ποτέ τιμή. | Επαληθεύστε πριν δημιουργήσετε το έγγραφο: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Προβλήματα κωδικοποίησης | Η βιβλιοθήκη υποθέτει UTF‑8 αλλά η πηγή χρησιμοποιεί άλλη κωδικοποίηση. | Παρέχετε υπερφόρτωση `Encoding` αν είναι διαθέσιμη, ή βεβαιωθείτε ότι η συμβολοσειρά έχει αποκωδικοποιηθεί σωστά. | + +## Δημιουργία προσαρμοσμένου χειριστή για διαχείριση πόρων + +Ένας **προσαρμοσμένος χειριστής πόρων** σας δίνει πλήρη έλεγχο στο πώς η βιβλιοθήκη γράφει εξωτερικούς πόρους (εικόνες, CSS, γραμματοσειρές). Παρακάτω υπάρχει μια ελάχιστη υλοποίηση που γράφει κάθε πόρο σε `MemoryStream`. Μπορείτε να αντικαταστήσετε το σώμα με λογική αρχείου, αποθήκευσης στο cloud ή οποιονδήποτε άλλο προορισμό. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Γιατί χρειάζεστε προσαρμοσμένο χειριστή:** +Ο προεπιλεγμένος χειριστής συχνά γράφει τους πόρους σε προσωρινό φάκελο, κάτι που μπορεί να είναι ανεπιθύμητο για λόγους ασφαλείας ή απόδοσης. Με την υπερισχύ του `HandleResource`, αποφασίζετε ακριβώς πού και πώς αποθηκεύεται κάθε byte. + +### Επέκταση του χειριστή για έξοδο σε αρχείο + +Αν προτιμάτε να γράφετε κάθε πόρο σε συγκεκριμένο φάκελο, τροποποιήστε τη μέθοδο ως εξής: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Πώς να αποθηκεύσετε το htmldocument χρησιμοποιώντας τον προσαρμοσμένο χειριστή + +Τώρα που έχουμε τόσο το αντικείμενο `HTMLDocument` όσο και την υλοποίηση `MyHandler`, μπορούμε να αποθηκεύσουμε το έγγραφο. Η μέθοδος `Save` δέχεται οποιαδήποτε υποκλάση `ResourceHandler`, επιτρέποντάς σας να ενσωματώσετε τη δική σας λογική. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Κατά την εκτέλεση του `Save`, η βιβλιοθήκη θα: + +1. Διασχίσει το δέντρο DOM. +2. Εντοπίσει εξωτερικούς πόρους (π.χ., ``). +3. Καλέσει `handler.HandleResource` για κάθε πόρο. +4. Γράψει τα δεδομένα του πόρου στο επιστρεφόμενο stream. +5. Ολοκληρώσει την κύρια έξοδο HTML (συχνά ως ξεχωριστό αρχείο ή stream). + +### Επαλήθευση του αποτελέσματος + +Αν χρησιμοποιήσατε την έκδοση αρχείου του `MyHandler`, θα πρέπει να δείτε έναν φάκελο `output` με το αρχικό αρχείο HTML και όλα τα αναφερόμενα assets. Για την έκδοση `MemoryStream`, μπορείτε να ελέγξετε το μήκος του stream για να επιβεβαιώσετε ότι τα δεδομένα γράφτηκαν: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Πλήρες, εκτελέσιμο παράδειγμα + +Παρακάτω υπάρχει ένα πρόγραμμα έτοιμο για αντιγραφή‑επικόλληση που δείχνει ολόκληρη τη ροή. Περιλαμβάνει διαχείριση σφαλμάτων, διακοπή ροών και σχόλια που εξηγούν κάθε βήμα. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Αναμενόμενη έξοδος** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Μετά την εκτέλεση του προγράμματος, ο φάκελος `output` περιέχει: + +- `index.html` (το κύριο έγγραφο) +- Οποιαδήποτε επιπλέον αρχεία δημιούργησε η βιβλιοθήκη (π.χ., εικόνες, CSS) + +## Προχωρημένες παραλλαγές και ειδικές περιπτώσεις + +### Αποθήκευση σε `MemoryStream` για επεξεργασία εντός μνήμης + +Αν χρειάζεστε το τελικό HTML ως συμβολοσειρά ή θέλετε να το στείλετε μέσω HTTP χωρίς να αγγίξετε το δίσκο, αντικαταστήστε το `MyHandler` με μια έκδοση που επιστρέφει ένα κοινό `MemoryStream`: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Μετά το `htmlDoc.Save(handler)`, μπορείτε να διαβάσετε το HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Ασφαλής διαχείριση μεγάλων πόρων + +Όταν εργάζεστε με μεγάλες εικόνες ή PDF, αποφύγετε τη φόρτωση ολόκληρου του αρχείου στη μνήμη. Αντ' αυτού, επιστρέψτε ένα `FileStream` που γράφει απευθείας στο δίσκο, όπως φαίνεται παραπάνω. Αυτό αποτρέπει `OutOfMemoryException` σε σενάρια υψηλής διακίνησης. + +### Σκέψεις για thread‑safety + +Οι αντικείμενα `HTMLDocument` **δεν** είναι ασφαλή για χρήση από πολλαπλά νήματα. Αν χρειάζεται να επεξεργαστείτε πολλές συμβολοσειρές HTML ταυτόχρονα, δημιουργήστε ξεχωριστό `HTMLDocument` και `MyHandler` ανά νήμα ή συγχρονίστε την πρόσβαση με `lock`. + +### Διακοπή ροών + +Τanto `HTMLDocument.Save` όσο και `ResourceHandler.HandleResource` μπορεί να επιστρέψουν ροές που χρειάζονται διακοπή. Στα παραδείγματα παραπάνω, η βιβλιοθήκη διακόπτει αυτόματα τις ροές μετά το γράψιμο. Αν διαχειρίζεστε τις ροές εσείς (π.χ., ανοίγοντας `FileStream` πριν καλέσετε `Save`), τυλίξτε τις σε δηλώσεις `using`. + +## Συνοπτικό + +Αυτός ο οδηγός σας έδειξε πώς να **φορτώσετε συμβολοσειρά HTML** σε ένα `HTMLDocument`, **να δημιουργήσετε προσαρμοσμένο χειριστή** για τον καθορισμό αποθήκευσης πόρων, και **πώς να αποθηκεύσετε το htmldocument** με **προσαρμοσμένη διαχείριση πόρων**. Τώρα έχετε: + +1. Μια σαφή μέθοδο μετατροπής ακατέργαστου HTML σε αντικείμενο DOM. +2. Μια επαναχρησιμοποιήσιμη υποκλάση `ResourceHandler` που μπορεί να γράφει πόρους στη μνήμη, στο δίσκο ή σε αποθήκευση cloud. +3. Ένα πλήρες, εκτελέσιμο πρόγραμμα που επιδεικνύει όλη τη ροή εργασίας. + +## Επόμενα βήματα + +- Εξερευνήστε άλλες υπερφορτώσεις του `ResourceHandler` όπως `HandleCss` ή `HandleFont` αν η βιβλιοθήκη σας τις παρέχει. +- Συνδυάστε αυτήν την προσέγγιση με βήμα μετατροπής σε PDF για να δημιουργήσετε PDF από HTML διατηρώντας πλήρη έλεγχο των ενσωματωμένων πόρων. +- Ανασκοπήστε την τεκμηρίωση της βιβλιοθήκης για πρόσθετες επιλογές όπως *συμπίεση*, *caching* ή *ασύγχρονη* αποθήκευση. + +Πειραματιστείτε με διαφορετικές στρατηγικές αποθήκευσης και μοιραστείτε τα ευρήματά σας στα σχόλια ή στην αγαπημένη σας κοινότητα προγραμματιστών. Καλό κώδικα! + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κυριαρχήσετε σε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας έργα. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 45408d5a1f..f5beb1f4ef 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 क्यों? @@ -43,6 +43,9 @@ Aspose.HTML for .NET सिर्फ़ एक लाइब्रेरी न ### [HTML से PDF बनाएं – C# चरण‑दर‑चरण गाइड](./create-pdf-from-html-c-step-by-step-guide/) C# में Aspose.HTML का उपयोग करके HTML को PDF में बदलने का चरण‑दर‑चरण मार्गदर्शन। +### [C# में HTML को PDF में बदलें – प्रोग्रामेटिक रूप से फ़ॉन्ट शैली सेट करें](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +.NET के लिए Aspose.HTML का उपयोग करके C# में HTML को PDF में बदलते समय फ़ॉन्ट शैली को प्रोग्रामेटिकली सेट करने का तरीका सीखें। + ### [Aspose.HTML के साथ .NET में EPUB को छवि में बदलें](./convert-epub-to-image/) .NET के लिए Aspose.HTML का उपयोग करके EPUB को छवियों में परिवर्तित करना सीखें। कोड उदाहरणों और अनुकूलन योग्य विकल्पों के साथ चरण-दर-चरण ट्यूटोरियल। diff --git a/html/hindi/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/hindi/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..4d10ead08d --- /dev/null +++ b/html/hindi/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: C# में HTML को PDF में बदलें, पूर्ण रेंडरिंग नियंत्रण के साथ। जानें कि + प्रोग्रामेटिक रूप से फ़ॉन्ट शैली कैसे सेट करें, एंटी‑एलियासिंग सक्षम करें, और टेक्स्ट + की स्पष्टता में सुधार करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: hi +lastmod: 2026-08-03 +og_description: C# में विस्तृत विकल्पों के साथ HTML को PDF में बदलें। यह गाइड दिखाता + है कि प्रोग्रामेटिक रूप से फ़ॉन्ट शैली कैसे सेट करें, एंटी‑एलियासिंग सक्षम करें, + और उच्च‑गुणवत्ता वाले PDF बनाएं। +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: C# में HTML को PDF में बदलें – पूर्ण रेंडरिंग नियंत्रण +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: C# में HTML को PDF में बदलें – प्रोग्रामेटिकली फ़ॉन्ट शैली सेट करें +url: /hi/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में HTML को PDF में बदलें – फ़ॉन्ट शैली को प्रोग्रामेटिकली सेट करें + +यदि आपको .NET एप्लिकेशन में **HTML को PDF में बदलने** की आवश्यकता है, तो यह ट्यूटोरियल आपको एक पूर्ण, प्रोडक्शन‑रेडी समाधान के माध्यम से ले जाता है। आप देखेंगे कि **फ़ॉन्ट शैली को प्रोग्रामेटिकली कैसे सेट करें**, इमेज रेंडरिंग को कैसे सुधारें, और टेक्स्ट हिन्टिंग को कैसे सक्षम करें—बिना अपने C# कोड से बाहर निकले। + +वेब पेजों को PDF में बदलना रिपोर्टिंग, इनवॉइसिंग और अभिलेखीय कार्यों के लिए एक सामान्य आवश्यकता है। यह गाइड प्रोजेक्ट सेटअप से लेकर एक पूर्ण, चलाने योग्य उदाहरण तक सब कुछ कवर करता है। लेख के अंत तक आप ऐसे PDF बना सकते हैं जो लेआउट, टाइपोग्राफी और विज़ुअल फ़िडेलिटी को संरक्षित रखते हैं। + +## आप क्या सीखेंगे + +* आवश्यक NuGet पैकेज को जोड़ने और नेमस्पेस इम्पोर्ट करने का तरीका। +* `HtmlConversionOptions` को कॉन्फ़िगर करके रेंडरिंग को नियंत्रित करने का तरीका। +* `WebFontStyle` फ्लैग्स का उपयोग करके **फ़ॉन्ट शैली को प्रोग्रामेटिकली सेट करने** का तरीका। +* इमेज के लिए एंटीएलियासिंग और टेक्स्ट के लिए हिन्टिंग को सक्षम करने का तरीका। +* अंतिम PDF फ़ाइल बनाने के लिए `Converter` क्लास को कॉल करने का तरीका। + +ट्यूटोरियल मानता है कि आपके पास Visual Studio 2022 (या बाद का) और .NET 6 या उससे नया स्थापित है। कोई अतिरिक्त टूलिंग आवश्यक नहीं है। + +## आवश्यकताएँ + +| आवश्यकता | कारण | +|---|---| +| .NET 6 SDK or later | C# प्रोजेक्ट के लिए रनटाइम प्रदान करता है। | +| Visual Studio 2022 (or any IDE) | आसान प्रोजेक्ट निर्माण और डिबगिंग को सक्षम करता है। | +| Internet access to restore NuGet packages | कन्वर्ज़न लाइब्रेरी डाउनलोड करने के लिए आवश्यक है। | +| A simple HTML file (`input.html`) | कन्वर्ज़न के लिए स्रोत दस्तावेज़ के रूप में कार्य करता है। | + +> **Pro tip:** HTML फ़ाइल को प्रोजेक्ट के समान फ़ोल्डर में रखें ताकि पाथ‑संबंधी समस्याओं से बचा जा सके। + +## चरण 1: कन्वर्ज़न लाइब्रेरी स्थापित करें + +कोड सैंपल **GroupDocs.Conversion for .NET** लाइब्रेरी का उपयोग करता है, जो `HtmlConversionOptions` और `Converter` क्लास प्रदान करती है। इसे NuGet पैकेज मैनेजर के माध्यम से स्थापित करें: + +```bash +dotnet add package GroupDocs.Conversion +``` + +यह पैकेज आपके प्रोजेक्ट में आवश्यक टाइप्स जोड़ता है और सभी डिपेंडेंसीज़ को शामिल करता है। + +## चरण 2: C# कंसोल प्रोजेक्ट बनाएं + +कमांड प्रॉम्प्ट खोलें और चलाएँ: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +यह `HtmlToPdfDemo` नामक एक न्यूनतम कंसोल एप्लिकेशन बनाता है। उत्पन्न `Program.cs` फ़ाइल खोलें; आप बाद में उसकी सामग्री को पूर्ण उदाहरण से बदलेंगे। + +## चरण 3: कन्वर्ज़न विकल्प कॉन्फ़िगर करें – फ़ॉन्ट शैली को प्रोग्रामेटिकली सेट करें + +`HtmlConversionOptions` क्लास आपको HTML इंजन के पेज रेंडरिंग को फाइन‑ट्यून करने देता है। **फ़ॉन्ट शैली को प्रोग्रामेटिकली सेट करने** के लिए, `WebFontStyle` एनेमरेशन वैल्यूज़ को बिटवाइज़ OR के साथ संयोजित करें: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**यह क्यों महत्वपूर्ण है:** +* `WebFontStyle.Bold | WebFontStyle.Italic` रेंडरर को बताता है कि डिफ़ॉल्ट फ़ॉन्ट उपयोग करने वाले किसी भी टेक्स्ट पर दोनों शैलियों को लागू किया जाए। +* एंटीएलियासिंग रास्टर इमेजेज़ पर जैग्ड एजेज़ को कम करता है, विशेष रूप से स्केलिंग के समय। +* हिन्टिंग ग्लिफ़ आउटलाइन को पिक्सेल ग्रिड्स के साथ संरेखित करता है, जिससे लो‑रेज़ोल्यूशन स्क्रीन और उत्पन्न PDF में पठनीयता बेहतर होती है। + +## चरण 4: कन्वर्ज़न करें + +विकल्प तैयार होने के बाद, `Converter` क्लास को कॉल करें। `Convert` मेथड तीन आर्ग्यूमेंट लेता है: स्रोत HTML फ़ाइल पाथ, गंतव्य PDF फ़ाइल पाथ, और विकल्प ऑब्जेक्ट। + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +यह मेथड सिंक्रोनस रूप से चलता है और यदि स्रोत फ़ाइल पढ़ी नहीं जा सकती या आउटपुट पाथ अमान्य है तो एक्सेप्शन थ्रो करता है। प्रोडक्शन कोड के लिए कॉल को try‑catch ब्लॉक में रैप करें। + +## चरण 5: परिणाम सत्यापित करें + +प्रोग्राम समाप्त होने के बाद, किसी भी PDF व्यूअर से `output.pdf` खोलें। आपको यह दिखना चाहिए: + +* टेक्स्ट **बोल्ड और इटैलिक** में रेंडर हुआ (भले ही मूल HTML ने इन शैलियों को निर्दिष्ट न किया हो)। +* एंटीएलियासिंग के कारण इमेजेज़ अधिक स्मूद दिखती हैं। +* हिन्टिंग से टेक्स्ट की स्पष्टता बेहतर हुई, विशेष रूप से छोटे फ़ॉन्ट साइज के लिए। + +यदि PDF अपेक्षित शैलियों को नहीं दर्शाता है, तो दोबारा जांचें कि HTML फ़ाइल वेब‑सेफ़ फ़ॉन्ट को रेफ़रेंस करती है या उसमें `@font-face` नियम शामिल है जिसे कन्वर्टर लोड कर सके। + +## पूर्ण, चलाने योग्य उदाहरण + +नीचे एक स्व-निहित प्रोग्राम है जो सभी पिछले चरणों को सम्मिलित करता है। कोड को `Program.cs` में कॉपी करें, उसके बगल में `input.html` फ़ाइल रखें, और `dotnet run` चलाएँ। + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**अपेक्षित कंसोल आउटपुट** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +उत्पन्न PDF खोलें ताकि लागू शैलियों की पुष्टि हो सके। + +## सामान्य किनारे मामलों को संभालना + +| स्थिति | सिफारिश किया गया तरीका | +|---|---| +| **External CSS or fonts** | CSS फ़ाइलें और फ़ॉन्ट रिसोर्सेज़ को `input.html` के समान फ़ोल्डर में रखें या उन्हें ऐसे एब्सोल्यूट URLs से रेफ़रेंस करें जो कन्वर्ज़न चलाने वाली मशीन से पहुँच योग्य हों। | +| **Large HTML documents** | यदि आप `OutOfMemoryException` का सामना करते हैं तो `ConversionConfig` को समायोजित करके डिफ़ॉल्ट मेमोरी लिमिट बढ़ाएँ। | +| **Dynamic content (JavaScript)** | लाइब्रेरी JavaScript को निष्पादित नहीं करती। डायनामिक भागों को सर्वर‑साइड पहले रेंडर करें या कन्वर्ज़न से पहले एक स्थैतिक HTML स्नैपशॉट बनाने के लिए हेडलेस ब्राउज़र का उपयोग करें। | +| **Unicode characters not displaying** | सुनिश्चित करें कि HTML में `` घोषित है और स्रोत फ़ॉन्ट्स में आवश्यक ग्लिफ़्स मौजूद हैं। | +| **Incorrect page size** | `conversionOptions.PageSize = PageSize.A4` (या कोई अन्य एनेम वैल्यू) सेट करके सुसंगत आयाम लागू करें। | + +## प्रदर्शन टिप्स + +* कई फ़ाइलों को कन्वर्ट करते समय एक ही `Converter` इंस्टेंस को पुनः उपयोग करें; यह स्टार्टअप ओवरहेड को कम करता है। +* यदि आपको आवश्यकता नहीं है तो अनावश्यक रेंडरिंग फीचर्स (जैसे `EnableHyperlinks`) को डिसेबल करें, जिससे प्रोसेसिंग तेज़ होती है। +* यदि आपको PDF को सीधे HTTP पर भेजना है तो डिस्क पर लिखने के बजाय मेमोरी स्ट्रीम में लिखें। + +## अगले कदम + +अब जब आप कस्टम फ़ॉन्ट सेटिंग्स के साथ **HTML को PDF में बदल** सकते हैं, तो इन संबंधित विषयों को देखें: + +* **पेज मार्जिन को प्रोग्रामेटिकली सेट करें** – व्हाइट स्पेस को नियंत्रित करने के लिए `conversionOptions.Margin` को समायोजित करें। +* **वॉटरमार्क जोड़ें** – टेक्स्ट या इमेज ओवरले करने के लिए `PdfConversionOptions` का उपयोग करें। +* **बैच कन्वर्ज़न** – HTML फ़ाइलों के संग्रह पर लूप करें और समान विकल्प ऑब्जेक्ट को पुनः उपयोग करें। + +## अगला आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन निकट-संबंधित विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण-दर-चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोच को एक्सप्लोर करने में मदद करती हैं। + +- [.NET में Aspose.HTML के साथ HTML को PDF में बदलें](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [स्टाइल्ड टेक्स्ट के साथ HTML दस्तावेज़ बनाएं और PDF में एक्सपोर्ट करें – पूर्ण गाइड](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [.NET में Aspose.HTML के साथ SVG को PDF में बदलें](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/hindi/net/working-with-html-documents/_index.md index 4c5be51ef6..1d00220eb6 100644 --- a/html/hindi/net/working-with-html-documents/_index.md +++ b/html/hindi/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ HTML दस्तावेज़ वेब की रीढ़ हैं, और अब, आइए अपने कौशल को अगले स्तर पर ले जाएं। HTML दस्तावेज़ों को संपादित करना वेब डेवलपर्स के लिए एक सामान्य कार्य है, और Aspose.HTML इस प्रक्रिया को काफी सरल बनाता है। इस अनुभाग में, हम दस्तावेज़ निर्माण, हेरफेर और स्टाइलिंग को कवर करेंगे। आप जानेंगे कि अपनी वेब सामग्री की उपस्थिति और कार्यक्षमता को कैसे बढ़ाया जाए, जिससे यह आकर्षक और उपयोगकर्ता के अनुकूल बन सके। ### [C# में HTML को सहेजना – कस्टम रिसोर्स हैंडलर का उपयोग करके पूर्ण गाइड](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [C# में HTML स्ट्रिंग लोड करना – कस्टम हैंडलर के साथ पूर्ण गाइड](./load-html-string-in-c-complete-guide-with-custom-handler/) + ### [CSS और C# के साथ हेडिंग को बोल्ड कैसे बनाएं – पूर्ण चरण-दर-चरण गाइड](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/hindi/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/hindi/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..88121c9e75 --- /dev/null +++ b/html/hindi/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-08-03 +description: C# में HTML स्ट्रिंग लोड करें और HTMLDocument को सहेजने के लिए कस्टम + हैंडलर बनाएं। कस्टम रिसोर्स हैंडलिंग के साथ HTMLDocument को कैसे सहेजें, सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: hi +lastmod: 2026-08-03 +og_description: C# में HTML स्ट्रिंग लोड करें और एक कस्टम हैंडलर का उपयोग करके HTMLDocument + को सहेजें। यह ट्यूटोरियल पूर्ण कार्यान्वयन और सर्वोत्तम प्रथाओं को दिखाता है। +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: C# में HTML स्ट्रिंग लोड करें – चरण‑दर‑चरण कस्टम हैंडलर गाइड +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: C# में HTML स्ट्रिंग लोड करें – कस्टम हैंडलर के साथ पूर्ण गाइड +url: /hi/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में HTML स्ट्रिंग लोड करें – कस्टम हैंडलर के साथ पूर्ण गाइड + +यदि आपको C# एप्लिकेशन में **HTML स्ट्रिंग लोड** करनी है, तो यह ट्यूटोरियल आपको ठीक-ठीक दिखाता है कि इसे कैसे करें और संसाधन प्रबंधन के लिए **कस्टम हैंडलर बनाएं** कैसे है। आप यह भी सीखेंगे कि **HTMLDocument को कैसे सहेजें** **कस्टम रिसोर्स हैंडलिंग** का उपयोग करके ताकि हर इमेज, CSS फ़ाइल, या स्क्रिप्ट ठीक उसी जगह लिखी जाए जहाँ आप चाहते हैं। + +हम पूरी प्रक्रिया के माध्यम से चलेंगे—एक कच्ची HTML स्ट्रिंग को `HTMLDocument` ऑब्जेक्ट में बदलने से लेकर `ResourceHandler` सबक्लास को लागू करने तक जो तय करता है कि प्रत्येक रिसोर्स कहाँ संग्रहीत किया जाए। अंत तक आपके पास एक स्व‑निहित, प्रोडक्शन‑रेडी उदाहरण होगा जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। + +## पूर्वापेक्षाएँ + +- .NET 6.0 या बाद का (कोड .NET Framework 4.7+ पर भी काम करता है) +- `HTMLDocument`, `ResourceHandler`, और `ResourceInfo` प्रदान करने वाली लाइब्रेरी का रेफ़रेंस (जैसे, *HtmlRenderer* या समान HTML‑to‑PDF/DOM लाइब्रेरी) +- C# सिंटैक्स और स्ट्रीम्स का बेसिक ज्ञान + +> **Pro tip:** यदि आप Visual Studio का उपयोग करते हैं, तो *nullable reference types* (`enable`) को सक्षम करें ताकि null‑संबंधी बग्स को जल्दी पकड़ा जा सके। + +## HTML स्ट्रिंग को HTMLDocument में लोड करने का तरीका + +पहला कदम एक साधारण HTML स्ट्रिंग को `HTMLDocument` ऑब्जेक्ट में बदलना है, जिसपर लाइब्रेरी काम कर सके। + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**यह क्यों महत्वपूर्ण है:** + +`HTMLDocument` मार्कअप को पार्स करता है, DOM ट्री बनाता है, और बाद में सहेजने के लिए रिसोर्सेज (इमेज, स्टाइलशीट आदि) तैयार करता है। स्ट्रिंग को सीधे पास करने से अस्थायी फ़ाइलों की आवश्यकता नहीं रहती और वर्कफ़्लो मेमोरी में रहता है। + +### सामान्य जाल + +| समस्या | क्यों होता है | समाधान | +|-------|----------------|-----| +| `htmlContent` is `null` | स्ट्रिंग वेरिएबल को कभी असाइन नहीं किया गया था। | डॉक्यूमेंट बनाने से पहले वैलिडेट करें: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | लाइब्रेरी मानती है कि UTF‑8 है लेकिन स्रोत किसी अन्य एन्कोडिंग का उपयोग करता है। | यदि उपलब्ध हो तो स्पष्ट `Encoding` ओवरलोड प्रदान करें, या सुनिश्चित करें कि स्ट्रिंग सही ढंग से डिकोड की गई है। | + +## रिसोर्स हैंडलिंग के लिए कस्टम हैंडलर बनाएं + +एक **कस्टम रिसोर्स हैंडलर** आपको पूरी नियंत्रण देता है कि लाइब्रेरी बाहरी रिसोर्सेज (इमेज, CSS, फ़ॉन्ट) को कैसे लिखे। नीचे एक न्यूनतम इम्प्लीमेंटेशन है जो प्रत्येक रिसोर्स को `MemoryStream` में लिखता है। आप बॉडी को फ़ाइल‑सिस्टम लॉजिक, क्लाउड स्टोरेज, या किसी अन्य गंतव्य से बदल सकते हैं। + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**आपको कस्टम हैंडलर की आवश्यकता क्यों है:** + +डिफ़ॉल्ट हैंडलर अक्सर रिसोर्सेज को एक अस्थायी फ़ोल्डर में लिखता है, जो सुरक्षा या प्रदर्शन कारणों से अनिच्छित हो सकता है। `HandleResource` को ओवरराइड करके आप तय करते हैं कि प्रत्येक बाइट ठीक कहाँ और कैसे संग्रहीत हो। + +### फ़ाइल आउटपुट के लिए हैंडलर का विस्तार + +यदि आप प्रत्येक रिसोर्स को एक विशिष्ट फ़ोल्डर में लिखना चाहते हैं, तो मेथड को इस प्रकार संशोधित करें: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## कस्टम हैंडलर का उपयोग करके HTMLDocument को कैसे सहेजें + +अब जब हमारे पास `HTMLDocument` इंस्टेंस और `MyHandler` इम्प्लीमेंटेशन दोनों हैं, हम दस्तावेज़ को सहेज सकते हैं। `Save` मेथड किसी भी `ResourceHandler` सबक्लास को स्वीकार करता है, जिससे आप अपनी कस्टम लॉजिक को प्लग इन कर सकते हैं। + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +जब `Save` चलता है, तो लाइब्रेरी करेगा: + +1. DOM ट्री को ट्रैवर्स करें। +2. बाहरी रिसोर्सेज का पता लगाएँ (जैसे, ``)। +3. प्रत्येक रिसोर्स के लिए `handler.HandleResource` को कॉल करें। +4. रिसोर्स डेटा को लौटाए गए स्ट्रीम में लिखें। +5. मुख्य HTML आउटपुट को फाइनल करें (अक्सर एक अलग फ़ाइल या स्ट्रीम के रूप में)। + +### परिणाम की पुष्टि + +यदि आपने `MyHandler` के फ़ाइल‑सिस्टम संस्करण का उपयोग किया है, तो आपको एक `output` फ़ोल्डर दिखना चाहिए जिसमें मूल HTML फ़ाइल और सभी रेफ़रेंस्ड एसेट्स हों। `MemoryStream` संस्करण के लिए, आप स्ट्रीम की लंबाई जांच सकते हैं ताकि पुष्टि हो सके कि डेटा लिखा गया है: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## पूर्ण, चलाने योग्य उदाहरण + +नीचे एक एकल, कॉपी‑पेस्ट‑तैयार प्रोग्राम है जो पूरे फ्लो को दर्शाता है। इसमें एरर हैंडलिंग, स्ट्रीम्स का डिस्पोज़ल, और प्रत्येक कदम को समझाने वाले कमेंट्स शामिल हैं। + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**अपेक्षित आउटपुट** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +प्रोग्राम चलाने के बाद, `output` डायरेक्टरी में शामिल हैं: + +- `index.html` (मुख्य दस्तावेज़) +- लाइब्रेरी द्वारा जेनरेट किए गए कोई भी अतिरिक्त फ़ाइलें (जैसे, इमेज, CSS) + +## उन्नत विविधताएँ और किनारे के मामले + +### इन‑मेमोरी प्रोसेसिंग के लिए `MemoryStream` में सहेजना + +यदि आपको अंतिम HTML स्ट्रिंग के रूप में चाहिए या डिस्क को छुए बिना HTTP पर भेजना है, तो `MyHandler` को ऐसे संस्करण से बदलें जो साझा `MemoryStream` लौटाता हो: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +`htmlDoc.Save(handler)` के बाद, आप HTML पढ़ सकते हैं: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### बड़े रिसोर्सेज को सुरक्षित रूप से हैंडल करना + +बड़ी इमेज या PDF के साथ काम करते समय, पूरी फ़ाइल को मेमोरी में लोड करने से बचें। इसके बजाय, एक `FileStream` लौटाएँ जो सीधे डिस्क पर लिखता है, जैसा कि पहले दिखाया गया था। यह हाई‑थ्रूपुट परिदृश्यों में `OutOfMemoryException` को रोकता है। + +### थ्रेड‑सेफ़्टी विचार + +`HTMLDocument` इंस्टेंस **थ्रेड‑सेफ़** नहीं हैं। यदि आपको कई HTML स्ट्रिंग्स को एक साथ प्रोसेस करना है, तो प्रत्येक थ्रेड के लिए अलग `HTMLDocument` और `MyHandler` बनाएं, या `lock` के साथ एक्सेस को सिंक्रोनाइज़ करें। + +### स्ट्रीम्स का डिस्पोज़ल + +`HTMLDocument.Save` और `ResourceHandler.HandleResource` दोनों स्ट्रीम्स लौटा सकते हैं जिन्हें डिस्पोज़ करना आवश्यक है। ऊपर के उदाहरणों में, लाइब्रेरी लिखने के बाद स्ट्रीम्स को स्वतः डिस्पोज़ कर देती है। यदि आप स्वयं स्ट्रीम्स को मैनेज करते हैं (जैसे, `Save` कॉल करने से पहले `FileStream` खोलना), तो उन्हें `using` स्टेटमेंट में रैप करें। + +## सारांश + +इस गाइड ने आपको दिखाया कि कैसे **HTML स्ट्रिंग लोड** करें `HTMLDocument` में, **कस्टम हैंडलर बनाएं** ताकि रिसोर्स स्टोरेज तय हो, और **कस्टम रिसोर्स हैंडलिंग** के साथ **HTMLDocument को सहेजें**। अब आपके पास है: + +1. कच्ची HTML को DOM ऑब्जेक्ट में बदलने का स्पष्ट तरीका। +2. एक पुन: उपयोग योग्य `ResourceHandler` सबक्लास जो रिसोर्सेज को मेमोरी, डिस्क, या क्लाउड स्टोरेज में लिख सकता है। +3. एक पूर्ण, चलाने योग्य प्रोग्राम जो पूरे वर्कफ़्लो को दर्शाता है। + +## अगले कदम + +- यदि आपकी लाइब्रेरी प्रदान करती है, तो `HandleCss` या `HandleFont` जैसे अन्य `ResourceHandler` ओवरराइड्स का अन्वेषण करें। +- इस दृष्टिकोण को PDF कन्वर्ज़न स्टेप के साथ मिलाएँ ताकि HTML से PDF जनरेट करते समय एम्बेडेड एसेट्स पर पूर्ण नियंत्रण बना रहे। +- लाइब्रेरी की डॉक्यूमेंटेशन की समीक्षा करें अतिरिक्त विकल्पों जैसे *compression*, *caching*, या *asynchronous* सेविंग के लिए। + +विभिन्न स्टोरेज रणनीतियों के साथ प्रयोग करने में संकोच न करें, और अपने निष्कर्ष कमेंट्स में या अपने पसंदीदा डेवलपर कम्युनिटी पर साझा करें। कोडिंग का आनंद लें! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑बद्ध व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोच को एक्सप्लोर करने में मदद करेंगे। + +- [C# में HTML सहेजने का तरीका – कस्टम रिसोर्स हैंडलर के साथ पूर्ण गाइड](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [C# में स्ट्रिंग से HTML बनाना – कस्टम रिसोर्स हैंडलर गाइड](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [C# में HTML को ज़िप करना – HTML को ज़िप में सहेजें](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 3d146ada27..938507624a 100644 --- a/html/hongkong/net/html-extensions-and-conversions/_index.md +++ b/html/hongkong/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 ## HTML 擴充功能與轉換教學課程 ### [使用 Aspose.HTML 將 .NET 中的 HTML 轉換為 PDF](./convert-html-to-pdf/) 使用 Aspose.HTML for .NET 輕鬆將 HTML 轉換為 PDF。遵循我們的逐步指南,釋放 HTML 到 PDF 轉換的強大功能。 +### [在 C# 中將 HTML 轉換為 PDF – 程式化設定字體樣式](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +使用 Aspose.HTML for .NET 在 C# 程式中設定字體樣式,將 HTML 轉換為 PDF。 ### [使用 C# 從 HTML 建立 PDF – 完整步驟指南](./create-pdf-from-html-c-step-by-step-guide/) 使用 Aspose.HTML for .NET,透過 C# 將 HTML 轉換為 PDF 的完整步驟說明與範例。 ### [使用 Aspose.HTML 將 EPUB 轉換為 .NET 中的映像](./convert-epub-to-image/) diff --git a/html/hongkong/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/hongkong/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..6411a793a1 --- /dev/null +++ b/html/hongkong/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-08-03 +description: 在 C# 中將 HTML 轉換為 PDF,完整掌控渲染。了解如何以程式方式設定字型樣式、啟用抗鋸齒,提升文字清晰度。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: zh-hant +lastmod: 2026-08-03 +og_description: 在 C# 中將 HTML 轉換為 PDF,提供詳細選項。本指南示範如何以程式方式設定字型樣式、啟用抗鋸齒,並產生高品質的 PDF。 +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: 在 C# 中將 HTML 轉換為 PDF – 完全渲染控制 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: 在 C# 中將 HTML 轉換為 PDF – 程式化設定字型樣式 +url: /zh-hant/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中將 HTML 轉換為 PDF – 程式化設定字型樣式 + +如果您需要在 .NET 應用程式中 **將 HTML 轉換為 PDF**,本教學將帶您完成一個完整、可投入生產環境的解決方案。您將學會如何 **程式化設定字型樣式**、改善影像渲染,並啟用文字 hinting,全部都在 C# 程式碼中完成。 + +將網頁轉成 PDF 是報表、發票與歸檔的常見需求。本指南涵蓋從專案設定到可執行範例的全部步驟。閱讀完本文後,您即可產生保留版面配置、排版與視覺忠實度的 PDF。 + +## 您將學到 + +* 如何加入必要的 NuGet 套件並匯入命名空間。 +* 如何設定 `HtmlConversionOptions` 以控制渲染行為。 +* 如何使用 `WebFontStyle` 旗標 **程式化設定字型樣式**。 +* 如何為影像啟用抗鋸齒,並為文字啟用 hinting。 +* 如何呼叫 `Converter` 類別產生最終的 PDF 檔案。 + +本教學假設您已安裝 Visual Studio 2022(或更新版本)以及 .NET 6 或更新的環境。無需額外工具。 + +## 前置條件 + +| 前置條件 | 原因 | +|---|---| +| .NET 6 SDK 或更新版本 | 為 C# 專案提供執行時環境。 | +| Visual Studio 2022(或任何 IDE) | 方便建立專案與除錯。 | +| 可連網以還原 NuGet 套件 | 需要下載轉換函式庫。 | +| 一個簡易的 HTML 檔案(`input.html`) | 作為轉換的來源文件。 | + +> **專業小技巧:** 請將 HTML 檔案放在與專案相同的資料夾中,以免產生路徑相關問題。 + +## 步驟 1:安裝轉換函式庫 + +範例程式使用 **GroupDocs.Conversion for .NET** 函式庫,提供 `HtmlConversionOptions` 與 `Converter` 類別。透過 NuGet 套件管理員安裝: + +```bash +dotnet add package GroupDocs.Conversion +``` + +此套件會將必要的類型加入您的專案,並自動拉入所有相依性。 + +## 步驟 2:建立 C# 主控台專案 + +在命令提示字元執行: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +此指令會建立名為 `HtmlToPdfDemo` 的最小主控台應用程式。開啟產生的 `Program.cs` 檔案,稍後會把內容替換成完整範例。 + +## 步驟 3:設定轉換選項 – 程式化設定字型樣式 + +`HtmlConversionOptions` 類別讓您微調 HTML 引擎的渲染方式。若要 **程式化設定字型樣式**,可使用位元 OR 結合 `WebFontStyle` 列舉值: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**為什麼這很重要:** +* `WebFontStyle.Bold | WebFontStyle.Italic` 會告訴渲染器對使用預設字型的文字同時套用粗體與斜體。 +* 抗鋸齒可減少點陣圖影像在縮放時的鋸齒。 +* Hinting 會將字形輪廓對齊到像素格,提升低解析度螢幕與最終 PDF 的可讀性。 + +## 步驟 4:執行轉換 + +準備好選項後,呼叫 `Converter` 類別。`Convert` 方法接受三個參數:來源 HTML 檔案路徑、目標 PDF 檔案路徑,以及選項物件。 + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +此方法同步執行,若來源檔案無法讀取或輸出路徑無效,會拋出例外。建議在正式環境中將呼叫包在 try‑catch 區塊內。 + +## 步驟 5:驗證結果 + +程式執行完畢後,使用任意 PDF 閱讀器開啟 `output.pdf`,您應該會看到: + +* 文字以 **粗體與斜體** 呈現(即使原始 HTML 未指定這些樣式)。 +* 影像因抗鋸齒而更平滑。 +* 文字因 hinting 而更清晰,特別是在小字體時。 + +若 PDF 未呈現預期樣式,請再次確認 HTML 是否引用了網路安全字型,或已包含可被轉換器載入的 `@font-face` 規則。 + +## 完整、可執行範例 + +以下是一個自包含的程式,整合了前述所有步驟。將程式碼複製到 `Program.cs`,在同目錄放置 `input.html`,然後執行 `dotnet run`。 + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**預期的主控台輸出** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +開啟產生的 PDF,確認字型樣式已正確套用。 + +## 處理常見邊緣案例 + +| 情境 | 建議做法 | +|---|---| +| **外部 CSS 或字型** | 將 CSS 檔案與字型資源放在 `input.html` 同一資料夾,或使用機器可存取的絕對 URL。 | +| **大型 HTML 文件** | 若遇到 `OutOfMemoryException`,可透過調整 `ConversionConfig` 提升預設記憶體上限。 | +| **動態內容(JavaScript)** | 此函式庫不會執行 JavaScript。請在伺服器端預先渲染動態部分,或使用無頭瀏覽器產生靜態 HTML 快照再進行轉換。 | +| **Unicode 字元未顯示** | 確認 HTML 宣告了 ``,且來源字型包含所需字形。 | +| **頁面尺寸不正確** | 設定 `conversionOptions.PageSize = PageSize.A4`(或其他 enum 值)以強制統一尺寸。 | + +## 效能小技巧 + +* 在大量檔案轉換時,重複使用同一個 `Converter` 實例,可減少啟動開銷。 +* 若不需要超連結等功能,可關閉 `EnableHyperlinks` 等不必要的渲染特性,以加速處理。 +* 需要直接透過 HTTP 回傳 PDF 時,可將 PDF 寫入記憶體串流,而非寫入磁碟。 + +## 後續步驟 + +現在您已能 **將 HTML 轉換為 PDF** 並自訂字型設定,接下來可以探索以下相關主題: + +* **程式化設定頁面邊距** – 調整 `conversionOptions.Margin` 以控制留白。 +* **加入浮水印** – 使用 `PdfConversionOptions` 於 PDF 上覆蓋文字或影像。 +* **批次轉換** – 迭代多個 HTML 檔案,並重複使用相同的選項物件。 + +## 接下來該學什麼? + +以下教學與本指南的技巧密切相關,能幫助您進一步掌握 API 功能,並在自己的專案中探索其他實作方式。 + +- [將 HTML 轉換為 PDF(.NET + Aspose.HTML)](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [建立具樣式文字的 HTML 文件並匯出為 PDF – 完整指南](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [將 SVG 轉換為 PDF(.NET + Aspose.HTML)](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/hongkong/net/working-with-html-documents/_index.md index d2685fbe51..40b156fbd8 100644 --- a/html/hongkong/net/working-with-html-documents/_index.md +++ b/html/hongkong/net/working-with-html-documents/_index.md @@ -41,6 +41,8 @@ HTML 文件是網路的支柱,能夠有效地創建和操作它們對於任何 本教學說明如何在 C# 中使用自訂資源處理程式將 HTML 內容保存至檔案或串流,涵蓋完整步驟與範例。 ### [如何使用 CSS 與 C# 加粗標題 – 完整步驟指南](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [在 C# 中載入 HTML 字串 – 使用自訂處理程式的完整指南](./load-html-string-in-c-complete-guide-with-custom-handler/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/hongkong/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/hongkong/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..d911e061c4 --- /dev/null +++ b/html/hongkong/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,329 @@ +--- +category: general +date: 2026-08-03 +description: 在 C# 中載入 HTML 字串並建立自訂處理程式以儲存 HTMLDocument。了解如何使用自訂資源處理來儲存 HTMLDocument。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: zh-hant +lastmod: 2026-08-03 +og_description: 在 C# 中載入 HTML 字串,並使用自訂處理程式儲存 HTMLDocument。本教學展示完整實作與最佳實踐。 +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: 在 C# 中載入 HTML 字串 – 步驟式自訂處理程式指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: 在 C# 中載入 HTML 字串 – 完整指南與自訂處理程式 +url: /zh-hant/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中載入 HTML 字串 – 完整指南與自訂處理程式 + +如果你需要在 C# 應用程式中 **載入 HTML 字串**,本教學會精確說明如何執行,以及如何為資源管理 **建立自訂處理程式**。你還會學習 **如何使用自訂資源處理** 來 **儲存 htmldocument**,讓每個圖片、CSS 檔案或腳本都寫入你指定的位置。 + +我們將一步步走過整個流程——從將原始 HTML 字串轉換為 `HTMLDocument` 物件,到實作一個 `ResourceHandler` 子類別,控制每個資源的儲存位置。完成後,你將擁有一個自足、可直接投入任意 .NET 專案的生產等級範例。 + +## 前置條件 + +- .NET 6.0 或更新版本(程式碼同樣適用於 .NET Framework 4.7+) +- 參考提供 `HTMLDocument`、`ResourceHandler` 與 `ResourceInfo` 的函式庫(例如 *HtmlRenderer* 或其他類似的 HTML‑to‑PDF/DOM 函式庫) +- 基本的 C# 語法與串流概念 + +> **專業提示:** 若使用 Visual Studio,請啟用 *nullable reference types*(`enable`),以提前捕捉 null 相關的錯誤。 + +## 如何將 HTML 字串載入 HTMLDocument + +第一步是將純文字的 HTML 字串轉換成函式庫可操作的 `HTMLDocument` 物件。 + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**為什麼這很重要:** +`HTMLDocument` 會解析標記、建立 DOM 樹,並為之後的儲存作業準備資源(圖片、樣式表等)。直接傳入字串可避免產生暫存檔,讓整個工作流程全程留在記憶體中。 + +### 常見陷阱 + +| 問題 | 為何會發生 | 解決方式 | +|------|------------|----------| +| `htmlContent` 為 `null` | 變數從未被指派值。 | 在建立文件前先驗證:`if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| 編碼問題 | 函式庫預設使用 UTF‑8,但來源使用其他編碼。 | 若有提供 `Encoding` 的重載就使用,或確保字串已正確解碼。 | + +## 建立自訂資源處理程式 + +**自訂資源處理程式** 讓你完全掌控函式庫寫入外部資源(圖片、CSS、字型)的方式。以下是一個最小實作,將每個資源寫入 `MemoryStream`。你可以將內容改寫為檔案系統、雲端儲存或其他目的地。 + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**為什麼需要自訂處理程式:** +預設的處理程式常會把資源寫入暫存資料夾,這在安全性或效能上可能不符合需求。透過覆寫 `HandleResource`,你可以自行決定每個位元組的儲存位置與方式。 + +### 延伸處理程式以輸出至檔案系統 + +若想把每個資源寫入特定資料夾,可將方法改寫如下: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## 如何使用自訂處理程式儲存 htmldocument + +現在我們同時擁有 `HTMLDocument` 實例與 `MyHandler` 實作,便可以將文件持久化。`Save` 方法接受任何 `ResourceHandler` 子類別,讓你插入自訂邏輯。 + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +執行 `Save` 時,函式庫會: + +1. 遍歷 DOM 樹。 +2. 偵測外部資源(例如 ``)。 +3. 為每個資源呼叫 `handler.HandleResource`。 +4. 將資源資料寫入回傳的串流。 +5. 完成主要 HTML 輸出(通常是獨立的檔案或串流)。 + +### 驗證結果 + +若使用檔案系統版的 `MyHandler`,應會看到一個 `output` 資料夾,內含原始 HTML 檔案與所有參考的資產。若使用 `MemoryStream` 版,則可檢查串流長度以確認資料已寫入: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## 完整、可執行的範例 + +以下是一個可直接複製貼上的完整程式,示範整個流程。程式內含錯誤處理、串流釋放,以及說明每一步的註解。 + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**預期輸出** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +執行程式後,`output` 目錄會包含: + +- `index.html`(主文件) +- 函式庫產生的其他檔案(例如圖片、CSS) + +## 進階變形與邊緣情況 + +### 儲存至 `MemoryStream` 以進行記憶體內處理 + +若需要最終的 HTML 為字串,或想在不寫入磁碟的情況下透過 HTTP 傳送,可將 `MyHandler` 換成回傳共用 `MemoryStream` 的版本: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +在 `htmlDoc.Save(handler)` 之後,即可讀取 HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### 安全處理大型資源 + +面對大型圖片或 PDF 時,避免一次將整個檔案載入記憶體。改為回傳直接寫入磁碟的 `FileStream`(如前述範例),可防止高吞吐量情境下的 `OutOfMemoryException`。 + +### 執行緒安全考量 + +`HTMLDocument` 實例 **不是** 執行緒安全的。若需同時處理多筆 HTML 字串,請為每個執行緒建立獨立的 `HTMLDocument` 與 `MyHandler`,或使用 `lock` 進行同步。 + +### 釋放串流 + +`HTMLDocument.Save` 與 `ResourceHandler.HandleResource` 可能會回傳需要自行釋放的串流。在上述範例中,函式庫會在寫入完成後自動釋放。但若你自行開啟 `FileStream` 再呼叫 `Save`,請務必以 `using` 包裹以確保釋放。 + +## 小結 + +本指南說明了如何 **載入 HTML 字串** 成 `HTMLDocument`、**建立自訂處理程式** 以決定資源儲存方式,並 **使用自訂資源處理** 來 **儲存 htmldocument**。你現在已掌握: + +1. 將原始 HTML 轉換為 DOM 物件的清晰步驟。 +2. 可重複使用的 `ResourceHandler` 子類別,能將資源寫入記憶體、磁碟或雲端。 +3. 完整、可執行的程式範例,展示完整工作流程。 + +## 往後的步驟 + +- 探索其他 `ResourceHandler` 覆寫,例如 `HandleCss` 或 `HandleFont`(若函式庫提供)。 +- 結合 PDF 轉換步驟,從 HTML 產生 PDF,同時保持對嵌入資產的完整控制。 +- 查閱函式庫文件,了解 *壓縮*、*快取*、*非同步* 儲存等額外選項。 + +歡迎自行嘗試不同的儲存策略,並在評論或你喜愛的開發者社群分享你的發現。祝開發順利! + +## 接下來該學什麼? + +以下教學與本指南內容密切相關,能進一步深化你所學的技巧。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能或探索替代實作方式。 + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 53dd8b575e..33697dcc49 100644 --- a/html/hungarian/net/html-extensions-and-conversions/_index.md +++ b/html/hungarian/net/html-extensions-and-conversions/_index.md @@ -38,6 +38,7 @@ Az Aspose.HTML for .NET nem csak egy könyvtár; ez egy változás a webfejleszt ## HTML-kiterjesztések és -konverziók oktatóanyagok ### [Konvertálja a HTML-t PDF-be .NET-ben az Aspose.HTML-lel](./convert-html-to-pdf/) +### [Konvertálja a HTML-t PDF-be C#‑ban – betűstílus programozott beállítása](./convert-html-to-pdf-in-c-set-font-style-programmatically/) ### [Az Aspose.HTML segítségével EPUB-t konvertáljon képpé .NET-ben](./convert-epub-to-image/) ### [Konvertálja az EPUB-t PDF-be .NET-ben az Aspose.HTML segítségével](./convert-epub-to-pdf/) ### [Konvertálja az EPUB-t XPS-re .NET-ben az Aspose.HTML segítségével](./convert-epub-to-xps/) diff --git a/html/hungarian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/hungarian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..ce91b379be --- /dev/null +++ b/html/hungarian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-08-03 +description: HTML konvertálása PDF-be C#-ban teljes renderelés-vezérléssel. Tanulja + meg, hogyan állíthatja be a betűstílust programozottan, engedélyezheti az élsimítást, + és javíthatja a szöveg tisztaságát. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: hu +lastmod: 2026-08-03 +og_description: HTML konvertálása PDF-be C#-ban részletes beállításokkal. Ez az útmutató + bemutatja, hogyan állítható be programozottan a betűstílus, hogyan engedélyezhető + az antialiasing, és hogyan készíthetők magas minőségű PDF‑ek. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: HTML konvertálása PDF-be C#-ban – teljes renderelés-vezérlés +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: HTML konvertálása PDF-be C#-ban – betűstílus programozott beállítása +url: /hu/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML konvertálása PDF-re C#-ban – betűstílus programozott beállítása + +Ha **HTML-t PDF-re kell konvertálni** egy .NET alkalmazásban, ez a bemutató egy teljes, termelés‑kész megoldáson keresztül vezet végig. Megmutatjuk, hogyan **állítható be a betűstílus programozottan**, hogyan javítható a képek megjelenítése, és hogyan engedélyezhető a szöveg hinting – mindezt anélkül, hogy elhagyná a C# kódját. + +A weboldalak PDF-re konvertálása gyakori igény jelentések, számlázás és archiválás céljából. Ez az útmutató mindent lefed a projekt beállításától egy teljes, futtatható példáig. A cikk végére képes lesz PDF-eket generálni, amelyek megőrzik a elrendezést, tipográfiát és a vizuális hűséget. + +## Mit fog megtanulni + +* Hogyan adja hozzá a szükséges NuGet csomagot és importálja a névtereket. +* Hogyan konfigurálja a `HtmlConversionOptions`-t a renderelés szabályozásához. +* Hogyan **állítható be a betűstílus programozottan** a `WebFontStyle` zászlók használatával. +* Hogyan engedélyezhető az antialiasing a képekhez és a hinting a szöveghez. +* Hogyan hívható meg a `Converter` osztály a végleges PDF fájl előállításához. + +A bemutató feltételezi, hogy a Visual Studio 2022 (vagy újabb) és a .NET 6 vagy újabb telepítve van. További eszközök nem szükségesek. + +## Előfeltételek + +| Követelmény | Indoklás | +|---|---| +| .NET 6 SDK vagy újabb | Biztosítja a futtatókörnyezetet a C# projekthez. | +| Visual Studio 2022 (vagy bármely IDE) | Lehetővé teszi a könnyű projekt létrehozást és hibakeresést. | +| Internetkapcsolat a NuGet csomagok visszaállításához | Szükséges a konverziós könyvtár letöltéséhez. | +| Egyszerű HTML fájl (`input.html`) | A konverzió forrásdokumentumaként szolgál. | + +> **Pro tipp:** Tartsa a HTML fájlt a projekt ugyanabban a mappájában, hogy elkerülje az útvonallal kapcsolatos problémákat. + +## 1. lépés: A konverziós könyvtár telepítése + +A kódminta a **GroupDocs.Conversion for .NET** könyvtárat használja, amely `HtmlConversionOptions`-t és egy `Converter` osztályt biztosít. Telepítse a NuGet Package Manager segítségével: + +```bash +dotnet add package GroupDocs.Conversion +``` + +A csomag hozzáadja a szükséges típusokat a projekthez, és letölti az összes függőséget. + +## 2. lépés: C# konzolprojekt létrehozása + +Nyisson meg egy parancssort, és futtassa: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +## 3. lépés: Konverziós beállítások konfigurálása – betűstílus programozott beállítása + +A `HtmlConversionOptions` osztály lehetővé teszi, hogy finomhangolja, hogyan rendereli a HTML motor az oldalt. A **betűstílus programozott beállításához** kombinálja a `WebFontStyle` felsorolás értékeit bitwise OR segítségével: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Miért fontos:** +* `WebFontStyle.Bold | WebFontStyle.Italic` azt mondja a renderelőnek, hogy mindkét stílust alkalmazza minden olyan szövegre, amely az alapértelmezett betűtípust használja. +* Az antialiasing csökkenti a lépcsőzetes éleket a raszteres képeken, különösen nagyításkor. +* A hinting a glifvonalakat a pixelrácshoz igazítja, javítva az olvashatóságot alacsony felbontású képernyőkön és a létrehozott PDF-ben. + +## 4. lépés: A konverzió végrehajtása + +A beállítások elkészülte után hívja meg a `Converter` osztályt. A `Convert` metódus három argumentumot vár: a forrás HTML fájl útvonalát, a cél PDF fájl útvonalát és a beállítási objektumot. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +A metódus szinkron módon fut, és kivételt dob, ha a forrásfájl nem olvasható vagy a kimeneti útvonal érvénytelen. A hívást helyezze try‑catch blokkba a termelési kódban. + +## 5. lépés: Az eredmény ellenőrzése + +A program befejezése után nyissa meg az `output.pdf`-et bármely PDF megjelenítővel. A következőket kell látnia: + +* A szöveg **félkövér és dőlt** formában jelenik meg (még akkor is, ha az eredeti HTML nem határozta meg ezeket a stílusokat). +* A képek simábbak az antialiasingnek köszönhetően. +* A szöveg tisztasága javul a hintingnek köszönhetően, különösen kis betűméreteknél. + +Ha a PDF nem tükrözi a várt stílusokat, ellenőrizze újra, hogy a HTML fájl web‑biztonságos betűtípust hivatkozik-e, vagy tartalmaz-e egy `@font-face` szabályt, amelyet a konverter be tud tölteni. + +## Teljes, futtatható példa + +Az alábbi önálló program tartalmazza az összes korábbi lépést. Másolja a kódot a `Program.cs`-be, helyezzen egy `input.html` fájlt mellé, és futtassa a `dotnet run` parancsot. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Várható konzolkimenet** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Nyissa meg a generált PDF-et, hogy megerősítse a alkalmazott stílusokat. + +## Gyakori edge case-ek kezelése + +| Helyzet | Ajánlott megközelítés | +|---|---| +| **Külső CSS vagy betűtípusok** | Helyezze a CSS fájlokat és betűtípus-resszurseket ugyanabba a mappába, mint az `input.html`, vagy hivatkozzon rájuk abszolút URL-ekkel, amelyek elérhetők a konverziót futtató gépről. | +| **Nagy HTML dokumentumok** | Növelje az alapértelmezett memóriahatárt a `ConversionConfig` módosításával, ha `OutOfMemoryException`-t kap. | +| **Dinamikus tartalom (JavaScript)** | A könyvtár nem hajt végre JavaScriptet. Előre renderelje a dinamikus részeket szerveroldalon, vagy használjon headless böngészőt, hogy statikus HTML pillanatképet készítsen a konverzió előtt. | +| **Unicode karakterek nem jelennek meg** | Győződjön meg róla, hogy a HTML tartalmazza a `` elemet, és a forrás betűtípusok tartalmazzák a szükséges glifeket. | +| **Helytelen oldalméret** | Állítsa be a `conversionOptions.PageSize = PageSize.A4` (vagy más enum értéket) a konzisztens méretek biztosításához. | + +## Teljesítmény tippek + +* Használjon egyetlen `Converter` példányt több fájl konvertálásakor; ez csökkenti az indítási terhelést. +* Tiltsa le a felesleges renderelési funkciókat (pl. `EnableHyperlinks`), ha nincs rájuk szüksége, ez felgyorsítja a feldolgozást. +* Írja a PDF-et egy memóriafolyamba, ha közvetlenül HTTP-n kell továbbítani, ahelyett, hogy lemezre írna. + +## Következő lépések + +Most, hogy **HTML-t PDF-re tud konvertálni** egyedi betűtípus beállításokkal, fedezze fel ezeket a kapcsolódó témákat: + +- **Oldal margók programozott beállítása** – állítsa be a `conversionOptions.Margin`-t a fehér tér szabályozásához. +- **Vízjelek hozzáadása** – használja a `PdfConversionOptions`-t szöveg vagy képek átfedéséhez. +- **Kötegelt konverzió** – iteráljon egy HTML fájlok gyűjteményén, és használja újra ugyanazt a beállítási objektumot. + +## Mit tanuljon meg legközelebb? + +Az alábbi bemutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsen elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket saját projektjeiben. + +- [HTML konvertálása PDF-re .NET-ben az Aspose.HTML segítségével](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [HTML dokumentum létrehozása formázott szöveggel és exportálása PDF-re – Teljes útmutató](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [SVG konvertálása PDF-re .NET-ben az Aspose.HTML segítségével](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/hungarian/net/working-with-html-documents/_index.md b/html/hungarian/net/working-with-html-documents/_index.md index 81c4e72f31..fd914d414b 100644 --- a/html/hungarian/net/working-with-html-documents/_index.md +++ b/html/hungarian/net/working-with-html-documents/_index.md @@ -36,6 +36,8 @@ Miután megértette az alapokat, mélyebbre ásunk az alkotás folyamatában. Eb Most emeljük tudását a következő szintre. A HTML-dokumentumok szerkesztése gyakori feladat a webfejlesztők számára, és az Aspose.HTML jelentősen leegyszerűsíti ezt a folyamatot. Ebben a részben a dokumentumok létrehozásával, manipulálásával és stílusával foglalkozunk. Felfedezi, hogyan javíthatja webtartalma megjelenését és funkcionalitását, hogy vonzóvá és felhasználóbaráttá tegye azt. +### [HTML string betöltése C#-ban – Teljes útmutató egyéni kezelővel](./load-html-string-in-c-complete-guide-with-custom-handler/) + ### [HTML mentése C#-ban – Teljes útmutató egy egyéni erőforráskezelő használatával](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [Hogyan tegyünk félkövér címet CSS‑el és C#‑val – Teljes lépésről‑lépésre útmutató](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) diff --git a/html/hungarian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/hungarian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..e026984b36 --- /dev/null +++ b/html/hungarian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-03 +description: HTML-karakterlánc betöltése C#-ban és egyedi kezelő létrehozása az HTMLDocument + mentéséhez. Tanulja meg, hogyan mentse az HTMLDocument-et egyedi erőforráskezeléssel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: hu +lastmod: 2026-08-03 +og_description: Tölts be HTML-karakterláncot C#-ban, és használj egy egyéni kezelőt + az HTMLDocument mentéséhez. Ez az útmutató bemutatja a teljes megvalósítást és a + legjobb gyakorlatokat. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: HTML karakterlánc betöltése C#‑ban – lépésről‑lépésre útmutató egyedi kezelőhöz +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: HTML string betöltése C#‑ban – teljes útmutató egyedi kezelővel +url: /hu/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML karakterlánc betöltése C#‑ban – teljes útmutató egyedi kezelővel + +Ha **HTML karakterláncot** kell betöltenie egy C# alkalmazásba, ez a bemutató pontosan megmutatja, hogyan teheti meg, és hogyan **hozhat létre egyedi kezelőt** az erőforrás‑kezeléshez. Emellett megtanulja, **hogyan mentse el a htmldocument‑ot** **egyedi erőforráskezeléssel**, hogy minden kép, CSS‑fájl vagy szkript pontosan oda kerüljön, ahová szeretné. + +Végigvezetjük az egész folyamaton – a nyers HTML karakterlánc `HTMLDocument` objektummá alakításától kezdve egy `ResourceHandler` alosztály megvalósításáig, amely szabályozza, hogy az egyes erőforrások hol legyenek tárolva. A végére egy önálló, termelésre kész példát kap, amelyet bármely .NET projektbe beilleszthet. + +## Előfeltételek + +- .NET 6.0 vagy újabb (a kód .NET Framework 4.7+‑on is működik) +- Hivatkozás a könyvtárra, amely biztosítja a `HTMLDocument`, `ResourceHandler` és `ResourceInfo` osztályokat (pl. *HtmlRenderer* vagy egy hasonló HTML‑to‑PDF/DOM könyvtár) +- Alapvető C# szintaxis és stream ismeretek + +> **Pro tipp:** Ha Visual Studio‑t használ, engedélyezze a *nullable reference types* funkciót (`enable`), hogy korán elkapja a null‑hoz kapcsolódó hibákat. + +## HTML karakterlánc betöltése HTMLDocument‑ba + +Az első lépés egy egyszerű HTML karakterlánc `HTMLDocument` objektummá alakítása, amelyet a könyvtár használni tud. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Miért fontos ez:** +`HTMLDocument` elemzi a jelölőnyelvet, felépíti a DOM‑fát, és előkészíti az erőforrásokat (képek, stíluslapok stb.) a későbbi mentéshez. A karakterlánc közvetlen átadása elkerüli az ideiglenes fájlok használatát, és a munkafolyamatot memóriában tartja. + +### Gyakori buktatók + +| Probléma | Miért fordul elő | Megoldás | +|----------|------------------|----------| +| `htmlContent` `null` értékű | A karakterlánc változó soha nem kapott értéket. | Ellenőrizze a dokumentum létrehozása előtt: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Kódolási problémák | A könyvtár UTF‑8‑at feltételez, de a forrás más kódolást használ. | Adj meg egy explicit `Encoding` túlterhelést, ha elérhető, vagy győződj meg arról, hogy a karakterlánc helyesen van dekódolva. | + +## Egyedi kezelő létrehozása az erőforráskezeléshez + +Egy **egyedi erőforráskezelő** teljes irányítást ad arra, hogyan írja a könyvtár a külső erőforrásokat (képek, CSS, betűkészletek). Az alábbiakban egy minimális megvalósítást láthat, amely minden erőforrást egy `MemoryStream`‑be ír. A testet helyettesítheti fájlrendszer‑logikával, felhő‑tárolóval vagy bármilyen más célhellyel. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Miért van szükség egyedi kezelőre:** +Az alapértelmezett kezelő gyakran egy ideiglenes mappába írja az erőforrásokat, ami biztonsági vagy teljesítménybeli okokból nem kívánatos lehet. A `HandleResource` felülírásával pontosan meghatározhatja, hogy az egyes bájtok hol és hogyan legyenek tárolva. + +### A kezelő kiterjesztése fájl kimenethez + +Ha inkább minden erőforrást egy adott mappába szeretne írni, módosítsa a metódust a következőképpen: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## HTMLDocument mentése egyedi kezelővel + +Miután megvan mind a `HTMLDocument` példány, mind a `MyHandler` megvalósítás, elmenthetjük a dokumentumot. A `Save` metódus bármely `ResourceHandler` alosztályt elfogad, lehetővé téve, hogy saját logikáját csatlakoztassa. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Amikor a `Save` fut, a könyvtár a következőket teszi: + +1. Bejárja a DOM fát. +2. Felismeri a külső erőforrásokat (pl. ``). +3. Meghívja a `handler.HandleResource` metódust minden erőforrásra. +4. Az erőforrás adatát a visszaadott stream‑be írja. +5. Befejezi a fő HTML kimenetet (gyakran külön fájlként vagy stream‑ként). + +### Az eredmény ellenőrzése + +Ha a `MyHandler` fájlrendszer‑változatát használta, egy `output` mappát kell látnia az eredeti HTML fájllal és a hivatkozott eszközökkel. A `MemoryStream` változat esetén ellenőrizheti a stream hosszát, hogy megerősítse az adat írását: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Teljes, futtatható példa + +Az alábbi egy önálló, másolás‑beillesztésre kész program, amely bemutatja a teljes folyamatot. Tartalmaz hibakezelést, stream‑ek felszabadítását, és megjegyzéseket, amelyek minden lépést elmagyaráznak. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Várható kimenet** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +A program futtatása után az `output` könyvtár a következőket tartalmazza: + +- `index.html` (a fő dokumentum) +- Bármely további fájl, amelyet a könyvtár generált (pl. képek, CSS) + +## Haladó változatok és szélhelyzetek + +### Mentés `MemoryStream`‑be a memória‑beli feldolgozáshoz + +Ha a végleges HTML‑t karakterláncként kell megkapnia, vagy HTTP‑n keresztül szeretné elküldeni anélkül, hogy lemezhez nyúlna, cserélje le a `MyHandler`‑t egy olyan verzióra, amely egy megosztott `MemoryStream`‑et ad vissza: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +`htmlDoc.Save(handler)` után beolvashatja a HTML‑t: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Nagy erőforrások biztonságos kezelése + +Nagy képek vagy PDF‑ek kezelésekor kerülje el a teljes fájl memóriába töltését. Ehelyett adjon vissza egy `FileStream`‑et, amely közvetlenül a lemezre ír, ahogyan korábban bemutattuk. Ez megakadályozza az `OutOfMemoryException` kivételt nagy áteresztőképességű helyzetekben. + +### Szálbiztonsági szempontok + +A `HTMLDocument` példányok **nem** szálbiztosak. Ha egyszerre több HTML karakterláncot kell feldolgoznia, hozzon létre egy külön `HTMLDocument` és `MyHandler` példányt szálanként, vagy szinkronizálja a hozzáférést egy `lock`‑kal. + +### Stream‑ek felszabadítása + +A `HTMLDocument.Save` és a `ResourceHandler.HandleResource` egyaránt visszaadhat stream‑eket, amelyeket fel kell szabadítani. A fenti példákban a könyvtár automatikusan felszabadítja a stream‑eket a írás után. Ha saját maga kezeli a stream‑eket (pl. `FileStream`‑et nyit a `Save` hívása előtt), csomagolja őket `using` blokkokba. + +## Összefoglaló + +Ez az útmutató megmutatta, hogyan **töltsön be HTML karakterláncot** egy `HTMLDocument`‑ba, **hozzon létre egyedi kezelőt** az erőforrások tárolásának meghatározásához, és **hogyan mentse el a htmldocument‑ot** **egyedi erőforráskezeléssel**. Most már rendelkezik: + +1. Egyértelmű módszerrel, amellyel a nyers HTML‑t DOM objektummá alakíthatja. +2. Újrahasználható `ResourceHandler` alosztállyal, amely erőforrásokat memóriába, lemezre vagy felhő‑tárolóba ír. +3. Egy teljes, futtatható programmal, amely bemutatja a teljes munkafolyamatot. + +## Következő lépések + +- Fedezze fel a többi `ResourceHandler` felülírást, például a `HandleCss` vagy `HandleFont`‑ot, ha a könyvtára támogatja őket. +- Kombinálja ezt a megközelítést egy PDF konverziós lépéssel, hogy HTML‑ből PDF‑et generáljon, miközben teljes irányítást tart a beágyazott eszközök felett. +- Tekintse át a könyvtár dokumentációját további lehetőségekért, mint a *compression*, *caching* vagy *asynchronous* mentés. + +Nyugodtan kísérletezzen különböző tárolási stratégiákkal, és ossza meg eredményeit a megjegyzésekben vagy kedvenc fejlesztői közösségében. Boldog kódolást! + +## Mit érdemes legközelebb megtanulni? + +Az alábbi bemutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsen elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket saját projektjeiben. + +- [Hogyan mentse el a HTML-t C#‑ban – Teljes útmutató egyedi erőforráskezelő használatával](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [HTML létrehozása karakterláncból C#‑ban – Egyedi erőforráskezelő útmutató](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Hogyan zip‑elje a HTML-t C#‑ban – HTML mentése ZIP‑be](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 6ac5368fff..69bb994e09 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/) @@ -73,6 +73,8 @@ Pelajari cara membuat dokumen HTML dengan teks berformat dan mengekspornya ke PD Pelajari cara menyimpan file HTML sebagai arsip ZIP menggunakan Aspose.HTML untuk .NET dengan contoh kode C# lengkap. ### [Simpan HTML ke ZIP di C# – Contoh In‑Memory Lengkap](./save-html-to-zip-in-c-complete-in-memory-example/) Pelajari cara menyimpan file HTML ke dalam arsip ZIP secara langsung di memori menggunakan C# dan Aspose.HTML. +### [Konversi HTML ke PDF di C# – mengatur gaya font secara programatis](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Pelajari cara mengonversi HTML ke PDF di C# sambil mengatur gaya font secara programatis menggunakan Aspose.HTML. ## Kesimpulan diff --git a/html/indonesian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/indonesian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..bcb8b57949 --- /dev/null +++ b/html/indonesian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,228 @@ +--- +category: general +date: 2026-08-03 +description: Konversi HTML ke PDF dalam C# dengan kontrol rendering penuh. Pelajari + cara mengatur gaya font secara programatis, mengaktifkan antialiasing, dan meningkatkan + kejernihan teks. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: id +lastmod: 2026-08-03 +og_description: Konversi HTML ke PDF dalam C# dengan opsi terperinci. Panduan ini + menunjukkan cara mengatur gaya font secara programatis, mengaktifkan antialiasing, + dan menghasilkan PDF berkualitas tinggi. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Konversi HTML ke PDF di C# – kontrol rendering penuh +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Mengonversi HTML ke PDF di C# – mengatur gaya font secara programatis +url: /id/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mengonversi HTML ke PDF di C# – mengatur gaya font secara programatis + +Jika Anda perlu **mengonversi HTML ke PDF** dalam aplikasi .NET, tutorial ini akan memandu Anda melalui solusi lengkap yang siap produksi. Anda akan melihat cara **mengatur gaya font secara programatis**, meningkatkan rendering gambar, dan mengaktifkan hinting teks—semua tanpa meninggalkan kode C# Anda. + +Mengonversi halaman web ke PDF adalah kebutuhan umum untuk pelaporan, penagihan, dan pengarsipan. Panduan ini mencakup semua hal mulai dari penyiapan proyek hingga contoh lengkap yang dapat dijalankan. Pada akhir artikel Anda dapat menghasilkan PDF yang mempertahankan tata letak, tipografi, dan kesetiaan visual. + +## Apa yang akan Anda pelajari + +* Cara menambahkan paket NuGet yang diperlukan dan mengimpor namespace. +* Cara mengonfigurasi `HtmlConversionOptions` untuk mengontrol rendering. +* Cara **mengatur gaya font secara programatis** menggunakan flag `WebFontStyle`. +* Cara mengaktifkan antialiasing untuk gambar dan hinting untuk teks. +* Cara memanggil kelas `Converter` untuk menghasilkan file PDF akhir. + +Tutorial ini mengasumsikan Anda memiliki Visual Studio 2022 (atau lebih baru) dan .NET 6 atau yang lebih baru terpasang. Tidak diperlukan alat tambahan. + +## Prasyarat + +| Persyaratan | Alasan | +|---|---| +| .NET 6 SDK atau lebih baru | Menyediakan runtime untuk proyek C#. | +| Visual Studio 2022 (atau IDE apa pun) | Memungkinkan pembuatan proyek dan debugging yang mudah. | +| Akses internet untuk memulihkan paket NuGet | Diperlukan untuk mengunduh perpustakaan konversi. | +| File HTML sederhana (`input.html`) | Berfungsi sebagai dokumen sumber untuk konversi. | + +> **Pro tip:** Simpan file HTML di folder yang sama dengan proyek untuk menghindari masalah terkait jalur. + +## Langkah 1: Instal perpustakaan konversi + +Contoh kode menggunakan perpustakaan **GroupDocs.Conversion for .NET**, yang menyediakan `HtmlConversionOptions` dan kelas `Converter`. Instal melalui NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +## Langkah 2: Buat proyek konsol C# + +Buka command prompt dan jalankan: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +## Langkah 3: Konfigurasikan opsi konversi – mengatur gaya font secara programatis + +Kelas `HtmlConversionOptions` memungkinkan Anda menyesuaikan cara mesin HTML merender halaman. Untuk **mengatur gaya font secara programatis**, gabungkan nilai enumerasi `WebFontStyle` menggunakan operator OR bitwise: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Mengapa ini penting:** +* `WebFontStyle.Bold | WebFontStyle.Italic` memberi tahu renderer untuk menerapkan kedua gaya pada teks apa pun yang menggunakan font default. +* Antialiasing mengurangi tepi bergerigi pada gambar raster, terutama saat memperbesar. +* Hinting menyelaraskan kontur glyph ke grid piksel, meningkatkan keterbacaan pada layar beresolusi rendah dan pada PDF yang dihasilkan. + +## Langkah 4: Lakukan konversi + +Dengan opsi yang telah disiapkan, panggil kelas `Converter`. Metode `Convert` menerima tiga argumen: jalur file HTML sumber, jalur file PDF tujuan, dan objek opsi. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Metode ini berjalan secara sinkron dan melemparkan pengecualian jika file sumber tidak dapat dibaca atau jalur output tidak valid. Bungkus pemanggilan dalam blok try‑catch untuk kode produksi. + +## Langkah 5: Verifikasi hasil + +Setelah program selesai, buka `output.pdf` dengan penampil PDF apa pun. Anda harus melihat: + +* Teks dirender dalam **tebal dan miring** (meskipun HTML asli tidak menentukan gaya tersebut). +* Gambar tampak lebih halus berkat antialiasing. +* Kejernihan teks meningkat dengan hinting, terutama untuk ukuran font kecil. + +Jika PDF tidak mencerminkan gaya yang diharapkan, periksa kembali bahwa file HTML merujuk pada font web‑safe atau menyertakan aturan `@font-face` yang dapat dimuat oleh konverter. + +## Contoh lengkap yang dapat dijalankan + +Berikut adalah program mandiri yang menggabungkan semua langkah sebelumnya. Salin kode ke `Program.cs`, letakkan file `input.html` di sampingnya, dan jalankan `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Output konsol yang diharapkan** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Buka PDF yang dihasilkan untuk mengonfirmasi gaya yang diterapkan. + +## Menangani kasus tepi umum + +| Situasi | Pendekatan yang disarankan | +|---|---| +| **External CSS or fonts** | Letakkan file CSS dan sumber daya font di folder yang sama dengan `input.html` atau referensikan mereka dengan URL absolut yang dapat dijangkau dari mesin yang menjalankan konversi. | +| **Large HTML documents** | Tingkatkan batas memori default dengan menyesuaikan `ConversionConfig` jika Anda menemui `OutOfMemoryException`. | +| **Dynamic content (JavaScript)** | Perpustakaan tidak mengeksekusi JavaScript. Prarender bagian dinamis di sisi server atau gunakan browser headless untuk menghasilkan snapshot HTML statis sebelum konversi. | +| **Unicode characters not displaying** | Pastikan HTML mendeklarasikan `` dan bahwa font sumber berisi glyph yang diperlukan. | +| **Incorrect page size** | Setel `conversionOptions.PageSize = PageSize.A4` (atau nilai enum lain) untuk menegakkan dimensi yang konsisten. | + +## Tips kinerja + +* Gunakan kembali satu instance `Converter` saat mengonversi banyak file; ini mengurangi overhead startup. +* Nonaktifkan fitur rendering yang tidak diperlukan (misalnya, `EnableHyperlinks`) jika Anda tidak membutuhkannya, yang mempercepat proses. +* Tulis PDF ke memory stream ketika Anda perlu mengirimnya langsung melalui HTTP alih-alih menulis ke disk. + +## Langkah selanjutnya + +Sekarang Anda dapat **mengonversi HTML ke PDF** dengan pengaturan font khusus, jelajahi topik terkait berikut: + +- [Mengonversi HTML ke PDF di .NET dengan Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Buat Dokumen HTML dengan Teks Bergaya dan Ekspor ke PDF – Panduan Lengkap](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Mengonversi SVG ke PDF di .NET dengan Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/indonesian/net/working-with-html-documents/_index.md b/html/indonesian/net/working-with-html-documents/_index.md index b7ad357be1..6fc159b1bd 100644 --- a/html/indonesian/net/working-with-html-documents/_index.md +++ b/html/indonesian/net/working-with-html-documents/_index.md @@ -37,8 +37,13 @@ Setelah Anda memahami dasar-dasarnya, kita akan mempelajari lebih dalam proses p Sekarang, mari tingkatkan keterampilan Anda ke tingkat berikutnya. Mengedit dokumen HTML merupakan tugas umum bagi pengembang web, dan Aspose.HTML menyederhanakan proses ini secara signifikan. Di bagian ini, kami akan membahas pembuatan, manipulasi, dan penataan dokumen. Anda akan menemukan cara meningkatkan tampilan dan fungsionalitas konten web Anda, membuatnya menarik dan mudah digunakan. ### [Cara Menyimpan HTML di C# – Panduan Lengkap Menggunakan Penangan Sumber Daya Kustom](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + ### [Cara Membuat Heading Tebal dengan CSS & C# – Panduan Lengkap Langkah demi Langkah](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Muat string HTML di C# – Panduan Lengkap dengan Penangan Kustom](./load-html-string-in-c-complete-guide-with-custom-handler/) + +Pelajari cara memuat string HTML secara langsung di C# menggunakan Aspose.HTML dengan penangan sumber daya khusus untuk kontrol penuh. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/indonesian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/indonesian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..1b62283973 --- /dev/null +++ b/html/indonesian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-03 +description: Muat string HTML di C# dan buat penangan khusus untuk menyimpan HTMLDocument. + Pelajari cara menyimpan HTMLDocument dengan penangan sumber daya khusus. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: id +lastmod: 2026-08-03 +og_description: Muat string HTML di C# dan gunakan penangan khusus untuk menyimpan + HTMLDocument. Tutorial ini menunjukkan implementasi lengkap serta praktik terbaik. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Muat string HTML di C# – panduan penangan khusus langkah demi langkah +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Muat string HTML di C# – panduan lengkap dengan handler khusus +url: /id/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Muat string html di C# – panduan lengkap dengan handler khusus + +Jika Anda perlu **load html string** dalam aplikasi C#, tutorial ini menunjukkan secara tepat cara melakukannya dan cara **create custom handler** untuk manajemen sumber daya. Anda juga akan belajar **how to save htmldocument** menggunakan **custom resource handling** sehingga setiap gambar, file CSS, atau skrip ditulis tepat di tempat yang Anda inginkan. + +Kami akan menelusuri seluruh proses—dari mengubah string HTML mentah menjadi objek `HTMLDocument`, hingga mengimplementasikan subclass `ResourceHandler` yang mengontrol dimana setiap sumber daya disimpan. Pada akhir tutorial, Anda akan memiliki contoh yang mandiri, siap produksi, yang dapat Anda gunakan di proyek .NET mana pun. + +## Prasyarat + +- .NET 6.0 atau lebih baru (kode juga berfungsi pada .NET Framework 4.7+) +- Referensi ke pustaka yang menyediakan `HTMLDocument`, `ResourceHandler`, dan `ResourceInfo` (mis., *HtmlRenderer* atau pustaka HTML‑to‑PDF/DOM serupa) +- Pengetahuan dasar tentang sintaks C# dan stream + +> **Pro tip:** Jika Anda menggunakan Visual Studio, aktifkan *nullable reference types* (`enable`) untuk menangkap bug terkait null lebih awal. + +## Cara memuat string html ke dalam HTMLDocument + +Langkah pertama adalah mengonversi string HTML biasa menjadi objek `HTMLDocument` yang dapat diproses oleh pustaka. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Mengapa ini penting:** +`HTMLDocument` mengurai markup, membangun pohon DOM, dan menyiapkan sumber daya (gambar, stylesheet, dll.) untuk penyimpanan nanti. Mengirimkan string secara langsung menghindari kebutuhan file sementara dan menjaga alur kerja tetap dalam memori. + +### Kesalahan umum + +| Masalah | Mengapa terjadi | Perbaikan | +|-------|----------------|-----| +| `htmlContent` is `null` | Variabel string tidak pernah diberikan nilai. | Validasi sebelum membuat dokumen: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | Pustaka mengasumsikan UTF‑8 tetapi sumber menggunakan encoding lain. | Berikan overload `Encoding` secara eksplisit jika tersedia, atau pastikan string terdekripsi dengan benar. | + +## Buat handler khusus untuk penanganan sumber daya + +Sebuah **custom resource handler** memberi Anda kontrol penuh atas cara pustaka menulis sumber daya eksternal (gambar, CSS, font). Di bawah ini adalah implementasi minimal yang menulis setiap sumber daya ke `MemoryStream`. Anda dapat mengganti isi dengan logika sistem file, penyimpanan cloud, atau tujuan lain apa pun. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Mengapa Anda memerlukan handler khusus:** +Handler default sering menulis sumber daya ke folder sementara, yang dapat tidak diinginkan karena alasan keamanan atau kinerja. Dengan menimpa `HandleResource`, Anda memutuskan tepat dimana dan bagaimana setiap byte disimpan. + +### Memperluas handler untuk output file + +Jika Anda lebih suka menulis setiap sumber daya ke folder tertentu, ubah metode berikut: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Cara menyimpan htmldocument menggunakan handler khusus + +Sekarang kita memiliki instance `HTMLDocument` dan implementasi `MyHandler`, kita dapat menyimpan dokumen. Metode `Save` menerima subclass `ResourceHandler` apa pun, memungkinkan Anda menyisipkan logika khusus Anda. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +When `Save` runs, the library will: + +1. Menelusuri pohon DOM. +2. Mendeteksi sumber daya eksternal (mis., ``). +3. Memanggil `handler.HandleResource` untuk setiap sumber daya. +4. Menulis data sumber daya ke dalam stream yang dikembalikan. +5. Menyelesaikan output HTML utama (sering sebagai file atau stream terpisah). + +### Memverifikasi hasil + +Jika Anda menggunakan versi sistem file dari `MyHandler`, Anda akan melihat folder `output` dengan file HTML asli dan semua aset yang direferensikan. Untuk versi `MemoryStream`, Anda dapat memeriksa panjang stream untuk memastikan data telah ditulis: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Contoh lengkap yang dapat dijalankan + +Berikut adalah program tunggal yang siap disalin‑tempel yang mendemonstrasikan seluruh alur. Program ini mencakup penanganan error, pembuangan stream, dan komentar yang menjelaskan setiap langkah. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Output yang diharapkan** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Setelah menjalankan program, direktori `output` berisi: + +- `index.html` (dokumen utama) +- File tambahan apa pun yang dihasilkan pustaka (mis., gambar, CSS) + +## Variasi lanjutan dan kasus tepi + +### Menyimpan ke `MemoryStream` untuk pemrosesan dalam memori + +Jika Anda memerlukan HTML akhir sebagai string atau ingin mengirimnya lewat HTTP tanpa menyentuh disk, ganti `MyHandler` dengan versi yang mengembalikan `MemoryStream` bersama: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Setelah `htmlDoc.Save(handler)`, Anda dapat membaca HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Menangani sumber daya besar dengan aman + +Saat menangani gambar atau PDF berukuran besar, hindari memuat seluruh file ke memori. Sebagai gantinya, kembalikan `FileStream` yang menulis langsung ke disk, seperti yang ditunjukkan sebelumnya. Ini mencegah `OutOfMemoryException` dalam skenario throughput tinggi. + +### Pertimbangan keamanan thread + +Instance `HTMLDocument` **tidak** thread‑safe. Jika Anda perlu memproses beberapa string HTML secara bersamaan, buat `HTMLDocument` dan `MyHandler` terpisah per thread, atau sinkronkan akses dengan `lock`. + +### Membuang (disposing) stream + +Baik `HTMLDocument.Save` maupun `ResourceHandler.HandleResource` dapat mengembalikan stream yang perlu dibuang. Pada contoh di atas, pustaka secara otomatis membuang stream setelah menulis. Jika Anda mengelola stream sendiri (mis., membuka `FileStream` sebelum memanggil `Save`), bungkus mereka dalam pernyataan `using`. + +## Ringkasan + +Panduan ini menunjukkan cara **load html string** ke dalam `HTMLDocument`, **create custom handler** untuk menentukan penyimpanan sumber daya, dan **how to save htmldocument** dengan **custom resource handling**. Sekarang Anda memiliki: + +1. Cara yang jelas untuk mengubah HTML mentah menjadi objek DOM. +2. Subclass `ResourceHandler` yang dapat digunakan kembali yang dapat menulis sumber daya ke memori, disk, atau penyimpanan cloud. +3. Program lengkap yang dapat dijalankan yang mendemonstrasikan seluruh alur kerja. + +## Langkah selanjutnya + +- Jelajahi override `ResourceHandler` lain seperti `HandleCss` atau `HandleFont` jika pustaka Anda menyediakannya. +- Gabungkan pendekatan ini dengan langkah konversi PDF untuk menghasilkan PDF dari HTML sambil mempertahankan kontrol penuh atas aset tersemat. +- Tinjau dokumentasi pustaka untuk opsi tambahan seperti *compression*, *caching*, atau penyimpanan *asynchronous*. + +Silakan bereksperimen dengan strategi penyimpanan yang berbeda, dan bagikan temuan Anda di komentar atau di komunitas pengembang favorit Anda. Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 fcf4daa304..021dae26e8 100644 --- a/html/italian/net/html-extensions-and-conversions/_index.md +++ b/html/italian/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML per .NET non è solo una libreria; è un punto di svolta nel mondo d ## Tutorial sulle estensioni e conversioni HTML ### [Convertire HTML in PDF in .NET con Aspose.HTML](./convert-html-to-pdf/) Converti HTML in PDF senza sforzo con Aspose.HTML per .NET. Segui la nostra guida passo dopo passo e libera la potenza della conversione da HTML a PDF. +### [Convertire HTML in PDF in C# – impostare lo stile del font programmaticamente](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Scopri come impostare lo stile del font durante la conversione da HTML a PDF in C# con Aspose.HTML. ### [Crea documento HTML con testo formattato ed esporta in PDF – Guida completa](./create-html-document-with-styled-text-and-export-to-pdf-full/) Impara a creare un documento HTML con testo stilizzato e a convertirlo in PDF usando Aspose.HTML per .NET, passo dopo passo. ### [Convertire EPUB in immagine in .NET con Aspose.HTML](./convert-epub-to-image/) diff --git a/html/italian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/italian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..f481a5ed59 --- /dev/null +++ b/html/italian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Converti HTML in PDF in C# con pieno controllo del rendering. Scopri + come impostare lo stile del carattere programmaticamente, abilitare l'antialiasing + e migliorare la chiarezza del testo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: it +lastmod: 2026-08-03 +og_description: Converti HTML in PDF in C# con opzioni dettagliate. Questa guida mostra + come impostare lo stile del carattere programmaticamente, abilitare l'antialiasing + e produrre PDF di alta qualità. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Converti HTML in PDF in C# – controllo completo del rendering +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Converti HTML in PDF in C# – imposta lo stile del carattere programmaticamente +url: /it/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertire HTML in PDF in C# – impostare lo stile del carattere programmaticamente + +Se hai bisogno di **convertire HTML in PDF** in un'applicazione .NET, questo tutorial ti guida attraverso una soluzione completa, pronta per la produzione. Vedrai come **impostare lo stile del carattere programmaticamente**, migliorare il rendering delle immagini e abilitare il hinting del testo—tutto senza uscire dal tuo codice C#. + +Convertire pagine web in PDF è una necessità comune per report, fatturazione e archiviazione. Questa guida copre tutto, dalla configurazione del progetto a un esempio completo e eseguibile. Alla fine dell'articolo potrai generare PDF che preservano layout, tipografia e fedeltà visiva. + +## Cosa imparerai + +* Come aggiungere il pacchetto NuGet necessario e importare i namespace. +* Come configurare `HtmlConversionOptions` per controllare il rendering. +* Come **impostare lo stile del carattere programmaticamente** usando i flag `WebFontStyle`. +* Come abilitare l'antialiasing per le immagini e il hinting per il testo. +* Come invocare la classe `Converter` per produrre il file PDF finale. + +Il tutorial presuppone che tu abbia Visual Studio 2022 (o successivo) e .NET 6 o versioni più recenti installate. Non è necessario alcun strumento aggiuntivo. + +## Prerequisiti + +| Requisito | Motivo | +|---|---| +| .NET 6 SDK or later | Fornisce il runtime per il progetto C#. | +| Visual Studio 2022 (or any IDE) | Consente una facile creazione e debug del progetto. | +| Internet access to restore NuGet packages | Necessario per scaricare la libreria di conversione. | +| A simple HTML file (`input.html`) | Funziona come documento sorgente per la conversione. | + +> **Suggerimento:** Mantieni il file HTML nella stessa cartella del progetto per evitare problemi legati ai percorsi. + +## Passo 1: Installa la libreria di conversione + +Il campione di codice utilizza la libreria **GroupDocs.Conversion for .NET**, che offre `HtmlConversionOptions` e una classe `Converter`. Installala tramite il NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Il pacchetto aggiunge i tipi necessari al tuo progetto e scarica tutte le dipendenze. + +## Passo 2: Crea un progetto console C# + +Apri un prompt dei comandi ed esegui: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Questo crea un'applicazione console minimale chiamata `HtmlToPdfDemo`. Apri il file `Program.cs` generato; sostituirai il suo contenuto con l'esempio completo in seguito. + +## Passo 3: Configura le opzioni di conversione – imposta lo stile del carattere programmaticamente + +La classe `HtmlConversionOptions` ti consente di regolare finemente come il motore HTML renderizza la pagina. Per **impostare lo stile del carattere programmaticamente**, combina i valori dell'enumerazione `WebFontStyle` usando un OR bitwise: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Perché è importante:** +* `WebFontStyle.Bold | WebFontStyle.Italic` indica al renderer di applicare entrambi gli stili a qualsiasi testo che utilizza il font predefinito. +* L'antialiasing riduce i bordi frastagliati delle immagini raster, specialmente durante lo scaling. +* Il hinting allinea i contorni dei glifi alla griglia dei pixel, migliorando la leggibilità su schermi a bassa risoluzione e nel PDF risultante. + +## Passo 4: Esegui la conversione + +Con le opzioni pronte, chiama la classe `Converter`. Il metodo `Convert` accetta tre argomenti: il percorso del file HTML sorgente, il percorso del file PDF di destinazione e l'oggetto delle opzioni. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Il metodo viene eseguito in modo sincrono e genera un'eccezione se il file sorgente non può essere letto o se il percorso di output è non valido. Avvolgi la chiamata in un blocco try‑catch per il codice di produzione. + +## Passo 5: Verifica il risultato + +Dopo che il programma termina, apri `output.pdf` con qualsiasi visualizzatore PDF. Dovresti vedere: + +* Testo renderizzato in **grassetto e corsivo** (anche se l'HTML originale non specificava quegli stili). +* Le immagini appaiono più fluide grazie all'antialiasing. +* La chiarezza del testo migliorata dal hinting, specialmente per dimensioni di font ridotte. + +Se il PDF non riflette gli stili attesi, verifica che il file HTML faccia riferimento a un font web‑safe o includa una regola `@font-face` che il convertitore possa caricare. + +## Esempio completo e eseguibile + +Di seguito trovi un programma autonomo che incorpora tutti i passaggi precedenti. Copia il codice in `Program.cs`, posiziona un file `input.html` accanto e esegui `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Output console previsto** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Apri il PDF generato per confermare gli stili applicati. + +## Gestione dei casi limite comuni + +| Situazione | Approccio consigliato | +|---|---| +| **CSS o font esterni** | Posiziona i file CSS e le risorse dei font nella stessa cartella di `input.html` o riferiscili con URL assoluti raggiungibili dalla macchina che esegue la conversione. | +| **Documenti HTML di grandi dimensioni** | Aumenta il limite di memoria predefinito modificando `ConversionConfig` se incontri `OutOfMemoryException`. | +| **Contenuto dinamico (JavaScript)** | La libreria non esegue JavaScript. Pre‑renderizza le parti dinamiche lato server o utilizza un browser headless per produrre uno snapshot HTML statico prima della conversione. | +| **Caratteri Unicode non visualizzati** | Assicurati che l'HTML dichiari `` e che i font sorgente contengano i glifi richiesti. | +| **Dimensione pagina errata** | Imposta `conversionOptions.PageSize = PageSize.A4` (o un altro valore enum) per garantire dimensioni coerenti. | + +## Suggerimenti sulle prestazioni + +* Riutilizza una singola istanza di `Converter` quando converti molti file; riduce l'overhead di avvio. +* Disabilita le funzionalità di rendering non necessarie (ad esempio `EnableHyperlinks`) se non ti servono, accelerando l'elaborazione. +* Scrivi il PDF su uno stream di memoria quando devi inviarlo direttamente via HTTP invece di scriverlo su disco. + +## Passi successivi + +Ora che puoi **convertire HTML in PDF** con impostazioni di font personalizzate, esplora questi argomenti correlati: + +- **Imposta i margini della pagina programmaticamente** – regola `conversionOptions.Margin` per controllare lo spazio bianco. +- **Aggiungi filigrane** – utilizza `PdfConversionOptions` per sovrapporre testo o immagini. +- **Conversione batch** – itera su una collezione di file HTML e riutilizza lo stesso oggetto delle opzioni. + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Convertire HTML in PDF in .NET con Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Creare documento HTML con testo formattato ed esportare in PDF – Guida completa](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convertire SVG in PDF in .NET con Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/italian/net/working-with-html-documents/_index.md b/html/italian/net/working-with-html-documents/_index.md index 0d466ec954..be2cad122c 100644 --- a/html/italian/net/working-with-html-documents/_index.md +++ b/html/italian/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ Ora, portiamo le tue competenze al livello successivo. La modifica di documenti ### [Come salvare HTML in C# – Guida completa con un gestore di risorse personalizzato](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [Come rendere grassetto un'intestazione con CSS e C# – Guida completa passo‑passo](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Carica stringa HTML in C# – guida completa con gestore personalizzato](./load-html-string-in-c-complete-guide-with-custom-handler/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/italian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/italian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..53bc5bba2a --- /dev/null +++ b/html/italian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-08-03 +description: Carica una stringa HTML in C# e crea un gestore personalizzato per salvare + HTMLDocument. Scopri come salvare HTMLDocument con la gestione personalizzata delle + risorse. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: it +lastmod: 2026-08-03 +og_description: Carica una stringa HTML in C# e utilizza un gestore personalizzato + per salvare HTMLDocument. Questo tutorial mostra l'implementazione completa e le + migliori pratiche. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Carica stringa HTML in C# – guida passo‑passo per gestore personalizzato +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Carica stringa HTML in C# – guida completa con gestore personalizzato +url: /it/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Caricare una stringa HTML in C# – guida completa con gestore personalizzato + +Se hai bisogno di **caricare una stringa html** in un'applicazione C#, questo tutorial ti mostra esattamente come farlo e come **creare un gestore personalizzato** per la gestione delle risorse. Imparerai anche **come salvare htmldocument** usando **la gestione personalizzata delle risorse** in modo che ogni immagine, file CSS o script venga scritto esattamente dove desideri. + +Percorreremo l'intero processo—dalla conversione di una stringa HTML grezza in un oggetto `HTMLDocument`, all'implementazione di una sottoclasse `ResourceHandler` che controlla dove viene archiviata ogni risorsa. Alla fine avrai un esempio autonomo, pronto per la produzione, che potrai inserire in qualsiasi progetto .NET. + +## Prerequisiti + +- .NET 6.0 o versioni successive (il codice funziona anche su .NET Framework 4.7+) +- Un riferimento alla libreria che fornisce `HTMLDocument`, `ResourceHandler` e `ResourceInfo` (ad es., *HtmlRenderer* o una libreria simile HTML‑to‑PDF/DOM) +- Conoscenza di base della sintassi C# e degli stream + +> **Consiglio professionale:** Se usi Visual Studio, abilita i *nullable reference types* (`enable`) per rilevare i bug legati a null in anticipo. + +## Come caricare una stringa html in HTMLDocument + +Il primo passo è convertire una semplice stringa HTML in un oggetto `HTMLDocument` con cui la libreria può lavorare. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Perché è importante:** +`HTMLDocument` analizza il markup, costruisce un albero DOM e prepara le risorse (immagini, fogli di stile, ecc.) per il salvataggio successivo. Passare direttamente una stringa evita la necessità di file temporanei e mantiene il flusso di lavoro in memoria. + +### Trappole comuni + +| Problema | Perché accade | Soluzione | +|----------|----------------|----------| +| `htmlContent` è `null` | La variabile stringa non è mai stata assegnata. | Convalida prima di creare il documento: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Problemi di codifica | La libreria assume UTF‑8 ma la sorgente usa un'altra codifica. | Fornisci un overload esplicito di `Encoding` se disponibile, o assicurati che la stringa sia decodificata correttamente. | + +## Creare un gestore personalizzato per la gestione delle risorse + +Un **gestore di risorse personalizzato** ti dà il pieno controllo su come la libreria scrive le risorse esterne (immagini, CSS, font). Di seguito trovi un'implementazione minimale che scrive ogni risorsa in un `MemoryStream`. Puoi sostituire il corpo con logica di file‑system, storage cloud o qualsiasi altra destinazione. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Perché hai bisogno di un gestore personalizzato:** +Il gestore predefinito spesso scrive le risorse in una cartella temporanea, il che può essere indesiderato per motivi di sicurezza o prestazioni. Sovrascrivendo `HandleResource`, decidi esattamente dove e come viene memorizzato ogni byte. + +### Estendere il gestore per l'output su file + +Se preferisci scrivere ogni risorsa in una cartella specifica, modifica il metodo come segue: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Come salvare htmldocument usando il gestore personalizzato + +Ora che abbiamo sia l'istanza `HTMLDocument` sia l'implementazione `MyHandler`, possiamo persistere il documento. Il metodo `Save` accetta qualsiasi sottoclasse di `ResourceHandler`, permettendoti di inserire la tua logica personalizzata. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Quando `Save` viene eseguito, la libreria: + +1. Percorre l'albero DOM. +2. Rileva le risorse esterne (ad es., ``). +3. Chiama `handler.HandleResource` per ogni risorsa. +4. Scrive i dati della risorsa nello stream restituito. +5. Finalizza l'output HTML principale (spesso come file o stream separato). + +### Verifica del risultato + +Se hai usato la versione file‑system di `MyHandler`, dovresti vedere una cartella `output` con il file HTML originale e tutte le risorse referenziate. Per la versione `MemoryStream`, puoi ispezionare la lunghezza dello stream per confermare che i dati siano stati scritti: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Esempio completo, eseguibile + +Di seguito trovi un unico programma pronto per il copia‑incolla che dimostra l'intero flusso. Include la gestione degli errori, il rilascio degli stream e commenti che spiegano ogni passaggio. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Output previsto** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Dopo aver eseguito il programma, la directory `output` contiene: + +- `index.html` (il documento principale) +- Qualsiasi file aggiuntivo generato dalla libreria (ad es., immagini, CSS) + +## Varianti avanzate e casi limite + +### Salvataggio in un `MemoryStream` per l'elaborazione in memoria + +Se ti serve l'HTML finale come stringa o vuoi inviarlo via HTTP senza toccare il disco, sostituisci `MyHandler` con una versione che restituisce un `MemoryStream` condiviso: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Dopo `htmlDoc.Save(handler)`, puoi leggere l'HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Gestione sicura di risorse di grandi dimensioni + +Quando si gestiscono immagini o PDF di grandi dimensioni, evita di caricare l'intero file in memoria. Invece, restituisci un `FileStream` che scrive direttamente su disco, come mostrato in precedenza. Questo previene `OutOfMemoryException` in scenari ad alto throughput. + +### Considerazioni sulla thread‑safety + +Le istanze di `HTMLDocument` **non** sono thread‑safe. Se devi elaborare più stringhe HTML contemporaneamente, crea un `HTMLDocument` e un `MyHandler` separati per ogni thread, oppure sincronizza l'accesso con un `lock`. + +### Rilascio degli stream + +Sia `HTMLDocument.Save` sia `ResourceHandler.HandleResource` possono restituire stream che necessitano di essere rilasciati. Negli esempi sopra, la libreria rilascia automaticamente gli stream dopo la scrittura. Se gestisci gli stream manualmente (ad es., aprendo un `FileStream` prima di chiamare `Save`), avvolgili in istruzioni `using`. + +## Riepilogo + +Questa guida ti ha mostrato come **caricare una stringa html** in un `HTMLDocument`, **creare un gestore personalizzato** per determinare l'archiviazione delle risorse, e **come salvare htmldocument** con **la gestione personalizzata delle risorse**. Ora hai: + +1. Un modo chiaro per trasformare HTML grezzo in un oggetto DOM. +2. Una sottoclasse `ResourceHandler` riutilizzabile che può scrivere le risorse in memoria, su disco o su storage cloud. +3. Un programma completo, eseguibile, che dimostra l'intero flusso di lavoro. + +## Prossimi passi + +- Esplora altri override di `ResourceHandler` come `HandleCss` o `HandleFont` se la tua libreria li fornisce. +- Combina questo approccio con un passaggio di conversione PDF per generare PDF da HTML mantenendo il pieno controllo sugli asset incorporati. +- Rivedi la documentazione della libreria per opzioni aggiuntive come *compressione*, *caching* o salvataggio *asincrono*. + +Sentiti libero di sperimentare diverse strategie di archiviazione e condividi i tuoi risultati nei commenti o nella tua community di sviluppatori preferita. Buon coding! + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come salvare HTML in C# – Guida completa usando un gestore di risorse personalizzato](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Creare HTML da stringa in C# – Guida al gestore di risorse personalizzato](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Come comprimere HTML in C# – Salva HTML in Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 4110fd8e86..f2fdfa1083 100644 --- a/html/japanese/net/html-extensions-and-conversions/_index.md +++ b/html/japanese/net/html-extensions-and-conversions/_index.md @@ -46,6 +46,9 @@ Aspose.HTML for .NET を使用して、C# で HTML から PDF を作成する手 ### [スタイル付きテキストで HTML ドキュメントを作成し、PDF にエクスポートする – 完全ガイド](./create-html-document-with-styled-text-and-export-to-pdf-full/) Aspose.HTML for .NET を使用して、スタイル付きテキストを含む HTML ドキュメントを作成し、PDF にエクスポートする手順を詳しく解説します。 +### [C# で HTML を PDF に変換 – フォントスタイルをプログラムで設定する](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Aspose.HTML for .NET を使用し、C# でフォントスタイルをプログラム的に設定しながら HTML を PDF に変換する手順を解説します。 + ### [Aspose.HTML を使用して .NET で EPUB を画像に変換する](./convert-epub-to-image/) Aspose.HTML for .NET を使用して EPUB を画像に変換する方法を学びます。コード例とカスタマイズ可能なオプションを含むステップバイステップのチュートリアルです。 ### [Aspose.HTML を使用して .NET で EPUB を PDF に変換する](./convert-epub-to-pdf/) diff --git a/html/japanese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/japanese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..504cdc641e --- /dev/null +++ b/html/japanese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-08-03 +description: C#でHTMLをPDFに変換し、レンダリングを完全に制御します。フォントスタイルをプログラムで設定し、アンチエイリアスを有効にして、テキストの鮮明さを向上させる方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: ja +lastmod: 2026-08-03 +og_description: C#でHTMLをPDFに変換、詳細なオプション付き。このガイドでは、フォントスタイルをプログラムで設定し、アンチエイリアシングを有効にして、高品質なPDFを生成する方法を示します。 +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: C#でHTMLをPDFに変換 – 完全なレンダリング制御 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: C#でHTMLをPDFに変換 – フォントスタイルをプログラムで設定 +url: /ja/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で HTML を PDF に変換 – フォントスタイルをプログラムで設定 + +.NET アプリケーションで **HTML を PDF に変換** する必要がある場合、このチュートリアルでは完全な本番環境向けソリューションを順を追って説明します。**フォントスタイルをプログラムで設定**する方法、画像レンダリングの改善、テキストヒンティングの有効化を、C# のコードから離れることなく確認できます。 + +ウェブページを PDF に変換することは、レポート作成、請求書発行、アーカイブなどで一般的な要件です。本ガイドではプロジェクトのセットアップから実行可能な完全サンプルまでを網羅しています。記事の最後まで読むと、レイアウトやタイポグラフィ、ビジュアルの忠実度を保った PDF を生成できるようになります。 + +## 学べること + +* 必要な NuGet パッケージの追加方法と名前空間のインポート方法。 +* `HtmlConversionOptions` を設定してレンダリングを制御する方法。 +* `WebFontStyle` フラグを使用して **フォントスタイルをプログラムで設定**する方法。 +* 画像のアンチエイリアシングとテキストのヒンティングを有効にする方法。 +* `Converter` クラスを呼び出して最終的な PDF ファイルを生成する方法。 + +このチュートリアルは Visual Studio 2022(またはそれ以降)と .NET 6 以上がインストールされていることを前提としています。追加のツールは不要です。 + +## 前提条件 + +| Requirement | Reason | +|---|---| +| .NET 6 SDK or later | C# プロジェクトのランタイムを提供します。 | +| Visual Studio 2022 (or any IDE) | プロジェクト作成とデバッグを容易にします。 | +| Internet access to restore NuGet packages | 変換ライブラリをダウンロードするために必要です。 | +| A simple HTML file (`input.html`) | 変換元のドキュメントとして使用します。 | + +> **プロのコツ:** HTML ファイルはプロジェクトと同じフォルダーに置くと、パス関連の問題を回避できます。 + +## Step 1: Install the conversion library + +コードサンプルは **GroupDocs.Conversion for .NET** ライブラリを使用します。このライブラリは `HtmlConversionOptions` と `Converter` クラスを提供します。NuGet パッケージマネージャーからインストールしてください。 + +```bash +dotnet add package GroupDocs.Conversion +``` + +このパッケージにより、必要な型がプロジェクトに追加され、すべての依存関係が自動的に取得されます。 + +## Step 2: Create a C# console project + +コマンドプロンプトを開き、以下を実行します。 + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +これにより `HtmlToPdfDemo` という名前の最小限のコンソールアプリケーションが作成されます。生成された `Program.cs` ファイルを開き、後ほど全例に差し替えます。 + +## Step 3: Configure conversion options – set font style programmatically + +`HtmlConversionOptions` クラスを使うと、HTML エンジンがページをレンダリングする方法を細かく調整できます。**フォントスタイルをプログラムで設定**するには、`WebFontStyle` 列挙体の値をビット単位の OR で組み合わせます。 + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**この設定が重要な理由:** +* `WebFontStyle.Bold | WebFontStyle.Italic` は、デフォルトフォントを使用するすべてのテキストに対して太字と斜体の両方を適用するようレンダラに指示します。 +* アンチエイリアシングは、特に拡大縮小時にラスタ画像のギザギザを減らします。 +* ヒンティングは文字アウトラインをピクセルグリッドに合わせ、低解像度画面や生成された PDF での可読性を向上させます。 + +## Step 4: Perform the conversion + +オプションが準備できたら `Converter` クラスを呼び出します。`Convert` メソッドは 3 つの引数を受け取ります:ソース HTML ファイルのパス、出力 PDF ファイルのパス、そしてオプションオブジェクトです。 + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +このメソッドは同期的に実行され、ソースファイルが読めない、または出力パスが無効な場合は例外をスローします。実運用コードでは try‑catch でラップしてください。 + +## Step 5: Verify the result + +プログラムの実行が完了したら、任意の PDF ビューアで `output.pdf` を開きます。以下が確認できるはずです: + +* **太字かつ斜体**でテキストが描画されている(元の HTML がこれらのスタイルを指定していなくても)。 +* アンチエイリアシングにより画像が滑らかに表示される。 +* ヒンティングにより特に小さなフォントサイズで文字の鮮明さが向上している。 + +PDF に期待したスタイルが反映されていない場合は、HTML がウェブセーフフォントを参照しているか、コンバータが読み込める `@font-face` ルールが含まれているかを再確認してください。 + +## Full, runnable example + +以下はこれまでの手順をすべて組み込んだ自己完結型プログラムです。コードを `Program.cs` に貼り付け、同じディレクトリに `input.html` を配置して `dotnet run` を実行してください。 + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**期待されるコンソール出力** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +生成された PDF を開き、適用されたスタイルを確認します。 + +## Handling common edge cases + +| Situation | Recommended approach | +|---|---| +| **External CSS or fonts** | CSS ファイルとフォントリソースを `input.html` と同じフォルダーに置くか、変換マシンからアクセス可能な絶対 URL で参照してください。 | +| **Large HTML documents** | `OutOfMemoryException` が発生した場合は、`ConversionConfig` のデフォルトメモリ制限を増やしてください。 | +| **Dynamic content (JavaScript)** | ライブラリは JavaScript を実行しません。動的部分はサーバー側で事前にレンダリングするか、ヘッドレスブラウザで静的 HTML スナップショットを取得してから変換してください。 | +| **Unicode characters not displaying** | HTML が `` を宣言していること、使用するフォントに必要なグリフが含まれていることを確認してください。 | +| **Incorrect page size** | `conversionOptions.PageSize = PageSize.A4`(または他の enum 値)を設定して、サイズを統一してください。 | + +## Performance tips + +* 多数のファイルを変換する場合は `Converter` インスタンスを 1 つだけ再利用すると、起動オーバーヘッドが削減されます。 +* 必要のないレンダリング機能(例: `EnableHyperlinks`)は無効にすると処理速度が向上します。 +* PDF をディスクに書き出す代わりにメモリストリームに書き込めば、HTTP で直接送信するシナリオで便利です。 + +## Next steps + +カスタムフォント設定で **HTML を PDF に変換**できるようになったので、以下の関連トピックもぜひ試してみてください。 + +* **ページ余白をプログラムで設定** – `conversionOptions.Margin` を調整して余白を制御します。 +* **透かしの追加** – `PdfConversionOptions` を使用してテキストや画像の透かしをオーバーレイします。 +* **バッチ変換** – HTML ファイルのコレクションをループし、同じオプションオブジェクトを再利用します。 + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示した手法を基にした、密接に関連するトピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得したり、独自プロジェクトで代替実装アプローチを探求したりするのに役立ちます。 + +- [.NET で Aspose.HTML を使用して HTML を PDF に変換](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [スタイル付きテキストで HTML ドキュメントを作成し PDF にエクスポート – 完全ガイド](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [.NET で Aspose.HTML を使用して SVG を PDF に変換](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/japanese/net/working-with-html-documents/_index.md index b81b2fd9c9..f02f63a1a7 100644 --- a/html/japanese/net/working-with-html-documents/_index.md +++ b/html/japanese/net/working-with-html-documents/_index.md @@ -38,6 +38,7 @@ HTML ドキュメントは Web のバックボーンであり、それを効果 ### [カスタムリソースハンドラを使用した C# での HTML 保存完全ガイド](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [CSS と C# で見出しを太字にする方法 – 完全ステップバイステップガイド](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [カスタムハンドラを使用した C# で HTML 文字列をロードする完全ガイド](./load-html-string-in-c-complete-guide-with-custom-handler/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/japanese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/japanese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..0d440a10d2 --- /dev/null +++ b/html/japanese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,329 @@ +--- +category: general +date: 2026-08-03 +description: C#でHTML文字列を読み込み、HTMLDocumentを保存するカスタムハンドラを作成します。カスタムリソースハンドリングを用いたHTMLDocumentの保存方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: ja +lastmod: 2026-08-03 +og_description: C#でHTML文字列を読み込み、カスタムハンドラを使用してHTMLDocumentを保存します。このチュートリアルでは、完全な実装とベストプラクティスを示します。 +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: C#でHTML文字列を読み込む – ステップバイステップ カスタムハンドラガイド +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: C#でHTML文字列を読み込む – カスタムハンドラ付き完全ガイド +url: /ja/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でHTML文字列をロードする – カスタムハンドラを使用した完全ガイド + +C# アプリケーションで **HTML文字列をロード** する必要がある場合、このチュートリアルではその手順とリソース管理のための **カスタムハンドラの作成** 方法を正確に示します。また、**カスタムリソースハンドリング** を使用して **HTMLDocument を保存** する方法も学べます。これにより、画像、CSS ファイル、スクリプトがすべて希望の場所に書き込まれます。 + +生の HTML 文字列を `HTMLDocument` オブジェクトに変換し、各リソースの保存先を制御する `ResourceHandler` サブクラスを実装するまでの全プロセスを順を追って解説します。最後まで進めば、任意の .NET プロジェクトに組み込める自己完結型の本番向けサンプルが手に入ります。 + +## 前提条件 + +- .NET 6.0 以降(コードは .NET Framework 4.7+ でも動作します) +- `HTMLDocument`、`ResourceHandler`、`ResourceInfo` を提供するライブラリへの参照(例: *HtmlRenderer* や類似の HTML‑to‑PDF/DOM ライブラリ) +- C# の構文とストリームに関する基本知識 + +> **Pro tip:** Visual Studio を使用している場合は、*nullable reference types*(`enable`)を有効にして、null 関連のバグを早期に検出しましょう。 + +## HTML文字列をHTMLDocumentにロードする方法 + +最初のステップは、プレーンな HTML 文字列をライブラリが扱える `HTMLDocument` オブジェクトに変換することです。 + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**このステップが重要な理由:** +`HTMLDocument` はマークアップを解析し、DOM ツリーを構築し、後で保存するためのリソース(画像、スタイルシートなど)を準備します。文字列を直接渡すことで、一時ファイルが不要になり、ワークフローがメモリ上で完結します。 + +### よくある落とし穴 + +| 問題 | 発生理由 | 対策 | +|------|----------|------| +| `htmlContent` が `null` | 文字列変数が割り当てられていませんでした。 | ドキュメント作成前に検証してください: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| エンコーディングの問題 | ライブラリは UTF‑8 を想定していますが、ソースが別のエンコーディングを使用しています。 | 利用可能な場合は明示的な `Encoding` オーバーロードを提供するか、文字列が正しくデコードされていることを確認してください。 | + +## リソースハンドリング用カスタムハンドラの作成 + +**カスタムリソースハンドラ** を使用すると、ライブラリが外部リソース(画像、CSS、フォント)を書き込む方法を完全に制御できます。以下は各リソースを `MemoryStream` に書き込む最小実装です。ファイルシステム、クラウドストレージ、その他任意の保存先に置き換えることができます。 + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**カスタムハンドラが必要な理由:** +既定のハンドラはリソースを一時フォルダーに書き込むことが多く、セキュリティやパフォーマンス上の問題になることがあります。`HandleResource` をオーバーライドすることで、バイトデータの保存先と方法を正確に指定できます。 + +### ファイル出力向けにハンドラを拡張する + +各リソースを特定のフォルダーに書き込みたい場合は、以下のようにメソッドを修正します。 + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## カスタムハンドラを使用してHTMLDocumentを保存する方法 + +`HTMLDocument` インスタンスと `MyHandler` 実装が揃ったので、ドキュメントを永続化できます。`Save` メソッドは任意の `ResourceHandler` サブクラスを受け取り、カスタムロジックを差し込めます。 + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +`Save` が実行されると、ライブラリは次の処理を行います。 + +1. DOM ツリーを走査します。 +2. 外部リソースを検出します(例: ``)。 +3. 各リソースに対して `handler.HandleResource` を呼び出します。 +4. 返されたストリームにリソースデータを書き込みます。 +5. メインの HTML 出力を完了します(通常は別ファイルまたはストリームとして)。 + +### 結果の検証 + +ファイルシステム版の `MyHandler` を使用した場合、元の HTML ファイルと参照されたアセットが格納された `output` フォルダーが作成されます。`MemoryStream` 版の場合は、ストリーム長を確認してデータが書き込まれたことを検証できます。 + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## 完全な実行可能サンプル + +以下は、フロー全体を示すコピー&ペースト可能な単一プログラムです。エラーハンドリング、ストリームの破棄、各ステップの説明コメントが含まれています。 + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**期待される出力** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +プログラム実行後、`output` ディレクトリには次が含まれます。 + +- `index.html`(メインドキュメント) +- ライブラリが生成したその他のファイル(例: 画像、CSS) + +## 高度なバリエーションとエッジケース + +### `MemoryStream` に保存してインメモリ処理を行う + +最終的な HTML を文字列として取得したり、ディスクに触れずに HTTP で送信したりしたい場合は、`MyHandler` を共有 `MemoryStream` を返すバージョンに置き換えます。 + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +`htmlDoc.Save(handler)` 後に、HTML を次のように読み取れます。 + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### 大容量リソースを安全に扱う + +大きな画像や PDF を処理する際は、全体をメモリに読み込むのを避け、直接ディスクに書き込む `FileStream` を返すようにします。これにより、高スループットシナリオでの `OutOfMemoryException` を防げます。 + +### スレッド安全性の考慮 + +`HTMLDocument` インスタンスは **スレッドセーフではありません**。複数の HTML 文字列を同時に処理する必要がある場合は、スレッドごとに別々の `HTMLDocument` と `MyHandler` を作成するか、`lock` でアクセスを同期してください。 + +### ストリームの破棄 + +`HTMLDocument.Save` と `ResourceHandler.HandleResource` が返すストリームは、必要に応じて破棄する必要があります。上記例では、ライブラリが書き込み後に自動でストリームを破棄します。自前でストリームを開く(例: `FileStream`)場合は、`using` 文でラップしてください。 + +## まとめ + +このガイドでは、**HTML文字列を HTMLDocument にロード** し、**リソース保存先を制御するカスタムハンドラを作成** し、**カスタムリソースハンドリングで HTMLDocument を保存** する方法を示しました。これにより、以下が実現できます。 + +1. 生の HTML を DOM オブジェクトに変換する明確な手順。 +2. メモリ、ディスク、クラウドなど任意の場所にリソースを書き込める再利用可能な `ResourceHandler` サブクラス。 +3. 完全なワークフローを示す実行可能なサンプルプログラム。 + +## 次のステップ + +- ライブラリが提供している場合、`HandleCss` や `HandleFont` などの他の `ResourceHandler` オーバーライドを調査してください。 +- このアプローチを PDF 変換ステップと組み合わせ、HTML から PDF を生成しつつ埋め込みアセットを完全に制御できます。 +- ライブラリのドキュメントを確認し、*compression*、*caching*、*asynchronous* 保存などの追加オプションを検討してください。 + +さまざまな保存戦略を試し、コメントやお気に入りの開発者コミュニティで成果を共有してください。ハッピーコーディング! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を応用した関連トピックを扱っています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能を習得したり、代替実装アプローチを自分のプロジェクトで試したりするのに役立ちます。 + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 38fc3bd7e6..af8beb2fa8 100644 --- a/html/korean/net/html-extensions-and-conversions/_index.md +++ b/html/korean/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET은 단순한 라이브러리가 아니라 웹 개발의 세 ## HTML 확장 및 변환 튜토리얼 ### [Aspose.HTML을 사용하여 .NET에서 HTML을 PDF로 변환](./convert-html-to-pdf/) Aspose.HTML for .NET으로 HTML을 PDF로 손쉽게 변환하세요. 단계별 가이드를 따라 HTML-PDF 변환의 힘을 활용하세요. +### [C#에서 HTML을 PDF로 변환 – 프로그래밍으로 글꼴 스타일 설정](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +C# 코드에서 글꼴 스타일을 프로그래밍 방식으로 지정하여 HTML을 PDF로 변환하는 방법을 안내합니다. ### [HTML에서 PDF 만들기 – C# 단계별 가이드](./create-pdf-from-html-c-step-by-step-guide/) Aspose.HTML for .NET을 사용하여 C#에서 HTML을 PDF로 변환하는 단계별 가이드입니다. ### [Aspose.HTML을 사용하여 .NET에서 EPUB를 이미지로 변환](./convert-epub-to-image/) diff --git a/html/korean/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/korean/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..e14e917799 --- /dev/null +++ b/html/korean/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-08-03 +description: C#에서 전체 렌더링 제어와 함께 HTML을 PDF로 변환합니다. 프로그래밍 방식으로 글꼴 스타일을 설정하고, 안티앨리어싱을 + 활성화하며, 텍스트 선명도를 향상시키는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: ko +lastmod: 2026-08-03 +og_description: C#에서 상세 옵션으로 HTML을 PDF로 변환합니다. 이 가이드는 폰트 스타일을 프로그래밍 방식으로 설정하고, 안티앨리어싱을 + 활성화하며, 고품질 PDF를 생성하는 방법을 보여줍니다. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: C#에서 HTML을 PDF로 변환 – 전체 렌더링 제어 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: C#에서 HTML을 PDF로 변환 – 폰트 스타일을 프로그래밍 방식으로 설정 +url: /ko/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML을 PDF로 변환 – 폰트 스타일을 프로그래밍 방식으로 설정 + +.NET 애플리케이션에서 **HTML을 PDF로 변환**해야 한다면, 이 튜토리얼은 완전하고 프로덕션 준비된 솔루션을 단계별로 안내합니다. **폰트 스타일을 프로그래밍 방식으로 설정**하는 방법, 이미지 렌더링 개선, 텍스트 힌팅 활성화 등을 C# 코드를 떠나지 않고 수행하는 방법을 확인할 수 있습니다. + +웹 페이지를 PDF로 변환하는 것은 보고서, 청구서, 아카이브 등에서 흔히 요구되는 작업입니다. 이 가이드는 프로젝트 설정부터 전체 실행 가능한 예제까지 모든 과정을 다룹니다. 기사 끝까지 읽으면 레이아웃, 타이포그래피, 시각적 충실도를 유지하는 PDF를 생성할 수 있습니다. + +## 배울 내용 + +* 필수 NuGet 패키지를 추가하고 네임스페이스를 가져오는 방법. +* `HtmlConversionOptions`를 구성하여 렌더링을 제어하는 방법. +* `WebFontStyle` 플래그를 사용해 **폰트 스타일을 프로그래밍 방식으로 설정**하는 방법. +* 이미지에 대한 안티앨리어싱 및 텍스트에 대한 힌팅을 활성화하는 방법. +* `Converter` 클래스를 호출하여 최종 PDF 파일을 생성하는 방법. + +이 튜토리얼은 Visual Studio 2022(또는 그 이후 버전)와 .NET 6 이상이 설치되어 있다고 가정합니다. 추가 도구는 필요하지 않습니다. + +## 사전 요구 사항 + +| 요구 사항 | 이유 | +|---|---| +| .NET 6 SDK 이상 | C# 프로젝트에 대한 런타임을 제공합니다. | +| Visual Studio 2022 (또는 기타 IDE) | 프로젝트 생성 및 디버깅을 쉽게 할 수 있게 해줍니다. | +| NuGet 패키지 복원을 위한 인터넷 액세스 | 변환 라이브러리를 다운로드하는 데 필요합니다. | +| 간단한 HTML 파일 (`input.html`) | 변환을 위한 소스 문서 역할을 합니다. | + +> **전문가 팁:** 경로 관련 문제를 피하려면 HTML 파일을 프로젝트와 같은 폴더에 보관하세요. + +## 1단계: 변환 라이브러리 설치 + +코드 샘플은 **GroupDocs.Conversion for .NET** 라이브러리를 사용합니다. 이 라이브러리는 `HtmlConversionOptions`와 `Converter` 클래스를 제공합니다. NuGet 패키지 관리자를 통해 설치하세요: + +```bash +dotnet add package GroupDocs.Conversion +``` + +패키지는 프로젝트에 필요한 타입을 추가하고 모든 종속성을 가져옵니다. + +## 2단계: C# 콘솔 프로젝트 만들기 + +명령 프롬프트를 열고 다음을 실행합니다: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +이 명령은 `HtmlToPdfDemo`라는 최소 콘솔 애플리케이션을 생성합니다. 생성된 `Program.cs` 파일을 열고 나중에 전체 예제로 내용을 교체합니다. + +## 3단계: 변환 옵션 구성 – 폰트 스타일을 프로그래밍 방식으로 설정 + +`HtmlConversionOptions` 클래스는 HTML 엔진이 페이지를 렌더링하는 방식을 세밀하게 조정할 수 있게 해줍니다. **폰트 스타일을 프로그래밍 방식으로 설정**하려면 `WebFontStyle` 열거형 값을 비트 OR 연산자로 결합합니다: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**왜 중요한가:** +* `WebFontStyle.Bold | WebFontStyle.Italic`는 기본 폰트를 사용하는 모든 텍스트에 두 스타일을 모두 적용하도록 렌더러에 지시합니다. +* 안티앨리어싱은 특히 확대할 때 래스터 이미지의 거친 가장자리를 줄여줍니다. +* 힌팅은 글리프 윤곽을 픽셀 그리드에 맞추어 저해상도 화면 및 최종 PDF에서 가독성을 향상시킵니다. + +## 4단계: 변환 수행 + +옵션을 준비했으면 `Converter` 클래스를 호출합니다. `Convert` 메서드는 세 개의 인수를 받습니다: 소스 HTML 파일 경로, 대상 PDF 파일 경로, 옵션 객체. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +이 메서드는 동기적으로 실행되며 소스 파일을 읽을 수 없거나 출력 경로가 잘못된 경우 예외를 발생시킵니다. 프로덕션 코드에서는 try‑catch 블록으로 호출을 감싸세요. + +## 5단계: 결과 확인 + +프로그램이 끝난 후 `output.pdf`를 任意의 PDF 뷰어로 열어보세요. 다음과 같은 결과가 보여야 합니다: + +* 텍스트가 **굵게 및 기울임**으로 렌더링됩니다 (원본 HTML에 해당 스타일이 명시되지 않았더라도). +* 안티앨리어싱 덕분에 이미지가 더 부드럽게 표시됩니다. +* 힌팅으로 텍스트 선명도가 향상되어 특히 작은 폰트 크기에서 효과가 좋습니다. + +PDF에 기대한 스타일이 반영되지 않았다면 HTML 파일이 웹 안전 폰트를 참조하거나 변환기가 로드할 수 있는 `@font-face` 규칙을 포함하고 있는지 다시 확인하세요. + +## 전체 실행 가능한 예제 + +아래는 앞서 설명한 모든 단계를 포함한 독립 실행형 프로그램입니다. 코드를 `Program.cs`에 복사하고, 옆에 `input.html` 파일을 두고 `dotnet run`을 실행하세요. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**예상 콘솔 출력** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +생성된 PDF를 열어 적용된 스타일을 확인합니다. + +## 일반적인 엣지 케이스 처리 + +| 상황 | 권장 접근 방식 | +|---|---| +| **외부 CSS 또는 폰트** | CSS 파일 및 폰트 리소스를 `input.html`과 같은 폴더에 두거나, 변환을 실행하는 머신에서 접근 가능한 절대 URL로 참조하세요. | +| **대용량 HTML 문서** | `OutOfMemoryException`이 발생하면 `ConversionConfig`를 조정하여 기본 메모리 제한을 늘리세요. | +| **동적 콘텐츠 (JavaScript)** | 라이브러리는 JavaScript를 실행하지 않습니다. 동적 부분을 서버 측에서 미리 렌더링하거나, 헤드리스 브라우저를 사용해 정적 HTML 스냅샷을 만든 후 변환하세요. | +| **Unicode 문자 표시 안 됨** | HTML에 ``가 선언되어 있고, 사용된 폰트에 필요한 글리프가 포함되어 있는지 확인하세요. | +| **잘못된 페이지 크기** | `conversionOptions.PageSize = PageSize.A4`(또는 다른 enum 값)으로 일관된 크기를 강제하세요. | + +## 성능 팁 + +* 여러 파일을 변환할 때 단일 `Converter` 인스턴스를 재사용하면 시작 오버헤드가 감소합니다. +* 필요하지 않은 경우 불필요한 렌더링 기능(예: `EnableHyperlinks`)을 비활성화하면 처리 속도가 빨라집니다. +* 디스크에 쓰는 대신 HTTP로 직접 전송해야 할 경우 PDF를 메모리 스트림에 기록하세요. + +## 다음 단계 + +이제 **HTML을 PDF로 변환**하면서 사용자 지정 폰트 설정을 적용할 수 있으니, 다음 주제들을 살펴보세요: + +* **페이지 여백을 프로그래밍 방식으로 설정** – `conversionOptions.Margin`를 조정하여 여백을 제어합니다. +* **워터마크 추가** – `PdfConversionOptions`를 사용해 텍스트나 이미지를 오버레이합니다. +* **배치 변환** – HTML 파일 컬렉션을 순회하면서 동일한 옵션 객체를 재사용합니다. + +## 다음에 배워야 할 내용은? + +다음 튜토리얼은 이 가이드에서 다룬 기술을 기반으로 하며, 단계별 설명과 완전한 코드 예제를 포함하고 있어 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Aspose.HTML을 사용한 .NET에서 HTML을 PDF로 변환](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [스타일이 적용된 텍스트로 HTML 문서 만들고 PDF로 내보내기 – 전체 가이드](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Aspose.HTML을 사용한 .NET에서 SVG를 PDF로 변환](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/korean/net/working-with-html-documents/_index.md index 491b68f5a8..e1e4a14ac6 100644 --- a/html/korean/net/working-with-html-documents/_index.md +++ b/html/korean/net/working-with-html-documents/_index.md @@ -41,6 +41,8 @@ HTML 문서는 웹의 중추이며, 효과적으로 만들고 조작할 수 있 사용자 정의 리소스 핸들러를 사용해 C#에서 HTML을 저장하는 방법을 단계별로 안내합니다. ### [CSS와 C#로 제목을 굵게 만드는 방법 – 완전 단계별 가이드](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [C#에서 HTML 문자열 로드 – 사용자 정의 핸들러를 활용한 완전 가이드](./load-html-string-in-c-complete-guide-with-custom-handler/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/korean/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/korean/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..9834cf436d --- /dev/null +++ b/html/korean/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-03 +description: C#에서 HTML 문자열을 로드하고 HTMLDocument를 저장하기 위한 사용자 정의 핸들러를 생성합니다. 사용자 정의 리소스 + 처리를 통해 HTMLDocument를 저장하는 방법을 배웁니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: ko +lastmod: 2026-08-03 +og_description: C#에서 HTML 문자열을 로드하고 사용자 지정 핸들러를 사용하여 HTMLDocument를 저장합니다. 이 튜토리얼에서는 + 전체 구현과 모범 사례를 보여줍니다. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: C#에서 HTML 문자열 로드 – 단계별 맞춤 핸들러 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: C#에서 HTML 문자열 로드 – 맞춤 핸들러와 함께하는 완전 가이드 +url: /ko/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML 문자열 로드 – 커스텀 핸들러를 활용한 완전 가이드 + +C# 애플리케이션에서 **HTML 문자열을 로드**해야 한다면, 이 튜토리얼은 정확한 방법과 리소스 관리를 위한 **커스텀 핸들러 생성** 방법을 보여줍니다. 또한 **커스텀 리소스 핸들링**을 사용하여 **HTMLDocument를 저장**하는 방법을 배워, 모든 이미지, CSS 파일, 스크립트가 원하는 위치에 정확히 기록되도록 할 수 있습니다. + +우리는 전체 과정을 단계별로 살펴볼 것입니다—원시 HTML 문자열을 `HTMLDocument` 객체로 변환하는 것부터 각 리소스가 저장되는 위치를 제어하는 `ResourceHandler` 서브클래스를 구현하는 것까지. 최종적으로 .NET 프로젝트에 바로 삽입할 수 있는 자체 포함형, 프로덕션 준비된 예제를 얻게 됩니다. + +## 사전 요구 사항 + +- .NET 6.0 이상 (코드는 .NET Framework 4.7+에서도 작동합니다) +- `HTMLDocument`, `ResourceHandler`, `ResourceInfo`를 제공하는 라이브러리에 대한 참조 (예: *HtmlRenderer* 또는 유사한 HTML‑to‑PDF/DOM 라이브러리) +- C# 구문 및 스트림에 대한 기본 지식 + +> **팁:** Visual Studio를 사용하는 경우, *nullable reference types* (`enable`)를 활성화하여 null 관련 버그를 조기에 잡을 수 있습니다. + +## HTML 문자열을 HTMLDocument에 로드하는 방법 + +첫 번째 단계는 일반 HTML 문자열을 라이브러리가 사용할 수 있는 `HTMLDocument` 객체로 변환하는 것입니다. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**왜 중요한가:** +`HTMLDocument`는 마크업을 파싱하고 DOM 트리를 구축하며, 이후 저장을 위해 리소스(이미지, 스타일시트 등)를 준비합니다. 문자열을 직접 전달하면 임시 파일이 필요 없으며 워크플로우가 메모리 내에서 유지됩니다. + +### 흔히 발생하는 실수 + +| 문제 | 발생 원인 | 해결 방법 | +|------|----------|----------| +| `htmlContent`가 `null` | 문자열 변수가 할당되지 않았습니다. | 문서를 만들기 전에 검증하세요: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| 인코딩 문제 | 라이브러리는 UTF‑8을 가정하지만 소스는 다른 인코딩을 사용합니다. | 가능하면 명시적인 `Encoding` 오버로드를 제공하거나 문자열이 올바르게 디코딩되었는지 확인하세요. | + +## 리소스 핸들링을 위한 커스텀 핸들러 만들기 + +**커스텀 리소스 핸들러**는 라이브러리가 외부 리소스(이미지, CSS, 폰트)를 기록하는 방식을 완전히 제어할 수 있게 해줍니다. 아래는 각 리소스를 `MemoryStream`에 기록하는 최소 구현 예시입니다. 본문을 파일 시스템 로직, 클라우드 스토리지, 혹은 다른 목적지로 교체할 수 있습니다. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**커스텀 핸들러가 필요한 이유:** +기본 핸들러는 종종 리소스를 임시 폴더에 기록하는데, 이는 보안이나 성능 측면에서 바람직하지 않을 수 있습니다. `HandleResource`를 오버라이드하면 각 바이트가 정확히 어디에, 어떻게 저장될지 직접 결정할 수 있습니다. + +### 파일 출력용 핸들러 확장 + +각 리소스를 특정 폴더에 기록하고 싶다면, 메서드를 다음과 같이 수정하세요: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## 커스텀 핸들러를 사용하여 HTMLDocument 저장하기 + +이제 `HTMLDocument` 인스턴스와 `MyHandler` 구현이 모두 준비되었으니, 문서를 저장할 수 있습니다. `Save` 메서드는 任意의 `ResourceHandler` 서브클래스를 받아들여 커스텀 로직을 연결할 수 있게 합니다. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +`Save`가 실행되면 라이브러리는 다음을 수행합니다: + +1. DOM 트리를 순회합니다. +2. 외부 리소스를 감지합니다(예: ``). +3. 각 리소스에 대해 `handler.HandleResource`를 호출합니다. +4. 반환된 스트림에 리소스 데이터를 기록합니다. +5. 메인 HTML 출력을 최종화합니다(보통 별도 파일이나 스트림으로). + +### 결과 확인 + +`MyHandler`의 파일 시스템 버전을 사용했다면, 원본 HTML 파일과 참조된 모든 자산이 포함된 `output` 폴더가 생성됩니다. `MemoryStream` 버전의 경우, 스트림 길이를 확인하여 데이터가 기록됐는지 검증할 수 있습니다: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## 전체 실행 가능한 예제 + +아래는 전체 흐름을 보여주는 단일 복사‑붙여넣기 가능한 프로그램입니다. 오류 처리, 스트림 해제, 각 단계에 대한 설명 주석이 포함되어 있습니다. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**예상 출력** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +프로그램을 실행하면 `output` 디렉터리에 다음이 포함됩니다: + +- `index.html` (주 문서) +- 라이브러리가 생성한 추가 파일들(예: 이미지, CSS) + +## 고급 변형 및 엣지 케이스 + +### 메모리 내 처리를 위한 `MemoryStream`에 저장 + +최종 HTML을 문자열로 필요하거나 디스크에 쓰지 않고 HTTP로 전송하려면, `MyHandler`를 공유 `MemoryStream`을 반환하는 버전으로 교체하세요: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +`htmlDoc.Save(handler)` 호출 후, HTML을 읽을 수 있습니다: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### 대용량 리소스를 안전하게 처리하기 + +대용량 이미지나 PDF를 다룰 때는 전체 파일을 메모리에 로드하지 않도록 합니다. 대신 앞서 보여준 대로 디스크에 직접 쓰는 `FileStream`을 반환하세요. 이렇게 하면 고처리량 상황에서 `OutOfMemoryException`을 방지할 수 있습니다. + +### 스레드 안전성 고려 사항 + +`HTMLDocument` 인스턴스는 **스레드 안전하지** 않습니다. 여러 HTML 문자열을 동시에 처리해야 한다면, 스레드당 별도의 `HTMLDocument`와 `MyHandler`를 생성하거나 `lock`으로 접근을 동기화하세요. + +### 스트림 해제 + +`HTMLDocument.Save`와 `ResourceHandler.HandleResource`는 해제가 필요한 스트림을 반환할 수 있습니다. 위 예시에서는 라이브러리가 기록 후 자동으로 스트림을 해제합니다. 직접 스트림을 관리하는 경우(예: `Save` 호출 전에 `FileStream`을 열 경우) `using` 구문으로 감싸세요. + +## 요약 + +이 가이드는 **HTML 문자열을** `HTMLDocument`에 **로드**하고, 리소스 저장을 지정하는 **커스텀 핸들러를 생성**하며, **커스텀 리소스 핸들링**으로 **HTMLDocument를 저장**하는 방법을 보여줍니다. 이제 다음을 갖추었습니다: + +1. 원시 HTML을 DOM 객체로 변환하는 명확한 방법. +2. 메모리, 디스크, 클라우드 스토리지에 리소스를 기록할 수 있는 재사용 가능한 `ResourceHandler` 서브클래스. +3. 전체 워크플로우를 시연하는 완전한 실행 가능한 프로그램. + +## 다음 단계 + +- 라이브러리가 제공한다면 `HandleCss` 또는 `HandleFont`와 같은 다른 `ResourceHandler` 오버라이드를 탐색해 보세요. +- 이 방식을 PDF 변환 단계와 결합하여 HTML에서 PDF를 생성하면서 삽입된 자산에 대한 완전한 제어를 유지하세요. +- 라이브러리 문서를 검토하여 *compression*, *caching*, *asynchronous* 저장과 같은 추가 옵션을 확인하세요. + +다양한 저장 전략을 자유롭게 실험해 보고, 결과를 댓글이나 선호하는 개발자 커뮤니티에 공유하세요. 즐거운 코딩 되세요! + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료는 단계별 설명과 함께 완전한 동작 코드 예제를 제공하여 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하도록 돕습니다. + +- [C#에서 HTML 저장하기 – 커스텀 리소스 핸들러를 활용한 완전 가이드](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [C#에서 문자열로 HTML 만들기 – 커스텀 리소스 핸들러 가이드](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [C#에서 HTML 압축하기 – HTML을 Zip으로 저장](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 5b553b0026..5d02674126 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#. +### [Konwertuj HTML do PDF w C# – ustaw styl czcionki programowo](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Dowiedz się, jak programowo ustawić styl czcionki przy konwersji HTML do PDF w C# przy użyciu Aspose.HTML. ## Wniosek diff --git a/html/polish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/polish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..5d505f1b73 --- /dev/null +++ b/html/polish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Konwertuj HTML do PDF w C# z pełną kontrolą renderowania. Dowiedz się, + jak programowo ustawiać styl czcionki, włączać antyaliasing i poprawiać czytelność + tekstu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: pl +lastmod: 2026-08-03 +og_description: Konwertuj HTML na PDF w C# z szczegółowymi opcjami. Ten przewodnik + pokazuje, jak programowo ustawić styl czcionki, włączyć antyaliasing i tworzyć wysokiej + jakości pliki PDF. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Konwertuj HTML na PDF w C# – pełna kontrola renderowania +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Konwertuj HTML do PDF w C# – ustaw styl czcionki programowo +url: /pl/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwertuj HTML do PDF w C# – ustaw styl czcionki programowo + +Jeśli potrzebujesz **konwertować HTML do PDF** w aplikacji .NET, ten tutorial przeprowadzi Cię przez kompletną, gotową do produkcji rozwiązanie. Zobaczysz, jak **ustawić styl czcionki programowo**, poprawić renderowanie obrazów i włączyć hinting tekstu — wszystko bez opuszczania kodu C#. + +Konwertowanie stron internetowych do PDF jest powszechnym wymogiem w raportowaniu, fakturowaniu i archiwizacji. Ten przewodnik obejmuje wszystko, od konfiguracji projektu po pełny, działający przykład. Po przeczytaniu artykułu będziesz w stanie generować PDF‑y zachowujące układ, typografię i wierność wizualną. + +## Czego się nauczysz + +* Jak dodać wymaganą paczkę NuGet i zaimportować przestrzenie nazw. +* Jak skonfigurować `HtmlConversionOptions`, aby kontrolować renderowanie. +* Jak **ustawić styl czcionki programowo** przy użyciu flag `WebFontStyle`. +* Jak włączyć antyaliasing dla obrazów i hinting dla tekstu. +* Jak wywołać klasę `Converter`, aby uzyskać finalny plik PDF. + +Tutorial zakłada, że masz zainstalowane Visual Studio 2022 (lub nowsze) oraz .NET 6 lub nowszy. Nie jest wymagane dodatkowe oprogramowanie. + +## Wymagania wstępne + +| Wymaganie | Powód | +|---|---| +| .NET 6 SDK lub nowszy | Dostarcza środowisko uruchomieniowe dla projektu C#. | +| Visual Studio 2022 (lub dowolne IDE) | Umożliwia łatwe tworzenie projektu i debugowanie. | +| Dostęp do Internetu w celu przywrócenia pakietów NuGet | Potrzebny do pobrania biblioteki konwersji. | +| Prosty plik HTML (`input.html`) | Służy jako źródłowy dokument do konwersji. | + +> **Pro tip:** Trzymaj plik HTML w tym samym folderze co projekt, aby uniknąć problemów związanych ze ścieżkami. + +## Krok 1: Zainstaluj bibliotekę konwersji + +Przykład kodu używa biblioteki **GroupDocs.Conversion for .NET**, która oferuje `HtmlConversionOptions` oraz klasę `Converter`. Zainstaluj ją za pomocą Menedżera pakietów NuGet: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Pakiet dodaje niezbędne typy do Twojego projektu i pobiera wszystkie zależności. + +## Krok 2: Utwórz projekt konsolowy C# + +Otwórz wiersz poleceń i uruchom: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Tworzy to minimalną aplikację konsolową o nazwie `HtmlToPdfDemo`. Otwórz wygenerowany plik `Program.cs`; później zastąpisz jego zawartość pełnym przykładem. + +## Krok 3: Skonfiguruj opcje konwersji – ustaw styl czcionki programowo + +Klasa `HtmlConversionOptions` pozwala precyzyjnie dostroić sposób, w jaki silnik HTML renderuje stronę. Aby **ustawić styl czcionki programowo**, połącz wartości wyliczenia `WebFontStyle` przy użyciu operatora bitowego OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Dlaczego to ważne:** +* `WebFontStyle.Bold | WebFontStyle.Italic` instruuje renderer, aby zastosował oba style do dowolnego tekstu używającego domyślnej czcionki. +* Antyaliasing zmniejsza postrzępione krawędzie rastrowych obrazów, szczególnie przy skalowaniu. +* Hinting wyrównuje kontury glifów do siatki pikseli, poprawiając czytelność na ekranach o niskiej rozdzielczości oraz w wygenerowanym PDF‑ie. + +## Krok 4: Wykonaj konwersję + +Mając przygotowane opcje, wywołaj klasę `Converter`. Metoda `Convert` przyjmuje trzy argumenty: ścieżkę do pliku źródłowego HTML, ścieżkę docelowego pliku PDF oraz obiekt opcji. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Metoda działa synchronicznie i zgłasza wyjątek, jeśli nie można odczytać pliku źródłowego lub ścieżka wyjściowa jest nieprawidłowa. W kodzie produkcyjnym otocz wywołanie blokiem try‑catch. + +## Krok 5: Zweryfikuj wynik + +Po zakończeniu programu otwórz `output.pdf` w dowolnym przeglądarce PDF. Powinieneś zobaczyć: + +* Tekst renderowany w **pogrubieniu i kursywie** (nawet jeśli oryginalny HTML nie określał tych stylów). +* Obrazy wyglądające płynniej dzięki antyaliasingowi. +* Czytelność tekstu poprawioną przez hinting, szczególnie przy małych rozmiarach czcionki. + +Jeśli PDF nie odzwierciedla oczekiwanych stylów, sprawdź ponownie, czy plik HTML odwołuje się do czcionki web‑safe lub zawiera regułę `@font-face`, którą konwerter może załadować. + +## Pełny, działający przykład + +Poniżej znajduje się samodzielny program, który zawiera wszystkie poprzednie kroki. Skopiuj kod do `Program.cs`, umieść plik `input.html` obok niego i uruchom `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Oczekiwany wynik w konsoli** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Otwórz wygenerowany PDF, aby potwierdzić zastosowane style. + +## Obsługa typowych przypadków brzegowych + +| Sytuacja | Zalecane podejście | +|---|---| +| **Zewnętrzne CSS lub czcionki** | Umieść pliki CSS i zasoby czcionek w tym samym folderze co `input.html` lub odwołuj się do nich przy użyciu bezwzględnych URL‑ów dostępnych z maszyny wykonującej konwersję. | +| **Duże dokumenty HTML** | Zwiększ domyślny limit pamięci, modyfikując `ConversionConfig`, jeśli napotkasz `OutOfMemoryException`. | +| **Dynamiczna zawartość (JavaScript)** | Biblioteka nie wykonuje JavaScriptu. Wstępnie wyrenderuj dynamiczne części po stronie serwera lub użyj przeglądarki headless, aby uzyskać statyczny zrzut HTML przed konwersją. | +| **Znaki Unicode nie wyświetlają się** | Upewnij się, że HTML deklaruje `` oraz że używane czcionki zawierają wymagane glify. | +| **Nieprawidłowy rozmiar strony** | Ustaw `conversionOptions.PageSize = PageSize.A4` (lub inną wartość wyliczenia), aby wymusić spójne wymiary. | + +## Wskazówki dotyczące wydajności + +* Ponownie używaj jednej instancji `Converter` przy konwersji wielu plików; zmniejsza to narzut uruchomieniowy. +* Wyłącz niepotrzebne funkcje renderowania (np. `EnableHyperlinks`), jeśli ich nie potrzebujesz, co przyspiesza przetwarzanie. +* Zapisz PDF do strumienia pamięci, gdy musisz go wysłać bezpośrednio przez HTTP zamiast zapisywać na dysku. + +## Kolejne kroki + +Teraz, gdy możesz **konwertować HTML do PDF** z własnymi ustawieniami czcionki, poznaj powiązane tematy: + +* **Ustaw marginesy strony programowo** – dostosuj `conversionOptions.Margin`, aby kontrolować białe przestrzenie. +* **Dodaj znaki wodne** – użyj `PdfConversionOptions`, aby nałożyć tekst lub obrazy. +* **Konwersja wsadowa** – iteruj po kolekcji plików HTML i ponownie używaj tego samego obiektu opcji. + +## Co powinieneś się nauczyć dalej? + +Poniższe tutoriale obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z krok po kroku wyjaśnieniami, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Convert HTML to PDF in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convert SVG to PDF in .NET with Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/polish/net/working-with-html-documents/_index.md b/html/polish/net/working-with-html-documents/_index.md index ac233f79e1..63416cc7ac 100644 --- a/html/polish/net/working-with-html-documents/_index.md +++ b/html/polish/net/working-with-html-documents/_index.md @@ -43,6 +43,8 @@ Poznaj metodę zapisu HTML w C# z własnym obsługiwaczem zasobów, umożliwiaj Dowiedz się, jak użyć CSS i C# do pogrubienia nagłówka w HTML, krok po kroku, z praktycznymi przykładami. +### [Ładowanie ciągu HTML w C# – kompletny przewodnik z własnym obsługiwaczem](./load-html-string-in-c-complete-guide-with-custom-handler/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/polish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/polish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..c245288c1f --- /dev/null +++ b/html/polish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-03 +description: Wczytaj ciąg HTML w C# i utwórz własny handler do zapisu HTMLDocument. + Dowiedz się, jak zapisać HTMLDocument przy użyciu niestandardowej obsługi zasobów. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: pl +lastmod: 2026-08-03 +og_description: Wczytaj ciąg HTML w C# i użyj własnego handlera do zapisu HTMLDocument. + Ten samouczek pokazuje pełną implementację oraz najlepsze praktyki. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Ładowanie ciągu HTML w C# – przewodnik krok po kroku po własnym handlerze +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Wczytaj ciąg HTML w C# – kompletny przewodnik z niestandardowym handlerem +url: /pl/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ładowanie ciągu HTML w C# – kompletny przewodnik z własnym obsługiwaczem + +Jeśli potrzebujesz **załadować ciąg HTML** w aplikacji C#, ten tutorial pokaże Ci dokładnie, jak to zrobić oraz **utworzyć własny obsługiwacz** do zarządzania zasobami. Dowiesz się także, **jak zapisać htmldocument** przy użyciu **niestandardowego obsługiwania zasobów**, tak aby każdy obraz, plik CSS czy skrypt został zapisany dokładnie tam, gdzie tego potrzebujesz. + +Przejdziemy krok po kroku przez cały proces — od przekształcenia surowego ciągu HTML w obiekt `HTMLDocument`, po implementację podklasy `ResourceHandler`, która kontroluje, gdzie każdy zasób jest przechowywany. Na koniec będziesz mieć samodzielny, gotowy do produkcji przykład, który możesz wkleić do dowolnego projektu .NET. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (kod działa również na .NET Framework 4.7+) +- Odwołanie do biblioteki udostępniającej `HTMLDocument`, `ResourceHandler` i `ResourceInfo` (np. *HtmlRenderer* lub podobna biblioteka HTML‑to‑PDF/DOM) +- Podstawowa znajomość składni C# i strumieni + +> **Pro tip:** Jeśli używasz Visual Studio, włącz *nullable reference types* (`enable`), aby wcześnie wykrywać błędy związane z nullami. + +## Jak załadować ciąg HTML do HTMLDocument + +Pierwszym krokiem jest przekształcenie zwykłego ciągu HTML w obiekt `HTMLDocument`, z którym biblioteka może pracować. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Dlaczego to ważne:** +`HTMLDocument` parsuje znacznik, buduje drzewo DOM i przygotowuje zasoby (obrazy, arkusze stylów itp.) do późniejszego zapisu. Przekazanie ciągu bezpośrednio eliminuje potrzebę plików tymczasowych i utrzymuje cały przepływ w pamięci. + +### Typowe pułapki + +| Problem | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| `htmlContent` jest `null` | Zmienna nie została wcześniej przypisana. | Zweryfikuj przed utworzeniem dokumentu: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Problemy z kodowaniem | Biblioteka zakłada UTF‑8, a źródło używa innego kodowania. | Użyj przeciążenia z wyraźnym `Encoding`, jeśli jest dostępne, lub upewnij się, że ciąg jest poprawnie zdekodowany. | + +## Utwórz własny obsługiwacz do obsługi zasobów + +**Własny obsługiwacz zasobów** daje pełną kontrolę nad tym, jak biblioteka zapisuje zewnętrzne zasoby (obrazy, CSS, czcionki). Poniżej znajduje się minimalna implementacja, która zapisuje każdy zasób do `MemoryStream`. Możesz zamienić ciało metody na logikę zapisu do systemu plików, chmury lub innego docelowego miejsca. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Dlaczego potrzebujesz własnego obsługiwacza:** +Domyślny obsługiwacz często zapisuje zasoby w folderze tymczasowym, co może być niepożądane ze względów bezpieczeństwa lub wydajności. Przez nadpisanie `HandleResource` decydujesz dokładnie, gdzie i jak każdy bajt zostanie zapisany. + +### Rozszerzenie obsługiwacza o zapis do pliku + +Jeśli wolisz zapisywać każdy zasób w określonym folderze, zmodyfikuj metodę w następujący sposób: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Jak zapisać htmldocument przy użyciu własnego obsługiwacza + +Mając już zarówno instancję `HTMLDocument`, jak i implementację `MyHandler`, możemy utrwalić dokument. Metoda `Save` przyjmuje dowolną podklasę `ResourceHandler`, co pozwala podłączyć własną logikę. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Podczas wykonywania `Save` biblioteka: + +1. Przechodzi drzewo DOM. +2. Wykrywa zasoby zewnętrzne (np. ``). +3. Wywołuje `handler.HandleResource` dla każdego zasobu. +4. Zapisuje dane zasobu do zwróconego strumienia. +5. Finalizuje główny wynik HTML (często jako osobny plik lub strumień). + +### Weryfikacja wyniku + +Jeśli użyłeś wersji `MyHandler` zapisującej do systemu plików, powinien pojawić się folder `output` z oryginalnym plikiem HTML oraz wszystkimi powiązanymi zasobami. W wersji z `MemoryStream` możesz sprawdzić długość strumienia, aby potwierdzić, że dane zostały zapisane: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Pełny, gotowy do uruchomienia przykład + +Poniżej znajduje się pojedynczy program gotowy do skopiowania i wklejenia, demonstrujący cały przepływ. Zawiera obsługę błędów, prawidłowe zwalnianie strumieni oraz komentarze wyjaśniające każdy krok. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Oczekiwany wynik** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Po uruchomieniu programu w katalogu `output` znajdziesz: + +- `index.html` (główny dokument) +- Wszystkie dodatkowe pliki wygenerowane przez bibliotekę (np. obrazy, CSS) + +## Zaawansowane warianty i przypadki brzegowe + +### Zapis do `MemoryStream` w celu przetwarzania w pamięci + +Jeśli potrzebujesz finalnego HTML jako ciągu znaków lub chcesz go wysłać przez HTTP bez zapisu na dysk, zamień `MyHandler` na wersję zwracającą współdzielony `MemoryStream`: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Po wywołaniu `htmlDoc.Save(handler)` możesz odczytać HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Bezpieczne obsługiwanie dużych zasobów + +Przy dużych obrazach lub PDF‑ach unikaj ładowania całego pliku do pamięci. Zwróć `FileStream`, który zapisuje bezpośrednio na dysk, jak pokazano wcześniej. Zapobiega to `OutOfMemoryException` w scenariuszach o wysokim obciążeniu. + +### Rozważania dotyczące bezpieczeństwa wątków + +Instancje `HTMLDocument` **nie są** bezpieczne wątkowo. Jeśli musisz przetwarzać wiele ciągów HTML równocześnie, utwórz osobny `HTMLDocument` i `MyHandler` dla każdego wątku lub synchronizuj dostęp przy użyciu `lock`. + +### Zwalnianie strumieni + +Zarówno `HTMLDocument.Save`, jak i `ResourceHandler.HandleResource` mogą zwracać strumienie wymagające zwolnienia. W powyższych przykładach biblioteka automatycznie zamyka strumienie po zapisaniu. Jeśli sam zarządzasz strumieniami (np. otwierasz `FileStream` przed wywołaniem `Save`), owiń je w instrukcje `using`. + +## Podsumowanie + +Ten przewodnik pokazał, jak **załadować ciąg HTML** do `HTMLDocument`, **utworzyć własny obsługiwacz** określający miejsce przechowywania zasobów oraz **zapisać htmldocument** przy użyciu **niestandardowego obsługiwania zasobów**. Masz teraz: + +1. Jasny sposób na przekształcenie surowego HTML w obiekt DOM. +2. Wielokrotnego użytku podklasę `ResourceHandler`, zdolną zapisywać zasoby w pamięci, na dysku lub w chmurze. +3. Kompletny, uruchamialny program demonstrujący pełny przepływ pracy. + +## Kolejne kroki + +- Zbadaj inne nadpisania w `ResourceHandler`, takie jak `HandleCss` czy `HandleFont`, jeśli Twoja biblioteka je udostępnia. +- Połącz to podejście z krokiem konwersji do PDF, aby generować PDF‑y z HTML przy pełnej kontroli nad osadzonymi zasobami. +- Przejrzyj dokumentację biblioteki pod kątem dodatkowych opcji, takich jak *compression*, *caching* czy *asynchronous* saving. + +Śmiało eksperymentuj z różnymi strategiami przechowywania i podziel się swoimi wnioskami w komentarzach lub w ulubionej społeczności deweloperskiej. Szczęśliwego kodowania! + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu oraz szczegółowe wyjaśnienia, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Create HTML from String in C# – Custom Resource Handler Guide](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 8971d46a58..e2a6c04bdf 100644 --- a/html/portuguese/net/html-extensions-and-conversions/_index.md +++ b/html/portuguese/net/html-extensions-and-conversions/_index.md @@ -40,6 +40,9 @@ Aspose.HTML para .NET não é apenas uma biblioteca; é um divisor de águas no ### [Converter HTML para PDF no .NET com Aspose.HTML](./convert-html-to-pdf/) Converta HTML para PDF sem esforço com Aspose.HTML para .NET. Siga nosso guia passo a passo e libere o poder da conversão de HTML para PDF. +### [Converter HTML para PDF em C# – definir estilo de fonte programaticamente](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Aprenda a converter HTML para PDF em C# definindo estilos de fonte programaticamente com Aspose.HTML. + ### [Criar PDF a partir de HTML – Guia passo a passo em C#](./create-pdf-from-html-c-step-by-step-guide/) Aprenda a criar um PDF a partir de HTML usando C# com Aspose.HTML, seguindo um guia passo a passo. diff --git a/html/portuguese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/portuguese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..a3f1232bd1 --- /dev/null +++ b/html/portuguese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Converta HTML em PDF em C# com controle total de renderização. Aprenda + como definir o estilo da fonte programaticamente, habilitar o antialiasing e melhorar + a clareza do texto. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: pt +lastmod: 2026-08-03 +og_description: Converta HTML em PDF em C# com opções detalhadas. Este guia mostra + como definir o estilo da fonte programaticamente, habilitar antialiasing e produzir + PDFs de alta qualidade. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Converter HTML para PDF em C# – controle total de renderização +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Converter HTML para PDF em C# – definir estilo de fonte programaticamente +url: /pt/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter HTML para PDF em C# – definir estilo de fonte programaticamente + +Se você precisa **converter HTML para PDF** em uma aplicação .NET, este tutorial o guiará por uma solução completa e pronta para produção. Você verá como **definir o estilo de fonte programaticamente**, melhorar a renderização de imagens e habilitar o hinting de texto — tudo sem sair do seu código C#. + +Converter páginas da web em PDFs é uma necessidade comum para relatórios, faturamento e arquivamento. Este guia cobre tudo, desde a configuração do projeto até um exemplo completo e executável. Ao final do artigo, você poderá gerar PDFs que preservam layout, tipografia e fidelidade visual. + +## O que você aprenderá + +* Como adicionar o pacote NuGet necessário e importar namespaces. +* Como configurar `HtmlConversionOptions` para controlar a renderização. +* Como **definir o estilo de fonte programaticamente** usando os flags `WebFontStyle`. +* Como habilitar antialiasing para imagens e hinting para texto. +* Como invocar a classe `Converter` para produzir o arquivo PDF final. + +O tutorial pressupõe que você tem o Visual Studio 2022 (ou superior) e .NET 6 ou mais recente instalados. Nenhuma ferramenta adicional é necessária. + +## Pré‑requisitos + +| Requisito | Motivo | +|---|---| +| .NET 6 SDK ou superior | Fornece o runtime para o projeto C#. | +| Visual Studio 2022 (ou qualquer IDE) | Facilita a criação e depuração do projeto. | +| Acesso à Internet para restaurar pacotes NuGet | Necessário para baixar a biblioteca de conversão. | +| Um arquivo HTML simples (`input.html`) | Serve como documento fonte para a conversão. | + +> **Dica profissional:** Mantenha o arquivo HTML na mesma pasta do projeto para evitar problemas relacionados a caminhos. + +## Etapa 1: Instalar a biblioteca de conversão + +O exemplo de código usa a biblioteca **GroupDocs.Conversion for .NET**, que oferece `HtmlConversionOptions` e a classe `Converter`. Instale-a via NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +O pacote adiciona os tipos necessários ao seu projeto e traz todas as dependências. + +## Etapa 2: Criar um projeto console C# + +Abra um prompt de comando e execute: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Isso cria uma aplicação console mínima chamada `HtmlToPdfDemo`. Abra o arquivo `Program.cs` gerado; você substituirá seu conteúdo pelo exemplo completo mais adiante. + +## Etapa 3: Configurar opções de conversão – definir estilo de fonte programaticamente + +A classe `HtmlConversionOptions` permite ajustar finamente como o motor HTML renderiza a página. Para **definir o estilo de fonte programaticamente**, combine os valores da enumeração `WebFontStyle` usando o operador OR bit a bit: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Por que isso importa:** +* `WebFontStyle.Bold | WebFontStyle.Italic` indica ao renderizador que aplique ambos os estilos a qualquer texto que use a fonte padrão. +* Antialiasing reduz bordas serrilhadas em imagens raster, especialmente ao redimensionar. +* Hinting alinha os contornos dos glifos à grade de pixels, melhorando a legibilidade em telas de baixa resolução e no PDF resultante. + +## Etapa 4: Executar a conversão + +Com as opções configuradas, chame a classe `Converter`. O método `Convert` recebe três argumentos: o caminho do arquivo HTML de origem, o caminho do arquivo PDF de destino e o objeto de opções. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +O método é executado de forma síncrona e lança uma exceção se o arquivo de origem não puder ser lido ou se o caminho de saída for inválido. Envolva a chamada em um bloco try‑catch para código de produção. + +## Etapa 5: Verificar o resultado + +Depois que o programa terminar, abra `output.pdf` com qualquer visualizador de PDF. Você deverá ver: + +* Texto renderizado em **negrito e itálico** (mesmo que o HTML original não especificasse esses estilos). +* Imagens mais suaves graças ao antialiasing. +* Clareza de texto aprimorada pelo hinting, especialmente em tamanhos de fonte pequenos. + +Se o PDF não refletir os estilos esperados, verifique se o arquivo HTML referencia uma fonte segura para web ou inclui uma regra `@font-face` que o conversor possa carregar. + +## Exemplo completo e executável + +A seguir, um programa autocontido que incorpora todas as etapas anteriores. Copie o código para `Program.cs`, coloque um arquivo `input.html` ao lado dele e execute `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Saída esperada no console** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Abra o PDF gerado para confirmar os estilos aplicados. + +## Tratamento de casos de borda comuns + +| Situação | Abordagem recomendada | +|---|---| +| **CSS ou fontes externas** | Coloque arquivos CSS e recursos de fonte na mesma pasta que `input.html` ou referencie‑os com URLs absolutas acessíveis a partir da máquina que executa a conversão. | +| **Documentos HTML grandes** | Aumente o limite de memória padrão ajustando `ConversionConfig` se encontrar `OutOfMemoryException`. | +| **Conteúdo dinâmico (JavaScript)** | A biblioteca não executa JavaScript. Pré‑renderize partes dinâmicas no servidor ou use um navegador headless para gerar um snapshot HTML estático antes da conversão. | +| **Caracteres Unicode não exibidos** | Garanta que o HTML declare `` e que as fontes de origem contenham os glifos necessários. | +| **Tamanho de página incorreto** | Defina `conversionOptions.PageSize = PageSize.A4` (ou outro valor da enum) para impor dimensões consistentes. | + +## Dicas de desempenho + +* Reutilize uma única instância de `Converter` ao converter muitos arquivos; isso reduz a sobrecarga de inicialização. +* Desative recursos de renderização desnecessários (por exemplo, `EnableHyperlinks`) se não precisar deles, o que acelera o processamento. +* Grave o PDF em um `MemoryStream` quando precisar enviá‑lo diretamente via HTTP em vez de gravar no disco. + +## Próximos passos + +Agora que você pode **converter HTML para PDF** com configurações de fonte personalizadas, explore os tópicos relacionados: + +* **Definir margens de página programaticamente** – ajuste `conversionOptions.Margin` para controlar o espaço em branco. +* **Adicionar marcas d'água** – use `PdfConversionOptions` para sobrepor texto ou imagens. +* **Conversão em lote** – percorra uma coleção de arquivos HTML e reutilize o mesmo objeto de opções. + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Convert HTML to PDF in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Create HTML Document with Styled Text and Export to PDF – Full Guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convert SVG to PDF in .NET with Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/portuguese/net/working-with-html-documents/_index.md b/html/portuguese/net/working-with-html-documents/_index.md index a8b4154dc2..c546ed9e51 100644 --- a/html/portuguese/net/working-with-html-documents/_index.md +++ b/html/portuguese/net/working-with-html-documents/_index.md @@ -37,8 +37,11 @@ Depois que você tiver compreendido o básico, vamos nos aprofundar no processo Agora, vamos levar suas habilidades para o próximo nível. Editar documentos HTML é uma tarefa comum para desenvolvedores web, e o Aspose.HTML simplifica esse processo significativamente. Nesta seção, abordaremos a criação, manipulação e estilo de documentos. Você descobrirá como aprimorar a aparência e a funcionalidade do seu conteúdo web, tornando-o envolvente e amigável ao usuário. ### [Como salvar HTML em C# – Guia completo usando um manipulador de recursos personalizado](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + ### [Como deixar o título em negrito com CSS e C# – Guia completo passo a passo](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [Como carregar string HTML em C# – Guia completo com manipulador personalizado](./load-html-string-in-c-complete-guide-with-custom-handler/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/portuguese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/portuguese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..ce21df9993 --- /dev/null +++ b/html/portuguese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-08-03 +description: Carregue uma string HTML em C# e crie um manipulador personalizado para + salvar HTMLDocument. Aprenda como salvar HTMLDocument com tratamento de recursos + personalizado. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: pt +lastmod: 2026-08-03 +og_description: Carregue uma string HTML em C# e use um manipulador personalizado + para salvar HTMLDocument. Este tutorial mostra a implementação completa e as melhores + práticas. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Carregar string HTML em C# – guia passo a passo de manipulador personalizado +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Carregar string HTML em C# – guia completo com manipulador personalizado +url: /pt/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Carregar string HTML em C# – guia completo com manipulador personalizado + +Se você precisa **carregar string HTML** em uma aplicação C#, este tutorial mostra exatamente como fazer isso e como **criar um manipulador personalizado** para gerenciamento de recursos. Você também aprenderá **como salvar htmldocument** usando **manipulação de recursos personalizada** para que cada imagem, arquivo CSS ou script seja gravado exatamente onde você desejar. + +Vamos percorrer todo o processo — desde transformar uma string HTML bruta em um objeto `HTMLDocument`, até implementar uma subclasse `ResourceHandler` que controla onde cada recurso é armazenado. Ao final, você terá um exemplo autônomo, pronto para produção, que pode ser inserido em qualquer projeto .NET. + +## Pré-requisitos + +- .NET 6.0 ou posterior (o código também funciona no .NET Framework 4.7+) +- Uma referência à biblioteca que fornece `HTMLDocument`, `ResourceHandler` e `ResourceInfo` (por exemplo, *HtmlRenderer* ou uma biblioteca similar de HTML‑para‑PDF/DOM) +- Conhecimento básico de sintaxe C# e streams + +> **Dica profissional:** Se você usa o Visual Studio, habilite *nullable reference types* (`enable`) para detectar erros relacionados a null mais cedo. + +## Como carregar string HTML em HTMLDocument + +O primeiro passo é converter uma string HTML simples em um objeto `HTMLDocument` que a biblioteca pode manipular. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Por que isso importa:** +`HTMLDocument` analisa a marcação, constrói uma árvore DOM e prepara recursos (imagens, folhas de estilo, etc.) para salvamento posterior. Passar uma string diretamente evita a necessidade de arquivos temporários e mantém o fluxo de trabalho na memória. + +### Armadilhas comuns + +| Problema | Por que acontece | Correção | +|----------|------------------|----------| +| `htmlContent` is `null` | A variável string nunca foi atribuída. | Valide antes de criar o documento: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | A biblioteca assume UTF‑8 mas a origem usa outra codificação. | Forneça uma sobrecarga explícita de `Encoding` se disponível, ou garanta que a string esteja decodificada corretamente. | + +## Criar manipulador personalizado para gerenciamento de recursos + +Um **custom resource handler** oferece controle total sobre como a biblioteca grava recursos externos (imagens, CSS, fontes). Abaixo está uma implementação mínima que grava cada recurso em um `MemoryStream`. Você pode substituir o corpo por lógica de sistema de arquivos, armazenamento em nuvem ou qualquer outro destino. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Por que você precisa de um manipulador personalizado:** +O manipulador padrão costuma gravar recursos em uma pasta temporária, o que pode ser indesejável por razões de segurança ou desempenho. Ao sobrescrever `HandleResource`, você decide exatamente onde e como cada byte é armazenado. + +### Estendendo o manipulador para saída em arquivo + +Se você prefere gravar cada recurso em uma pasta específica, modifique o método da seguinte forma: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Como salvar htmldocument usando o manipulador personalizado + +Agora que temos tanto a instância `HTMLDocument` quanto a implementação `MyHandler`, podemos persistir o documento. O método `Save` aceita qualquer subclasse de `ResourceHandler`, permitindo que você insira sua lógica personalizada. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Quando `Save` for executado, a biblioteca irá: + +1. Percorrer a árvore DOM. +2. Detectar recursos externos (por exemplo, ``). +3. Chamar `handler.HandleResource` para cada recurso. +4. Gravar os dados do recurso no stream retornado. +5. Finalizar a saída HTML principal (geralmente como um arquivo ou stream separado). + +### Verificando o resultado + +Se você usou a versão baseada em sistema de arquivos do `MyHandler`, deverá ver uma pasta `output` com o arquivo HTML original e quaisquer ativos referenciados. Para a versão `MemoryStream`, você pode inspecionar o comprimento do stream para confirmar que os dados foram gravados: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Exemplo completo e executável + +Abaixo está um programa único, pronto para copiar e colar, que demonstra todo o fluxo. Ele inclui tratamento de erros, descarte de streams e comentários que explicam cada passo. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Saída esperada** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Após executar o programa, o diretório `output` contém: + +- `index.html` (o documento principal) +- Qualquer arquivo adicional que a biblioteca gerou (por exemplo, imagens, CSS) + +## Variações avançadas e casos de borda + +### Salvando em um `MemoryStream` para processamento em memória + +Se você precisa do HTML final como uma string ou deseja enviá-lo via HTTP sem tocar no disco, substitua `MyHandler` por uma versão que retorne um `MemoryStream` compartilhado: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Após `htmlDoc.Save(handler)`, você pode ler o HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Manipulando recursos grandes com segurança + +Ao lidar com imagens ou PDFs grandes, evite carregar o arquivo inteiro na memória. Em vez disso, retorne um `FileStream` que grava diretamente no disco, como mostrado anteriormente. Isso impede `OutOfMemoryException` em cenários de alta taxa de transferência. + +### Considerações sobre segurança de thread + +Instâncias de `HTMLDocument` **não** são seguras para threads. Se precisar processar múltiplas strings HTML simultaneamente, crie um `HTMLDocument` e `MyHandler` separados por thread, ou sincronize o acesso com um `lock`. + +### Descartando streams + +Tanto `HTMLDocument.Save` quanto `ResourceHandler.HandleResource` podem retornar streams que precisam ser descartados. Nos exemplos acima, a biblioteca descarta os streams automaticamente após a gravação. Se você gerencia os streams manualmente (por exemplo, abrindo um `FileStream` antes de chamar `Save`), envolva-os em declarações `using`. + +## Resumo + +Este guia mostrou como **carregar string HTML** em um `HTMLDocument`, **criar manipulador personalizado** para definir o armazenamento de recursos, e **como salvar htmldocument** com **manipulação de recursos personalizada**. Agora você tem: + +1. Uma maneira clara de transformar HTML bruto em um objeto DOM. +2. Uma subclasse reutilizável de `ResourceHandler` que pode gravar recursos na memória, disco ou armazenamento em nuvem. +3. Um programa completo e executável que demonstra todo o fluxo de trabalho. + +## Próximos passos + +- Explore outras sobrescritas de `ResourceHandler` como `HandleCss` ou `HandleFont` se sua biblioteca as fornecer. +- Combine esta abordagem com uma etapa de conversão para PDF para gerar PDFs a partir de HTML mantendo controle total sobre os recursos incorporados. +- Revise a documentação da biblioteca para opções adicionais como *compression*, *caching* ou salvamento *asynchronous*. + +Sinta-se à vontade para experimentar diferentes estratégias de armazenamento e compartilhe suas descobertas nos comentários ou na sua comunidade de desenvolvedores favorita. Feliz codificação! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá-lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como salvar HTML em C# – Guia completo usando um manipulador de recursos personalizado](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Criar HTML a partir de string em C# – Guia de manipulador de recursos personalizado](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Como compactar HTML em C# – Salvar HTML em Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 00354e6733..9248f60b86 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 в PDF в C# – установить стиль шрифта программно](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Узнайте, как задать стиль шрифта при конвертации HTML в PDF в C# с помощью Aspose.HTML. ## Заключение diff --git a/html/russian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/russian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..8172fd2c6a --- /dev/null +++ b/html/russian/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-08-03 +description: Преобразуйте HTML в PDF на C# с полным контролем рендеринга. Узнайте, + как программно задавать стиль шрифта, включать сглаживание и улучшать чёткость текста. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: ru +lastmod: 2026-08-03 +og_description: Конвертировать HTML в PDF на C# с подробными настройками. Это руководство + показывает, как программно задать стиль шрифта, включить сглаживание и создавать + PDF высокого качества. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Преобразовать HTML в PDF на C# – полный контроль рендеринга +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Преобразовать HTML в PDF в C# – установить стиль шрифта программно +url: /ru/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Преобразование HTML в PDF на C# – программная установка стиля шрифта + +Если вам нужно **преобразовать HTML в PDF** в .NET‑приложении, этот учебник проведёт вас через полное, готовое к использованию в продакшене решение. Вы увидите, как **программно установить стиль шрифта**, улучшить рендеринг изображений и включить подсказки текста — всё без выхода из вашего кода C#. + +Преобразование веб‑страниц в PDF — распространённая потребность для отчётности, выставления счетов и архивирования. Это руководство охватывает всё от настройки проекта до полного, исполняемого примера. К концу статьи вы сможете генерировать PDF, сохраняющие макет, типографику и визуальную точность. + +## Что вы узнаете + +* Как добавить необходимый пакет NuGet и импортировать пространства имён. +* Как настроить `HtmlConversionOptions` для управления рендерингом. +* Как **программно установить стиль шрифта** с помощью флагов `WebFontStyle`. +* Как включить сглаживание (antialiasing) для изображений и подсказки (hinting) для текста. +* Как вызвать класс `Converter` для создания окончательного PDF‑файла. + +В руководстве предполагается, что у вас установлен Visual Studio 2022 (или новее) и .NET 6 или более новая версия. Дополнительные инструменты не требуются. + +## Требования + +| Требование | Причина | +|---|---| +| .NET 6 SDK или новее | Обеспечивает среду выполнения для проекта C#. | +| Visual Studio 2022 (или любой IDE) | Обеспечивает простое создание проекта и отладку. | +| Доступ в Интернет для восстановления пакетов NuGet | Необходим для загрузки библиотеки конвертации. | +| Простой HTML‑файл (`input.html`) | Служит исходным документом для конвертации. | + +> **Совет:** Держите HTML‑файл в той же папке, что и проект, чтобы избежать проблем, связанных с путями. + +## Шаг 1: Установите библиотеку конвертации + +В примере кода используется библиотека **GroupDocs.Conversion for .NET**, которая предоставляет `HtmlConversionOptions` и класс `Converter`. Установите её через NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Пакет добавляет необходимые типы в ваш проект и подтягивает все зависимости. + +## Шаг 2: Создайте консольный проект C# + +Откройте командную строку и выполните: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Это создаст минимальное консольное приложение с именем `HtmlToPdfDemo`. Откройте сгенерированный файл `Program.cs`; позже вы замените его содержимое полным примером. + +## Шаг 3: Настройте параметры конвертации – программно установите стиль шрифта + +`HtmlConversionOptions` позволяет точно настроить, как HTML‑движок рендерит страницу. Чтобы **программно установить стиль шрифта**, объедините значения перечисления `WebFontStyle` с помощью побитового ИЛИ: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Почему это важно:** +* `WebFontStyle.Bold | WebFontStyle.Italic` указывает рендереру применять оба стиля к любому тексту, использующему шрифт по умолчанию. +* Сглаживание (antialiasing) уменьшает зубчатость растровых изображений, особенно при масштабировании. +* Подсказки (hinting) выравнивают контуры глифов по пиксельной сетке, улучшая читаемость на экранах с низким разрешением и в получаемом PDF. + +## Шаг 4: Выполните конвертацию + +После подготовки параметров вызовите класс `Converter`. Метод `Convert` принимает три аргумента: путь к исходному HTML‑файлу, путь к целевому PDF‑файлу и объект параметров. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Метод выполняется синхронно и бросает исключение, если исходный файл нельзя прочитать или путь вывода недействителен. Оберните вызов в блок try‑catch для продакшн‑кода. + +## Шаг 5: Проверьте результат + +После завершения программы откройте `output.pdf` в любом PDF‑просмотрщике. Вы должны увидеть: + +* Текст, отрендеренный в **жирном и курсивном** виде (даже если оригинальный HTML не указывал эти стили). +* Изображения выглядят более плавными благодаря сглаживанию. +* Чёткость текста улучшена подсказками, особенно для небольших размеров шрифта. + +Если PDF не отображает ожидаемые стили, дважды проверьте, что HTML‑файл ссылается на веб‑безопасный шрифт или включает правило `@font-face`, которое конвертер может загрузить. + +## Полный, исполняемый пример + +Ниже представлена автономная программа, включающая все предыдущие шаги. Скопируйте код в `Program.cs`, разместите файл `input.html` рядом с ним и выполните `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Ожидаемый вывод в консоль** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Откройте сгенерированный PDF, чтобы подтвердить применённые стили. + +## Обработка распространённых граничных случаев + +| Ситуация | Рекомендуемый подход | +|---|---| +| **Внешний CSS или шрифты** | Разместите файлы CSS и ресурсы шрифтов в той же папке, что и `input.html`, или указывайте их абсолютными URL, доступными с машины, где происходит конвертация. | +| **Большие HTML‑документы** | Увеличьте предельный объём памяти по умолчанию, изменив `ConversionConfig`, если столкнётесь с `OutOfMemoryException`. | +| **Динамический контент (JavaScript)** | Библиотека не исполняет JavaScript. Предварительно отрендерите динамические части на сервере или используйте безголовый браузер для создания статического HTML‑снимка перед конвертацией. | +| **Unicode‑символы не отображаются** | Убедитесь, что HTML содержит `` и что исходные шрифты включают необходимые глифы. | +| **Неправильный размер страницы** | Установите `conversionOptions.PageSize = PageSize.A4` (или другое значение перечисления), чтобы обеспечить согласованные размеры. | + +## Советы по производительности + +* Переиспользуйте один экземпляр `Converter` при конвертации множества файлов; это уменьшает накладные расходы на запуск. +* Отключайте ненужные функции рендеринга (например, `EnableHyperlinks`), если они не требуются, что ускоряет обработку. +* Записывайте PDF в поток памяти, когда нужно отправить его напрямую по HTTP, вместо записи на диск. + +## Следующие шаги + +Теперь, когда вы можете **преобразовать HTML в PDF** с пользовательскими настройками шрифта, изучите эти связанные темы: + +- [Преобразовать HTML в PDF в .NET с помощью Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Создать HTML‑документ со стилизованным текстом и экспортировать в PDF – Полное руководство](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Преобразовать SVG в PDF в .NET с помощью Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/russian/net/working-with-html-documents/_index.md index 843e2ebedf..6b728abed6 100644 --- a/html/russian/net/working-with-html-documents/_index.md +++ b/html/russian/net/working-with-html-documents/_index.md @@ -36,6 +36,8 @@ HTML-документы являются основой Интернета, и Теперь давайте поднимем ваши навыки на новый уровень. Редактирование HTML-документов — обычная задача для веб-разработчиков, и Aspose.HTML значительно упрощает этот процесс. В этом разделе мы рассмотрим создание, обработку и стилизацию документов. Вы узнаете, как улучшить внешний вид и функциональность вашего веб-контента, сделав его привлекательным и удобным для пользователя. +### [Как загрузить HTML-строку в C# – полное руководство с пользовательским обработчиком](./load-html-string-in-c-complete-guide-with-custom-handler/) + ### [Как сохранить HTML в C# – Полное руководство с использованием пользовательского обработчика ресурсов](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [Как сделать заголовок жирным с помощью CSS и C# – Полное пошаговое руководство](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) diff --git a/html/russian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/russian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..2bf431c8d2 --- /dev/null +++ b/html/russian/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,333 @@ +--- +category: general +date: 2026-08-03 +description: Загрузить строку HTML в C# и создать пользовательский обработчик для + сохранения HTMLDocument. Узнайте, как сохранять HTMLDocument с пользовательской + обработкой ресурсов. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: ru +lastmod: 2026-08-03 +og_description: Загрузите строку HTML в C# и используйте пользовательский обработчик + для сохранения HTMLDocument. Этот учебник демонстрирует полную реализацию и лучшие + практики. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Загрузка HTML‑строки в C# – пошаговое руководство по пользовательскому обработчику +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Загрузка HTML‑строки в C# — полное руководство с пользовательским обработчиком +url: /ru/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Загрузка html-строки в C# – полное руководство с пользовательским обработчиком + +Если вам нужно **загрузить html-строку** в приложении C#, это руководство покажет, как это сделать, и как **создать пользовательский обработчик** для управления ресурсами. Вы также узнаете, **как сохранить htmldocument** с использованием **пользовательской обработки ресурсов**, чтобы каждое изображение, CSS‑файл или скрипт были записаны точно там, где вы хотите. + +Мы пройдем весь процесс — от преобразования сырой HTML‑строки в объект `HTMLDocument` до реализации подкласса `ResourceHandler`, который контролирует, где хранится каждый ресурс. К концу вы получите автономный, готовый к использованию в продакшене пример, который можно добавить в любой проект .NET. + +## Требования + +- .NET 6.0 или новее (код также работает на .NET Framework 4.7+) +- Ссылка на библиотеку, предоставляющую `HTMLDocument`, `ResourceHandler` и `ResourceInfo` (например, *HtmlRenderer* или аналогичную библиотеку HTML‑to‑PDF/DOM) +- Базовые знания синтаксиса C# и потоков + +> **Pro tip:** Если вы используете Visual Studio, включите *nullable reference types* (`enable`), чтобы раннее обнаруживать ошибки, связанные с null. + +## Как загрузить html-строку в HTMLDocument + +Первый шаг — преобразовать обычную HTML‑строку в объект `HTMLDocument`, с которым может работать библиотека. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Почему это важно:** +`HTMLDocument` разбирает разметку, строит дерево DOM и подготавливает ресурсы (изображения, таблицы стилей и т.д.) для последующего сохранения. Передача строки напрямую избавляет от необходимости во временных файлах и сохраняет процесс в памяти. + +### Распространённые подводные камни + +| Проблема | Почему происходит | Исправление | +|----------|-------------------|-------------| +| `htmlContent` is `null` | Переменная строки никогда не была присвоена. | Проверьте перед созданием документа: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | Библиотека предполагает UTF‑8, но источник использует другую кодировку. | Укажите явный перегрузку с `Encoding`, если она доступна, или убедитесь, что строка правильно декодирована. | + +## Создание пользовательского обработчика для управления ресурсами + +**Пользовательский обработчик ресурсов** предоставляет полный контроль над тем, как библиотека записывает внешние ресурсы (изображения, CSS, шрифты). Ниже представлена минимальная реализация, которая записывает каждый ресурс в `MemoryStream`. Вы можете заменить тело логикой файловой системы, облачным хранилищем или любой другой целью. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Почему нужен пользовательский обработчик:** +Стандартный обработчик часто записывает ресурсы во временную папку, что может быть нежелательно по соображениям безопасности или производительности. Переопределяя `HandleResource`, вы решаете, где и как хранить каждый байт. + +### Расширение обработчика для вывода в файл + +Если вы предпочитаете записывать каждый ресурс в определённую папку, измените метод следующим образом: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Как сохранить htmldocument с использованием пользовательского обработчика + +Теперь, когда у нас есть экземпляр `HTMLDocument` и реализация `MyHandler`, мы можем сохранить документ. Метод `Save` принимает любой подкласс `ResourceHandler`, позволяя подключить вашу пользовательскую логику. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +When `Save` runs, the library will: + +1. Пройти дерево DOM. +2. Обнаружить внешние ресурсы (например, ``). +3. Вызвать `handler.HandleResource` для каждого ресурса. +4. Записать данные ресурса в возвращённый поток. +5. Завершить вывод основного HTML (часто как отдельный файл или поток). + +### Проверка результата + +Если вы использовали файловую версию `MyHandler`, вы должны увидеть папку `output` с оригинальным HTML‑файлом и всеми связанными ресурсами. Для версии с `MemoryStream` вы можете проверить длину потока, чтобы убедиться, что данные записаны: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Полный, готовый к запуску пример + +Ниже представлен единый готовый к копированию и вставке пример программы, демонстрирующий весь процесс. Он включает обработку ошибок, освобождение потоков и комментарии, объясняющие каждый шаг. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Ожидаемый вывод** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +После запуска программы в каталоге `output` будет: + +- `index.html` (основной документ) +- Любые дополнительные файлы, сгенерированные библиотекой (например, изображения, CSS) + +## Расширенные варианты и граничные случаи + +### Сохранение в `MemoryStream` для обработки в памяти + +Если вам нужен окончательный HTML в виде строки или вы хотите отправить его по HTTP без записи на диск, замените `MyHandler` на версию, возвращающую общий `MemoryStream`: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +После `htmlDoc.Save(handler)` вы можете прочитать HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Безопасная обработка больших ресурсов + +При работе с большими изображениями или PDF‑файлами избегайте загрузки всего файла в память. Вместо этого возвращайте `FileStream`, который записывает напрямую на диск, как показано выше. Это предотвращает `OutOfMemoryException` в сценариях с высокой нагрузкой. + +### Соображения по потокобезопасности + +Экземпляры `HTMLDocument` **не** являются потокобезопасными. Если необходимо обрабатывать несколько HTML‑строк одновременно, создавайте отдельный `HTMLDocument` и `MyHandler` для каждого потока или синхронизируйте доступ с помощью `lock`. + +### Освобождение потоков + +И `HTMLDocument.Save`, и `ResourceHandler.HandleResource` могут возвращать потоки, требующие освобождения. В приведённых выше примерах библиотека автоматически освобождает потоки после записи. Если вы управляете потоками самостоятельно (например, открываете `FileStream` перед вызовом `Save`), оберните их в конструкции `using`. + +## Итоги + +В этом руководстве показано, как **загрузить html-строку** в `HTMLDocument`, **создать пользовательский обработчик** для управления хранением ресурсов и **как сохранить htmldocument** с **пользовательской обработкой ресурсов**. Теперь у вас есть: + +1. Чёткий способ преобразовать сырой HTML в объект DOM. +2. Переиспользуемый подкласс `ResourceHandler`, который может записывать ресурсы в память, на диск или в облачное хранилище. +3. Полная, готовая к запуску программа, демонстрирующая весь процесс. + +## Следующие шаги + +- Исследуйте другие переопределения `ResourceHandler`, такие как `HandleCss` или `HandleFont`, если ваша библиотека их предоставляет. +- Скомбинируйте этот подход с шагом конвертации в PDF, чтобы генерировать PDF из HTML, сохраняя полный контроль над встроенными ресурсами. +- Ознакомьтесь с документацией библиотеки для получения дополнительных опций, таких как *compression*, *caching* или *asynchronous* сохранение. + +Не стесняйтесь экспериментировать с различными стратегиями хранения и делиться своими находками в комментариях или в любимом сообществе разработчиков. Приятного кодинга! + +## Что стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Как сохранить HTML в C# – Полное руководство с использованием пользовательского обработчика ресурсов](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Создание HTML из строки в C# – Руководство по пользовательскому обработчику ресурсов](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Как заархивировать HTML в C# – Сохранить HTML в ZIP](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 58e38eec45..cbdb3d8d2b 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. +### [Convertir HTML a PDF en C# – establecer estilo de fuente programáticamente](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Aprenda a convertir HTML a PDF en C# estableciendo el estilo de fuente mediante código con Aspose.HTML. ## Conclusión diff --git a/html/spanish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/spanish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..43b74a4c58 --- /dev/null +++ b/html/spanish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Convertir HTML a PDF en C# con control total del renderizado. Aprende + cómo establecer el estilo de fuente programáticamente, habilitar el antialiasing + y mejorar la claridad del texto. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: es +lastmod: 2026-08-03 +og_description: Convierte HTML a PDF en C# con opciones detalladas. Esta guía muestra + cómo establecer el estilo de fuente programáticamente, habilitar el antialiasing + y generar PDFs de alta calidad. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Convertir HTML a PDF en C# – control total del renderizado +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Convertir HTML a PDF en C# – establecer el estilo de fuente programáticamente +url: /es/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir HTML a PDF en C# – establecer estilo de fuente programáticamente + +Si necesitas **convertir HTML a PDF** en una aplicación .NET, este tutorial te guía a través de una solución completa y lista para producción. Verás cómo **establecer el estilo de fuente programáticamente**, mejorar la renderización de imágenes y habilitar el hinting de texto, todo sin salir de tu código C#. + +Convertir páginas web a PDF es un requisito común para informes, facturación y archivado. Esta guía cubre todo, desde la configuración del proyecto hasta un ejemplo completo y ejecutable. Al final del artículo podrás generar PDFs que preserven el diseño, la tipografía y la fidelidad visual. + +## Lo que aprenderás + +* Cómo agregar el paquete NuGet requerido e importar los espacios de nombres. +* Cómo configurar `HtmlConversionOptions` para controlar la renderización. +* Cómo **establecer el estilo de fuente programáticamente** usando los flags `WebFontStyle`. +* Cómo habilitar antialiasing para imágenes y hinting para texto. +* Cómo invocar la clase `Converter` para producir el archivo PDF final. + +El tutorial asume que tienes Visual Studio 2022 (o posterior) y .NET 6 o una versión más reciente instalados. No se requiere ninguna herramienta adicional. + +## Requisitos previos + +| Requisito | Razón | +|---|---| +| .NET 6 SDK or later | Proporciona el runtime para el proyecto C#. | +| Visual Studio 2022 (or any IDE) | Permite crear y depurar proyectos fácilmente. | +| Internet access to restore NuGet packages | Necesario para descargar la biblioteca de conversión. | +| A simple HTML file (`input.html`) | Sirve como documento fuente para la conversión. | + +> **Consejo profesional:** Mantén el archivo HTML en la misma carpeta que el proyecto para evitar problemas relacionados con rutas. + +## Paso 1: Instalar la biblioteca de conversión + +El ejemplo de código usa la biblioteca **GroupDocs.Conversion for .NET**, que ofrece `HtmlConversionOptions` y una clase `Converter`. Instálala mediante el Administrador de paquetes NuGet: + +```bash +dotnet add package GroupDocs.Conversion +``` + +El paquete agrega los tipos necesarios a tu proyecto y trae todas las dependencias. + +## Paso 2: Crear un proyecto de consola C# + +Abre una línea de comandos y ejecuta: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Esto crea una aplicación de consola mínima llamada `HtmlToPdfDemo`. Abre el archivo `Program.cs` generado; más adelante reemplazarás su contenido con el ejemplo completo. + +## Paso 3: Configurar opciones de conversión – establecer estilo de fuente programáticamente + +La clase `HtmlConversionOptions` te permite afinar cómo el motor HTML renderiza la página. Para **establecer el estilo de fuente programáticamente**, combina los valores de la enumeración `WebFontStyle` usando un OR a nivel de bits: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Por qué es importante:** +* `WebFontStyle.Bold | WebFontStyle.Italic` indica al renderizador que aplique ambos estilos a cualquier texto que use la fuente predeterminada. +* El antialiasing reduce los bordes dentados en imágenes raster, especialmente al escalar. +* El hinting alinea los contornos de los glifos a la cuadrícula de píxeles, mejorando la legibilidad en pantallas de baja resolución y en el PDF resultante. + +## Paso 4: Realizar la conversión + +Con las opciones preparadas, llama a la clase `Converter`. El método `Convert` recibe tres argumentos: la ruta del archivo HTML de origen, la ruta del archivo PDF de destino y el objeto de opciones. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +El método se ejecuta de forma síncrona y lanza una excepción si el archivo de origen no se puede leer o la ruta de salida es inválida. Envuelve la llamada en un bloque try‑catch para código de producción. + +## Paso 5: Verificar el resultado + +Después de que el programa termine, abre `output.pdf` con cualquier visor de PDF. Deberías ver: + +* Texto renderizado en **negrita y cursiva** (incluso si el HTML original no especificó esos estilos). +* Las imágenes aparecen más suaves gracias al antialiasing. +* La claridad del texto mejorada por el hinting, especialmente en tamaños de fuente pequeños. + +Si el PDF no refleja los estilos esperados, verifica que el archivo HTML haga referencia a una fuente web‑segura o incluya una regla `@font-face` que el conversor pueda cargar. + +## Ejemplo completo y ejecutable + +A continuación tienes un programa autocontenido que incorpora todos los pasos anteriores. Copia el código en `Program.cs`, coloca un archivo `input.html` junto a él y ejecuta `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Salida esperada en la consola** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Abre el PDF generado para confirmar los estilos aplicados. + +## Manejo de casos límite comunes + +| Situación | Enfoque recomendado | +|---|---| +| **CSS o fuentes externas** | Coloca los archivos CSS y los recursos de fuentes en la misma carpeta que `input.html` o haz referencia a ellos con URLs absolutas accesibles desde la máquina que ejecuta la conversión. | +| **Documentos HTML grandes** | Aumenta el límite de memoria predeterminado ajustando `ConversionConfig` si encuentras `OutOfMemoryException`. | +| **Contenido dinámico (JavaScript)** | La biblioteca no ejecuta JavaScript. Pre‑renderiza las partes dinámicas del lado del servidor o usa un navegador sin cabeza para producir una instantánea HTML estática antes de la conversión. | +| **Caracteres Unicode no se muestran** | Asegúrate de que el HTML declare `` y que las fuentes de origen contengan los glifos necesarios. | +| **Tamaño de página incorrecto** | Establece `conversionOptions.PageSize = PageSize.A4` (u otro valor de enumeración) para imponer dimensiones consistentes. | + +## Consejos de rendimiento + +* Reutiliza una única instancia de `Converter` al convertir muchos archivos; reduce la sobrecarga de inicio. +* Desactiva funciones de renderizado innecesarias (p. ej., `EnableHyperlinks`) si no las necesitas, lo que acelera el procesamiento. +* Escribe el PDF en un `MemoryStream` cuando necesites enviarlo directamente por HTTP en lugar de escribirlo en disco. + +## Próximos pasos + +Ahora que puedes **convertir HTML a PDF** con configuraciones de fuente personalizadas, explora estos temas relacionados: + +- **Establecer márgenes de página programáticamente** – ajusta `conversionOptions.Margin` para controlar el espacio en blanco. +- **Agregar marcas de agua** – usa `PdfConversionOptions` para superponer texto o imágenes. +- **Conversión por lotes** – recorre una colección de archivos HTML y reutiliza el mismo objeto de opciones. + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Convertir HTML a PDF en .NET con Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Crear documento HTML con texto con estilo y exportar a PDF – Guía completa](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Convertir SVG a PDF en .NET con Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/spanish/net/working-with-html-documents/_index.md b/html/spanish/net/working-with-html-documents/_index.md index e0db1c958a..65352f6233 100644 --- a/html/spanish/net/working-with-html-documents/_index.md +++ b/html/spanish/net/working-with-html-documents/_index.md @@ -41,6 +41,8 @@ Ahora, llevemos tus habilidades al siguiente nivel. Editar documentos HTML es un Aprenda a aplicar estilo negrita a encabezados usando CSS y C# con este tutorial detallado. +### [Cargar cadena HTML en C# – Guía completa con controlador personalizado](./load-html-string-in-c-complete-guide-with-custom-handler/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/spanish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/spanish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..9f08edaa14 --- /dev/null +++ b/html/spanish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-03 +description: Cargar una cadena HTML en C# y crear un controlador personalizado para + guardar HTMLDocument. Aprende cómo guardar HTMLDocument con manejo de recursos personalizado. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: es +lastmod: 2026-08-03 +og_description: Cargar cadena HTML en C# y usar un controlador personalizado para + guardar HTMLDocument. Este tutorial muestra la implementación completa y las mejores + prácticas. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Cargar cadena HTML en C# – guía paso a paso de manejador personalizado +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Cargar cadena HTML en C# – guía completa con manejador personalizado +url: /es/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cargar cadena html en C# – guía completa con manejador personalizado + +Si necesitas **cargar cadena html** en una aplicación C#, este tutorial te muestra exactamente cómo hacerlo y cómo **crear un manejador personalizado** para la gestión de recursos. También aprenderás **cómo guardar htmldocument** usando **manejo de recursos personalizado** para que cada imagen, archivo CSS o script se escriba exactamente donde deseas. + +Recorreremos todo el proceso—desde convertir una cadena HTML cruda en un objeto `HTMLDocument`, hasta implementar una subclase de `ResourceHandler` que controla dónde se almacena cada recurso. Al final tendrás un ejemplo autónomo, listo para producción, que puedes incorporar en cualquier proyecto .NET. + +## Requisitos previos + +- .NET 6.0 o posterior (el código también funciona en .NET Framework 4.7+) +- Una referencia a la biblioteca que proporciona `HTMLDocument`, `ResourceHandler` y `ResourceInfo` (p. ej., *HtmlRenderer* o una biblioteca similar de HTML‑a‑PDF/DOM) +- Conocimientos básicos de la sintaxis de C# y streams + +> **Consejo profesional:** Si utilizas Visual Studio, habilita *nullable reference types* (`enable`) para detectar errores relacionados con null temprano. + +## Cómo cargar cadena html en HTMLDocument + +El primer paso es convertir una cadena HTML simple en un objeto `HTMLDocument` que la biblioteca pueda utilizar. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Por qué es importante:** +`HTMLDocument` analiza el marcado, construye un árbol DOM y prepara los recursos (imágenes, hojas de estilo, etc.) para guardarlos posteriormente. Pasar una cadena directamente evita la necesidad de archivos temporales y mantiene el flujo de trabajo en memoria. + +### Errores comunes + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| `htmlContent` is `null` | La variable de cadena nunca se asignó. | Validar antes de crear el documento: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | La biblioteca asume UTF‑8 pero la fuente usa otra codificación. | Proporcionar una sobrecarga explícita de `Encoding` si está disponible, o asegurarse de que la cadena esté decodificada correctamente. | + +## Crear manejador personalizado para el manejo de recursos + +Un **manejador de recursos personalizado** te brinda control total sobre cómo la biblioteca escribe recursos externos (imágenes, CSS, fuentes). A continuación se muestra una implementación mínima que escribe cada recurso en un `MemoryStream`. Puedes reemplazar el cuerpo con lógica de sistema de archivos, almacenamiento en la nube o cualquier otro destino. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Por qué necesitas un manejador personalizado:** +El manejador predeterminado a menudo escribe recursos en una carpeta temporal, lo cual puede ser indeseable por razones de seguridad o rendimiento. Al sobrescribir `HandleResource`, decides exactamente dónde y cómo se almacena cada byte. + +### Extender el manejador para salida a archivo + +Si prefieres escribir cada recurso en una carpeta específica, modifica el método de la siguiente manera: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Cómo guardar htmldocument usando el manejador personalizado + +Ahora que tenemos tanto la instancia `HTMLDocument` como la implementación `MyHandler`, podemos persistir el documento. El método `Save` acepta cualquier subclase de `ResourceHandler`, lo que te permite integrar tu lógica personalizada. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Cuando `Save` se ejecuta, la biblioteca: + +1. Recorrerá el árbol DOM. +2. Detectará recursos externos (p. ej., ``). +3. Llamará a `handler.HandleResource` para cada recurso. +4. Escribirá los datos del recurso en el stream devuelto. +5. Finalizará la salida HTML principal (a menudo como un archivo o stream separado). + +### Verificando el resultado + +Si utilizaste la versión basada en sistema de archivos de `MyHandler`, deberías ver una carpeta `output` con el archivo HTML original y cualquier recurso referenciado. Para la versión `MemoryStream`, puedes inspeccionar la longitud del stream para confirmar que los datos fueron escritos: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Ejemplo completo y ejecutable + +A continuación se muestra un programa único, listo para copiar y pegar, que demuestra todo el flujo. Incluye manejo de errores, disposición de streams y comentarios que explican cada paso. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Salida esperada** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Después de ejecutar el programa, el directorio `output` contiene: + +- `index.html` (el documento principal) +- Cualquier archivo adicional que la biblioteca haya generado (p. ej., imágenes, CSS) + +## Variaciones avanzadas y casos límite + +### Guardar en un `MemoryStream` para procesamiento en memoria + +Si necesitas el HTML final como una cadena o deseas enviarlo por HTTP sin tocar el disco, reemplaza `MyHandler` con una versión que devuelva un `MemoryStream` compartido: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Después de `htmlDoc.Save(handler)`, puedes leer el HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Manejo seguro de recursos grandes + +Al trabajar con imágenes o PDFs grandes, evita cargar todo el archivo en memoria. En su lugar, devuelve un `FileStream` que escribe directamente en el disco, como se mostró antes. Esto previene `OutOfMemoryException` en escenarios de alto rendimiento. + +### Consideraciones de seguridad en hilos + +Las instancias de `HTMLDocument` **no** son seguras para hilos. Si necesitas procesar múltiples cadenas HTML simultáneamente, crea un `HTMLDocument` y `MyHandler` separados por hilo, o sincroniza el acceso con un `lock`. + +### Liberar streams + +Tanto `HTMLDocument.Save` como `ResourceHandler.HandleResource` pueden devolver streams que requieren ser liberados. En los ejemplos anteriores, la biblioteca libera los streams automáticamente después de escribir. Si gestionas los streams tú mismo (p. ej., abriendo un `FileStream` antes de llamar a `Save`), envuélvelos en sentencias `using`. + +## Resumen + +Esta guía te mostró cómo **cargar cadena html** en un `HTMLDocument`, **crear un manejador personalizado** para dictar el almacenamiento de recursos, y **cómo guardar htmldocument** con **manejo de recursos personalizado**. Ahora tienes: + +1. Una forma clara de convertir HTML crudo en un objeto DOM. +2. Una subclase reutilizable de `ResourceHandler` que puede escribir recursos en memoria, disco o almacenamiento en la nube. +3. Un programa completo y ejecutable que demuestra todo el flujo de trabajo. + +## Próximos pasos + +- Explora otras sobrecargas de `ResourceHandler` como `HandleCss` o `HandleFont` si tu biblioteca las proporciona. +- Combina este enfoque con un paso de conversión a PDF para generar PDFs a partir de HTML manteniendo control total sobre los recursos incrustados. +- Revisa la documentación de la biblioteca para opciones adicionales como *compression*, *caching* o guardado *asynchronous*. + +¡Siéntete libre de experimentar con diferentes estrategias de almacenamiento y comparte tus hallazgos en los comentarios o en tu comunidad de desarrolladores favorita! ¡Feliz codificación! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo guardar HTML en C# – Guía completa usando un manejador de recursos personalizado](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Crear HTML a partir de una cadena en C# – Guía de manejador de recursos personalizado](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Cómo comprimir HTML en C# – Guardar HTML en Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 6d01c9b961..405e7e8c61 100644 --- a/html/swedish/net/html-extensions-and-conversions/_index.md +++ b/html/swedish/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML för .NET är inte bara ett bibliotek; det är en spelomvandlare i w ## Tutorials för HTML-tillägg och omvandlingar ### [Konvertera HTML till PDF i .NET med Aspose.HTML](./convert-html-to-pdf/) Konvertera HTML till PDF utan ansträngning med Aspose.HTML för .NET. Följ vår steg-för-steg-guide och släpp lös kraften i HTML-till-PDF-konvertering. +### [Konvertera HTML till PDF i C# – ange teckensnittsstil programatiskt](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Lär dig hur du programatiskt ställer in teckensnittsstil när du konverterar HTML till PDF i C# med Aspose.HTML. ### [Konvertera EPUB till bild i .NET med Aspose.HTML](./convert-epub-to-image/) Lär dig hur du konverterar EPUB till bilder med Aspose.HTML för .NET. Steg-för-steg handledning med kodexempel och anpassningsbara alternativ. ### [Konvertera EPUB till PDF i .NET med Aspose.HTML](./convert-epub-to-pdf/) diff --git a/html/swedish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/swedish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..b3852157f1 --- /dev/null +++ b/html/swedish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Konvertera HTML till PDF i C# med full kontroll över rendering. Lär dig + hur du ställer in teckensnittsstil programatiskt, aktiverar kantutjämning och förbättrar + textens tydlighet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: sv +lastmod: 2026-08-03 +og_description: Konvertera HTML till PDF i C# med detaljerade alternativ. Den här + guiden visar hur du ställer in teckensnittsstil programatiskt, aktiverar kantutjämning + och skapar högkvalitativa PDF-filer. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Konvertera HTML till PDF i C# – full renderingkontroll +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Konvertera HTML till PDF i C# – ställ in teckensnittsstil programatiskt +url: /sv/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera HTML till PDF i C# – ställ in teckensnittsstil programatiskt + +Om du behöver **konvertera HTML till PDF** i en .NET-applikation, guidar den här handledningen dig genom en komplett, produktionsklar lösning. Du kommer att se hur du **ställer in teckensnittsstil programatiskt**, förbättrar bildrendering och aktiverar texthintning—allt utan att lämna din C#-kod. + +Att konvertera webbsidor till PDF är ett vanligt krav för rapportering, fakturering och arkivering. Denna guide täcker allt från projektuppsättning till ett komplett, körbart exempel. I slutet av artikeln kan du generera PDF-filer som bevarar layout, typografi och visuell kvalitet. + +## Vad du kommer att lära dig + +* Hur du lägger till det erforderliga NuGet-paketet och importerar namnrymder. +* Hur du konfigurerar `HtmlConversionOptions` för att styra rendering. +* Hur du **ställer in teckensnittsstil programatiskt** med hjälp av `WebFontStyle`-flaggorna. +* Hur du aktiverar kantutjämning för bilder och hintning för text. +* Hur du anropar `Converter`-klassen för att producera den slutliga PDF-filen. + +Handledningen förutsätter att du har Visual Studio 2022 (eller senare) och .NET 6 eller nyare installerat. Ingen extra verktyg behövs. + +## Förutsättningar + +| Requirement | Reason | +|---|---| +| .NET 6 SDK eller senare | Tillhandahåller runtime för C#-projektet. | +| Visual Studio 2022 (eller någon IDE) | Gör det enkelt att skapa projekt och felsöka. | +| Internetåtkomst för att återställa NuGet-paket | Behövs för att ladda ner konverteringsbiblioteket. | +| En enkel HTML-fil (`input.html`) | Fungerar som källdokument för konvertering. | + +> **Proffstips:** Behåll HTML-filen i samma mapp som projektet för att undvika sökvägsrelaterade problem. + +## Steg 1: Installera konverteringsbiblioteket + +Kodexemplet använder **GroupDocs.Conversion for .NET**-biblioteket, som erbjuder `HtmlConversionOptions` och en `Converter`-klass. Installera det via NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Paketet lägger till de nödvändiga typerna i ditt projekt och hämtar alla beroenden. + +## Steg 2: Skapa ett C#-konsolprojekt + +Öppna en kommandotolk och kör: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Detta skapar en minimal konsolapplikation med namnet `HtmlToPdfDemo`. Öppna den genererade filen `Program.cs`; du kommer att ersätta dess innehåll med det fullständiga exemplet senare. + +## Steg 3: Konfigurera konverteringsalternativ – ställ in teckensnittsstil programatiskt + +`HtmlConversionOptions`-klassen låter dig finjustera hur HTML-motorn renderar sidan. För att **ställa in teckensnittsstil programatiskt**, kombinera `WebFontStyle`-enumerationsvärdena med en bitvis OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Varför detta är viktigt:** +* `WebFontStyle.Bold | WebFontStyle.Italic` talar om för renderaren att tillämpa båda stilarna på all text som använder standardfonten. +* Kantutjämning minskar hackiga kanter på rasterbilder, särskilt vid skalning. +* Hintning justerar glyfkonturer till pixelrutnät, vilket förbättrar läsbarheten på lågupplösta skärmar och i den resulterande PDF-filen. + +## Steg 4: Utför konverteringen + +Med alternativen förberedda, anropa `Converter`-klassen. `Convert`-metoden tar tre argument: sökvägen till käll-HTML-filen, sökvägen till mål-PDF-filen och alternativobjektet. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Metoden körs synkront och kastar ett undantag om källfilen inte kan läsas eller om utskriftssökvägen är ogiltig. Omslut anropet med ett try‑catch‑block för produktionskod. + +## Steg 5: Verifiera resultatet + +När programmet är klart, öppna `output.pdf` med någon PDF-läsare. Du bör se: + +* Text renderad i **fet och kursiv** (även om den ursprungliga HTML:n inte specificerade dessa stilar). +* Bilder ser mjukare ut tack vare kantutjämning. +* Textens klarhet förbättras av hintning, särskilt för små teckensnittsstorlekar. + +Om PDF-filen inte visar de förväntade stilarna, dubbelkolla att HTML-filen refererar till ett webbsäkert teckensnitt eller inkluderar en `@font-face`-regel som konverteraren kan ladda. + +## Fullständigt, körbart exempel + +Nedan är ett självständigt program som inkluderar alla tidigare steg. Kopiera koden till `Program.cs`, placera en `input.html`-fil bredvid den och kör `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Förväntad konsolutdata** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Öppna den genererade PDF-filen för att bekräfta de tillämpade stilarna. + +## Hantera vanliga kantfall + +| Situation | Recommended approach | +|---|---| +| **Extern CSS eller teckensnitt** | Placera CSS-filer och teckensnitt i samma mapp som `input.html` eller referera dem med absoluta URL:er som är åtkomliga från maskinen som kör konverteringen. | +| **Stora HTML-dokument** | Öka standardminnesgränsen genom att justera `ConversionConfig` om du stöter på `OutOfMemoryException`. | +| **Dynamiskt innehåll (JavaScript)** | Biblioteket kör inte JavaScript. Förrendera dynamiska delar på servern eller använd en huvudlös webbläsare för att skapa en statisk HTML-snapshot innan konvertering. | +| **Unicode-tecken visas inte** | Säkerställ att HTML:n deklarerar `` och att källteckensnitten innehåller de nödvändiga glyferna. | +| **Felaktig sidstorlek** | Ställ in `conversionOptions.PageSize = PageSize.A4` (eller ett annat enum‑värde) för att upprätthålla konsekventa dimensioner. | + +## Prestandatips + +* Återanvänd en enda `Converter`-instans när du konverterar många filer; det minskar uppstartsöverhead. +* Inaktivera onödiga renderingsfunktioner (t.ex. `EnableHyperlinks`) om du inte behöver dem, vilket snabbar upp bearbetningen. +* Skriv PDF-filen till ett minnesström när du behöver skicka den direkt över HTTP istället för att skriva till disk. + +## Nästa steg + +Nu när du kan **konvertera HTML till PDF** med anpassade teckensnittsinställningar, utforska dessa relaterade ämnen: + +- [Ställ in sidmarginaler programatiskt] – adjust `conversionOptions.Margin` to control white space. +- [Lägg till vattenstämplar] – use `PdfConversionOptions` to overlay text or images. +- [Batch‑konvertering] – loop over a collection of HTML files and reuse the same options object. + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig behärska ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Konvertera HTML till PDF i .NET med Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Skapa HTML-dokument med formaterad text och exportera till PDF – Fullständig guide](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Konvertera SVG till PDF i .NET med Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/swedish/net/working-with-html-documents/_index.md b/html/swedish/net/working-with-html-documents/_index.md index a3260bb44c..247d4effde 100644 --- a/html/swedish/net/working-with-html-documents/_index.md +++ b/html/swedish/net/working-with-html-documents/_index.md @@ -43,6 +43,10 @@ Lär dig spara HTML i C# med en anpassad resurs‑hanterare och generera komplet Lär dig hur du använder CSS och C# för att göra rubriker fetstilta i dina HTML‑dokument med en steg‑för‑steg‑guide. +### [Ladda HTML‑sträng i C# – komplett guide med anpassad hanterare](./load-html-string-in-c-complete-guide-with-custom-handler/) + +Lär dig hur du laddar HTML‑strängar i C# med en anpassad hanterare för smidig bearbetning. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/swedish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/swedish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..b3c37fa64e --- /dev/null +++ b/html/swedish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-03 +description: Ladda HTML-sträng i C# och skapa en anpassad hanterare för att spara + HTMLDocument. Lär dig hur du sparar HTMLDocument med anpassad resurs‑hantering. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: sv +lastmod: 2026-08-03 +og_description: Läs in HTML-sträng i C# och använd en anpassad hanterare för att spara + HTMLDocument. Denna handledning visar den fullständiga implementeringen och bästa + praxis. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Ladda HTML-sträng i C# – steg‑för‑steg guide för anpassad hanterare +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Ladda HTML-sträng i C# – komplett guide med anpassad hanterare +url: /sv/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ladda html-sträng i C# – komplett guide med anpassad hanterare + +Om du behöver **ladda html-sträng** i en C#-applikation visar den här handledningen exakt hur du gör det och hur du **skapar en anpassad hanterare** för resurshantering. Du får också lära dig **hur du sparar htmldocument** med **anpassad resurshantering** så att varje bild, CSS‑fil eller skript skrivs exakt där du vill. + +Vi går igenom hela processen—från att omvandla en rå HTML-sträng till ett `HTMLDocument`‑objekt, till att implementera en `ResourceHandler`‑subklass som styr var varje resurs lagras. I slutet har du ett självständigt, produktionsklart exempel som du kan lägga in i vilket .NET‑projekt som helst. + +## Förutsättningar + +- .NET 6.0 eller senare (koden fungerar också på .NET Framework 4.7+) +- En referens till biblioteket som tillhandahåller `HTMLDocument`, `ResourceHandler` och `ResourceInfo` (t.ex. *HtmlRenderer* eller ett liknande HTML‑till‑PDF/DOM‑bibliotek) +- Grundläggande kunskap om C#‑syntax och strömmar + +> **Proffstips:** Om du använder Visual Studio, aktivera *nullable reference types* (`enable`) för att tidigt fånga null‑relaterade buggar. + +## Så laddar du html-sträng i HTMLDocument + +Det första steget är att konvertera en vanlig HTML-sträng till ett `HTMLDocument`‑objekt som biblioteket kan arbeta med. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Varför detta är viktigt:** +`HTMLDocument` analyserar markupen, bygger ett DOM‑träd och förbereder resurser (bilder, stilmallar osv.) för senare sparande. Att skicka en sträng direkt undviker behovet av temporära filer och håller arbetsflödet i minnet. + +### Vanliga fallgropar + +| Problem | Varför det händer | Lösning | +|---------|-------------------|---------| +| `htmlContent` är `null` | Strängvariabeln tilldelades aldrig. | Validera innan du skapar dokumentet: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Kodningsproblem | Biblioteket antar UTF‑8 men källan använder en annan kodning. | Tillhandahåll en explicit `Encoding`‑överladdning om den finns, eller säkerställ att strängen är korrekt avkodad. | + +## Skapa anpassad hanterare för resurshantering + +En **anpassad resurshanterare** ger dig full kontroll över hur biblioteket skriver externa resurser (bilder, CSS, teckensnitt). Nedan är en minimal implementation som skriver varje resurs till ett `MemoryStream`. Du kan ersätta kroppen med filsystemlogik, molnlagring eller någon annan destination. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Varför du behöver en anpassad hanterare:** +Standardhanteraren skriver ofta resurser till en temporär mapp, vilket kan vara oönskat av säkerhets- eller prestandaskäl. Genom att åsidosätta `HandleResource` bestämmer du exakt var och hur varje byte lagras. + +### Utöka hanteraren för filutmatning + +Om du föredrar att skriva varje resurs till en specifik mapp, ändra metoden enligt följande: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Så sparar du htmldocument med den anpassade hanteraren + +Nu när vi har både `HTMLDocument`‑instansen och `MyHandler`‑implementationen kan vi bestå dokumentet. `Save`‑metoden accepterar vilken `ResourceHandler`‑subklass som helst, så att du kan ansluta din anpassade logik. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +När `Save` körs kommer biblioteket att: + +1. Traversera DOM‑trädet. +2. Upptäcka externa resurser (t.ex. ``). +3. Anropa `handler.HandleResource` för varje resurs. +4. Skriva resursdata till den returnerade strömmen. +5. Slutföra huvud‑HTML‑utdata (ofta som en separat fil eller ström). + +### Verifiera resultatet + +Om du använde filsystemsversionen av `MyHandler` bör du se en `output`‑mapp med den ursprungliga HTML‑filen och alla refererade tillgångar. För `MemoryStream`‑versionen kan du inspektera strömlängden för att bekräfta att data har skrivits: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Fullt, körbart exempel + +Nedan är ett enda, kopiera‑och‑klistra‑klart program som demonstrerar hela flödet. Det inkluderar felhantering, disponering av strömmar och kommentarer som förklarar varje steg. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Förväntad utdata** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Efter att programmet har körts innehåller `output`‑katalogen: + +- `index.html` (huvuddokumentet) +- Alla ytterligare filer som biblioteket genererade (t.ex. bilder, CSS) + +## Avancerade varianter och kantfall + +### Spara till ett `MemoryStream` för bearbetning i minnet + +Om du behöver den slutgiltiga HTML‑koden som en sträng eller vill skicka den via HTTP utan att röra disken, ersätt `MyHandler` med en version som returnerar ett delat `MemoryStream`: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Efter `htmlDoc.Save(handler)` kan du läsa HTML‑koden: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Hantera stora resurser på ett säkert sätt + +När du hanterar stora bilder eller PDF‑filer, undvik att läsa in hela filen i minnet. Returnera istället ett `FileStream` som skriver direkt till disk, som visat tidigare. Detta förhindrar `OutOfMemoryException` i scenarier med hög genomströmning. + +### Trådsäkerhetsaspekter + +`HTMLDocument`‑instanser är **inte** trådsäkra. Om du behöver bearbeta flera HTML‑strängar samtidigt, skapa en separat `HTMLDocument` och `MyHandler` per tråd, eller synkronisera åtkomst med en `lock`. + +### Disposition av strömmar + +Både `HTMLDocument.Save` och `ResourceHandler.HandleResource` kan returnera strömmar som behöver disponeras. I exemplen ovan disponerar biblioteket strömmarna automatiskt efter skrivning. Om du hanterar strömmar själv (t.ex. öppnar ett `FileStream` innan du anropar `Save`), omslut dem med `using`‑satser. + +## Sammanfattning + +Denna guide visade dig hur du **laddar html-sträng** i ett `HTMLDocument`, **skapar en anpassad hanterare** för att bestämma resurslagring, och **hur du sparar htmldocument** med **anpassad resurshantering**. Du har nu: + +1. Ett tydligt sätt att omvandla rå HTML till ett DOM‑objekt. +2. En återanvändbar `ResourceHandler`‑subklass som kan skriva resurser till minne, disk eller molnlagring. +3. Ett komplett, körbart program som demonstrerar hela arbetsflödet. + +## Nästa steg + +- Utforska andra `ResourceHandler`‑överskuggningar såsom `HandleCss` eller `HandleFont` om ditt bibliotek tillhandahåller dem. +- Kombinera detta tillvägagångssätt med ett PDF‑konverteringssteg för att generera PDF‑filer från HTML samtidigt som du behåller full kontroll över inbäddade tillgångar. +- Granska bibliotekets dokumentation för ytterligare alternativ som *komprimering*, *cachning* eller *asynkron* sparning. + +Känn dig fri att experimentera med olika lagringsstrategier och dela dina resultat i kommentarerna eller i ditt favorit‑utvecklargemenskap. Lycka till med kodandet! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man sparar HTML i C# – Komplett guide med anpassad resurshanterare](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Skapa HTML från sträng i C# – Guide för anpassad resurshanterare](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Hur man zippar HTML i C# – Spara HTML till Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 2474ca32c0..ad22903997 100644 --- a/html/thai/net/html-extensions-and-conversions/_index.md +++ b/html/thai/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML สำหรับ .NET ไม่ใช่แค่ไลบรา ## บทช่วยสอนเกี่ยวกับส่วนขยายและการแปลง HTML ### [แปลง HTML เป็น PDF ใน .NET ด้วย Aspose.HTML](./convert-html-to-pdf/) แปลง HTML เป็น PDF ได้อย่างง่ายดายด้วย Aspose.HTML สำหรับ .NET ปฏิบัติตามคำแนะนำทีละขั้นตอนของเราและปลดปล่อยพลังแห่งการแปลง HTML เป็น PDF +### [แปลง HTML เป็น PDF ใน C# – ตั้งสไตล์ฟอนต์โดยโปรแกรม](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +เรียนรู้วิธีตั้งค่าแบบอักษรในไฟล์ PDF ที่แปลงจาก HTML ด้วย C# และ Aspose.HTML ### [แปลง EPUB เป็นรูปภาพใน .NET ด้วย Aspose.HTML](./convert-epub-to-image/) เรียนรู้วิธีการแปลง EPUB เป็นรูปภาพโดยใช้ Aspose.HTML สำหรับ .NET บทช่วยสอนแบบทีละขั้นตอนพร้อมตัวอย่างโค้ดและตัวเลือกที่ปรับแต่งได้ ### [แปลง EPUB เป็น PDF ใน .NET ด้วย Aspose.HTML](./convert-epub-to-pdf/) diff --git a/html/thai/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/thai/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..315b08a57b --- /dev/null +++ b/html/thai/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-08-03 +description: แปลง HTML เป็น PDF ด้วย C# พร้อมการควบคุมการเรนเดอร์เต็มรูปแบบ เรียนรู้วิธีตั้งค่ารูปแบบฟอนต์โดยโปรแกรม + เปิดใช้งานการแอนตี้แอลิอัส และปรับปรุงความคมชัดของข้อความ +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: th +lastmod: 2026-08-03 +og_description: แปลง HTML เป็น PDF ด้วย C# พร้อมตัวเลือกละเอียด คู่มือนี้แสดงวิธีตั้งค่าแบบอักษรโดยโปรแกรม, + เปิดใช้งานการแอนตี้แอลิอาซิง, และสร้าง PDF คุณภาพสูง +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: แปลง HTML เป็น PDF ใน C# – การควบคุมการแสดงผลเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: แปลง HTML เป็น PDF ใน C# – ตั้งค่าฟอนต์โดยโปรแกรม +url: /th/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง HTML เป็น PDF ใน C# – ตั้งค่ารูปแบบฟอนต์โดยโปรแกรม + +หากคุณต้องการ **แปลง HTML เป็น PDF** ในแอปพลิเคชัน .NET บทแนะนำนี้จะพาคุณผ่านโซลูชันที่สมบูรณ์และพร้อมใช้งานในระดับการผลิต คุณจะได้เห็นวิธี **ตั้งค่ารูปแบบฟอนต์โดยโปรแกรม**, ปรับปรุงการแสดงผลภาพ, และเปิดใช้งานการ hint ข้อความ—ทั้งหมดโดยไม่ต้องออกจากโค้ด C# ของคุณ + +การแปลงหน้าเว็บเป็น PDF เป็นความต้องการทั่วไปสำหรับการรายงาน, การออกใบแจ้งหนี้, และการเก็บถาวร คู่มือนี้ครอบคลุมทุกอย่างตั้งแต่การตั้งค่าโปรเจกต์จนถึงตัวอย่างที่สามารถรันได้เต็มรูปแบบ เมื่ออ่านจบบทความคุณจะสามารถสร้าง PDF ที่คงรูปแบบการจัดวาง, การพิมพ์, และความคมชัดของภาพได้ + +## สิ่งที่คุณจะได้เรียนรู้ + +* วิธีเพิ่มแพ็กเกจ NuGet ที่จำเป็นและนำเข้า namespace +* วิธีกำหนดค่า `HtmlConversionOptions` เพื่อควบคุมการเรนเดอร์ +* วิธี **ตั้งค่ารูปแบบฟอนต์โดยโปรแกรม** ด้วยแฟล็ก `WebFontStyle` +* วิธีเปิดใช้งาน antialiasing สำหรับภาพและ hinting สำหรับข้อความ +* วิธีเรียกใช้คลาส `Converter` เพื่อสร้างไฟล์ PDF ขั้นสุดท้าย + +บทแนะนำนี้สมมติว่าคุณมี Visual Studio 2022 (หรือใหม่กว่า) และ .NET 6 หรือใหม่กว่า ติดตั้งแล้ว ไม่ต้องใช้เครื่องมือเพิ่มเติมใด ๆ + +## ความต้องการเบื้องต้น + +| ความต้องการ | เหตุผล | +|---|---| +| .NET 6 SDK หรือใหม่กว่า | ให้ runtime สำหรับโปรเจกต์ C# | +| Visual Studio 2022 (หรือ IDE ใดก็ได้) | ช่วยสร้างโปรเจกต์และดีบักได้ง่าย | +| การเชื่อมต่ออินเทอร์เน็ตเพื่อเรียกคืนแพ็กเกจ NuGet | จำเป็นต้องดาวน์โหลดไลบรารีการแปลง | +| ไฟล์ HTML ง่าย ๆ (`input.html`) | ทำหน้าที่เป็นเอกสารต้นทางสำหรับการแปลง | + +> **เคล็ดลับ:** เก็บไฟล์ HTML ไว้ในโฟลเดอร์เดียวกับโปรเจกต์เพื่อหลีกเลี่ยงปัญหาเกี่ยวกับเส้นทาง + +## ขั้นตอนที่ 1: ติดตั้งไลบรารีการแปลง + +ตัวอย่างโค้ดใช้ไลบรารี **GroupDocs.Conversion for .NET** ซึ่งมี `HtmlConversionOptions` และคลาส `Converter` ติดตั้งผ่าน NuGet Package Manager: + +```bash +dotnet add package GroupDocs.Conversion +``` + +แพ็กเกจจะเพิ่มประเภทที่จำเป็นให้กับโปรเจกต์ของคุณและดึง dependencies ทั้งหมดเข้ามา + +## ขั้นตอนที่ 2: สร้างโปรเจกต์คอนโซล C# + +เปิด command prompt แล้วรัน: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +คำสั่งนี้จะสร้างแอปพลิเคชันคอนโซลขนาดเล็กชื่อ `HtmlToPdfDemo` เปิดไฟล์ `Program.cs` ที่สร้างขึ้น; คุณจะเปลี่ยนเนื้อหาเป็นตัวอย่างเต็มในขั้นตอนต่อไป + +## ขั้นตอนที่ 3: กำหนดค่าตัวเลือกการแปลง – ตั้งค่ารูปแบบฟอนต์โดยโปรแกรม + +คลาส `HtmlConversionOptions` ให้คุณปรับจูนการเรนเดอร์ของเอนจิน HTML ได้อย่างละเอียด เพื่อ **ตั้งค่ารูปแบบฟอนต์โดยโปรแกรม** ให้รวมค่าจาก enumeration `WebFontStyle` ด้วยการใช้ bitwise OR: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**ทำไมจึงสำคัญ:** +* `WebFontStyle.Bold | WebFontStyle.Italic` บอกให้เรนเดอร์ใช้สไตล์ทั้งสองกับข้อความใด ๆ ที่ใช้ฟอนต์เริ่มต้น +* Antialiasing ลดขอบหยักของภาพ raster โดยเฉพาะเมื่อมีการสเกล +* Hinting จัดแนว outlines ของ glyph ให้ตรงกับพิกเซลกริด ทำให้อ่านง่ายขึ้นบนหน้าจอความละเอียดต่ำและใน PDF ที่ได้ + +## ขั้นตอนที่ 4: ทำการแปลง + +เมื่อเตรียมตัวเลือกเรียบร้อยแล้ว ให้เรียกคลาส `Converter` วิธี `Convert` รับอาร์กิวเมนต์สามค่า: เส้นทางไฟล์ HTML ต้นทาง, เส้นทางไฟล์ PDF ปลายทาง, และอ็อบเจกต์ตัวเลือก + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +เมธอดทำงานแบบ synchronous และจะโยน exception หากไม่สามารถอ่านไฟล์ต้นทางหรือเส้นทางปลายทางไม่ถูกต้อง ควรห่อการเรียกในบล็อก try‑catch สำหรับโค้ดระดับ production + +## ขั้นตอนที่ 5: ตรวจสอบผลลัพธ์ + +เมื่อโปรแกรมทำงานเสร็จ เปิด `output.pdf` ด้วยโปรแกรมอ่าน PDF ใดก็ได้ คุณควรเห็น: + +* ข้อความแสดงผลเป็น **ตัวหนาและตัวเอียง** (แม้ HTML ดั้งเดิมจะไม่ได้ระบุสไตล์เหล่านั้น) +* ภาพดูเรียบเนียนขึ้นด้วย antialiasing +* ความคมชัดของข้อความดีขึ้นด้วย hinting โดยเฉพาะสำหรับขนาดฟอนต์เล็ก + +หาก PDF ไม่แสดงสไตล์ตามที่คาดไว้ ให้ตรวจสอบว่าไฟล์ HTML อ้างอิงฟอนต์ที่เป็น web‑safe หรือมีกฎ `@font-face` ที่ตัวแปลงสามารถโหลดได้ + +## ตัวอย่างเต็มที่สามารถรันได้ + +ด้านล่างเป็นโปรแกรมแบบ self‑contained ที่รวมขั้นตอนทั้งหมดไว้ในไฟล์เดียว คัดลอกโค้ดไปยัง `Program.cs` วางไฟล์ `input.html` ไว้ข้าง ๆ แล้วรัน `dotnet run` + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**ผลลัพธ์ที่คาดว่าจะเห็นในคอนโซล** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +เปิด PDF ที่สร้างขึ้นเพื่อยืนยันว่ามีการนำสไตล์ที่ตั้งค่าไว้ไปใช้ + +## การจัดการกรณีขอบเขตทั่วไป + +| สถานการณ์ | วิธีการที่แนะนำ | +|---|---| +| **CSS หรือฟอนต์ภายนอก** | วางไฟล์ CSS และทรัพยากรฟอนต์ในโฟลเดอร์เดียวกับ `input.html` หรืออ้างอิงด้วย URL แบบ absolute ที่เครื่องทำการแปลงสามารถเข้าถึงได้ | +| **เอกสาร HTML ขนาดใหญ่** | เพิ่มขีดจำกัดหน่วยความจำเริ่มต้นโดยปรับ `ConversionConfig` หากเจอ `OutOfMemoryException` | +| **เนื้อหาแบบไดนามิก (JavaScript)** | ไลบรารีไม่ทำการรัน JavaScript ให้เรนเดอร์ส่วนไดนามิกบนเซิร์ฟเวอร์ล่วงหน้าหรือใช้ headless browser สร้าง snapshot HTML แบบสถิติก่อนแปลง | +| **อักขระ Unicode ไม่แสดง** | ตรวจสอบว่า HTML มี `` และฟอนต์ต้นทางมี glyph ที่ต้องการ | +| **ขนาดหน้าผิด** | ตั้งค่า `conversionOptions.PageSize = PageSize.A4` (หรือค่า enum อื่น) เพื่อบังคับขนาดที่สม่ำเสมอ | + +## เคล็ดลับด้านประสิทธิภาพ + +* ใช้ instance ของ `Converter` เพียงตัวเดียวเมื่อแปลงหลายไฟล์; จะลดค่าใช้จ่ายการเริ่มต้น | +* ปิดฟีเจอร์การเรนเดอร์ที่ไม่จำเป็น (เช่น `EnableHyperlinks`) หากคุณไม่ต้องการ จะช่วยเร่งการประมวลผล | +* เขียน PDF ไปยัง memory stream เมื่อจำเป็นต้องส่งโดยตรงผ่าน HTTP แทนการเขียนลงดิสก์ | + +## ขั้นตอนต่อไป + +ตอนนี้คุณสามารถ **แปลง HTML เป็น PDF** พร้อมตั้งค่าฟอนต์แบบกำหนดเองได้แล้ว ลองสำรวจหัวข้อที่เกี่ยวข้องต่อไปนี้: + +* **ตั้งค่าขอบกระดาษโดยโปรแกรม** – ปรับ `conversionOptions.Margin` เพื่อควบคุมพื้นที่ว่าง | +* **เพิ่มลายน้ำ** – ใช้ `PdfConversionOptions` เพื่อวางข้อความหรือรูปภาพบน PDF | +* **แปลงเป็นชุด** – วนลูปผ่านคอลเลกชันของไฟล์ HTML และใช้ตัวเลือกเดียวกันซ้ำหลายครั้ง | + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโครงการของคุณเอง + +- [แปลง HTML เป็น PDF ใน .NET ด้วย Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [สร้างเอกสาร HTML พร้อมข้อความสไตล์และส่งออกเป็น PDF – คู่มือเต็ม](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [แปลง SVG เป็น PDF ใน .NET ด้วย Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/working-with-html-documents/_index.md b/html/thai/net/working-with-html-documents/_index.md index d8de34f36b..97d695922c 100644 --- a/html/thai/net/working-with-html-documents/_index.md +++ b/html/thai/net/working-with-html-documents/_index.md @@ -38,6 +38,8 @@ url: /th/net/working-with-html-documents/ ### [วิธีบันทึก HTML ใน C# – คู่มือฉบับสมบูรณ์โดยใช้ Custom Resource Handler](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) ### [วิธีทำให้หัวเรื่องเป็นตัวหนาด้วย CSS & C# – คู่มือขั้นตอนเต็ม](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) +### [โหลดสตริง HTML ใน C# – คู่มือฉบับสมบูรณ์ด้วยตัวจัดการแบบกำหนดเอง](./load-html-string-in-c-complete-guide-with-custom-handler/) + เรียนรู้วิธีทำให้หัวเรื่องเป็นตัวหนาด้วย CSS ใน C# อย่างละเอียด พร้อมขั้นตอนครบถ้วนเพื่อปรับปรุงการออกแบบเว็บของคุณ {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/thai/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/thai/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..f769e6e8b3 --- /dev/null +++ b/html/thai/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-03 +description: โหลดสตริง HTML ใน C# และสร้างตัวจัดการแบบกำหนดเองเพื่อบันทึก HTMLDocument. + เรียนรู้วิธีบันทึก HTMLDocument ด้วยการจัดการทรัพยากรแบบกำหนดเอง. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: th +lastmod: 2026-08-03 +og_description: โหลดสตริง HTML ใน C# และใช้ตัวจัดการแบบกำหนดเองเพื่อบันทึก HTMLDocument + บทเรียนนี้แสดงการทำงานเต็มรูปแบบและแนวทางปฏิบัติที่ดีที่สุด +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: โหลดสตริง HTML ใน C# – คู่มือการสร้างตัวจัดการแบบกำหนดเองแบบขั้นตอนต่อขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: โหลดสตริง HTML ใน C# – คู่มือฉบับสมบูรณ์พร้อมตัวจัดการแบบกำหนดเอง +url: /th/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# โหลดสตริง HTML ใน C# – คู่มือเต็มพร้อมตัวจัดการแบบกำหนดเอง + +หากคุณต้องการ **load html string** ในแอปพลิเคชัน C# นี้ คู่มือจะสาธิตให้คุณเห็นขั้นตอนอย่างละเอียดและวิธี **create custom handler** สำหรับการจัดการทรัพยากร คุณยังจะได้เรียนรู้ **how to save htmldocument** ด้วย **custom resource handling** เพื่อให้ภาพ, ไฟล์ CSS หรือสคริปต์ทั้งหมดถูกเขียนลงในตำแหน่งที่คุณต้องการอย่างแม่นยำ + +เราจะเดินผ่านกระบวนการทั้งหมด—จากการแปลงสตริง HTML ดิบเป็นอ็อบเจ็กต์ `HTMLDocument` ไปจนถึงการสร้าง subclass ของ `ResourceHandler` ที่ควบคุมตำแหน่งการจัดเก็บของแต่ละทรัพยากร เมื่อเสร็จแล้วคุณจะมีตัวอย่างที่เป็นอิสระและพร้อมใช้งานในระดับการผลิตซึ่งสามารถนำไปใส่ในโปรเจกต์ .NET ใดก็ได้ + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (โค้ดนี้ยังทำงานบน .NET Framework 4.7+ ได้เช่นกัน) +- การอ้างอิงถึงไลบรารีที่ให้ `HTMLDocument`, `ResourceHandler`, และ `ResourceInfo` (เช่น *HtmlRenderer* หรือไลบรารี HTML‑to‑PDF/DOM ที่คล้ายกัน) +- ความรู้พื้นฐานเกี่ยวกับไวยากรณ์ C# และสตรีม + +> **เคล็ดลับ:** หากคุณใช้ Visual Studio ให้เปิดใช้ *nullable reference types* (`enable`) เพื่อจับบั๊กที่เกี่ยวกับค่า null ตั้งแต่ต้น + +## วิธีโหลดสตริง HTML ไปยัง HTMLDocument + +ขั้นตอนแรกคือการแปลงสตริง HTML ธรรมดาให้เป็นอ็อบเจ็กต์ `HTMLDocument` ที่ไลบรารีสามารถทำงานได้ + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**ทำไมเรื่องนี้ถึงสำคัญ:** +`HTMLDocument` จะทำการพาร์สมาร์กอัป, สร้างต้นไม้ DOM, และเตรียมทรัพยากร (ภาพ, สไตล์ชีต ฯลฯ) สำหรับการบันทึกในภายหลัง การส่งสตริงโดยตรงช่วยหลีกเลี่ยงการต้องใช้ไฟล์ชั่วคราวและทำให้กระบวนการทำงานอยู่ในหน่วยความจำ + +### จุดบกพร่องทั่วไป + +| ปัญหา | ทำไมถึงเกิด | วิธีแก้ | +|-------|------------|---------| +| `htmlContent` is `null` | ตัวแปรสตริงไม่ได้รับค่าใด ๆ | ตรวจสอบก่อนสร้างเอกสาร: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | ไลบรารีสมมติว่าเป็น UTF‑8 แต่แหล่งข้อมูลใช้การเข้ารหัสอื่น | ระบุ overload ของ `Encoding` อย่างชัดเจนหากมีให้ใช้, หรือให้แน่ใจว่าสตริงถูกถอดรหัสอย่างถูกต้อง. | + +## สร้างตัวจัดการแบบกำหนดเองสำหรับการจัดการทรัพยากร + +**custom resource handler** ให้คุณควบคุมเต็มที่ว่าห้องสมุดเขียนทรัพยากรภายนอก (ภาพ, CSS, ฟอนต์) อย่างไร ด้านล่างเป็นการนำไปใช้อย่างง่ายที่สุดที่เขียนแต่ละทรัพยากรลงใน `MemoryStream` คุณสามารถแทนที่ส่วนเนื้อหาได้ด้วยตรรกะของระบบไฟล์, การจัดเก็บบนคลาวด์ หรือปลายทางอื่น ๆ + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**ทำไมคุณต้องการตัวจัดการแบบกำหนดเอง:** +ตัวจัดการเริ่มต้นมักเขียนทรัพยากรลงในโฟลเดอร์ชั่วคราว ซึ่งอาจไม่เหมาะสมจากเหตุผลด้านความปลอดภัยหรือประสิทธิภาพ โดยการ override `HandleResource` คุณจะกำหนดได้อย่างแม่นยำว่าข้อมูลไบต์แต่ละบิตจะถูกเก็บไว้ที่ไหนและอย่างไร + +### ขยายตัวจัดการเพื่อบันทึกเป็นไฟล์ + +หากคุณต้องการเขียนแต่ละทรัพยากรลงในโฟลเดอร์เฉพาะ ให้แก้ไขเมธอดดังต่อไปนี้: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## วิธีบันทึก htmldocument ด้วยตัวจัดการแบบกำหนดเอง + +ตอนนี้เรามีอินสแตนซ์ `HTMLDocument` และการทำงานของ `MyHandler` แล้ว เราจึงสามารถบันทึกเอกสารได้ เมธอด `Save` รับ subclass ของ `ResourceHandler` ใดก็ได้ ทำให้คุณสามารถเชื่อมต่อตรรกะที่กำหนดเองของคุณ + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +เมื่อ `Save` ทำงาน ไลบรารีจะ: + +1. เดินผ่านต้นไม้ DOM +2. ตรวจจับทรัพยากรภายนอก (เช่น ``) +3. เรียก `handler.HandleResource` สำหรับแต่ละทรัพยากร +4. เขียนข้อมูลทรัพยากรลงในสตรีมที่คืนค่า +5. สรุปผลลัพธ์ HTML หลัก (มักเป็นไฟล์หรือสตรีมแยก) + +### การตรวจสอบผลลัพธ์ + +หากคุณใช้เวอร์ชันไฟล์‑ระบบของ `MyHandler` คุณควรเห็นโฟลเดอร์ `output` ที่มีไฟล์ HTML ดั้งเดิมและทรัพยากรที่อ้างอิงทั้งหมด สำหรับเวอร์ชัน `MemoryStream` คุณสามารถตรวจสอบความยาวของสตรีมเพื่อยืนยันว่าข้อมูลถูกเขียนแล้ว: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## ตัวอย่างเต็มที่สามารถรันได้ + +ด้านล่างเป็นโปรแกรมเดียวที่พร้อมคัดลอก‑วางซึ่งแสดงกระบวนการทั้งหมด รวมถึงการจัดการข้อผิดพลาด, การปล่อยสตรีม, และคอมเมนต์ที่อธิบายแต่ละขั้นตอน + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**ผลลัพธ์ที่คาดหวัง** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +หลังจากรันโปรแกรมแล้ว โฟลเดอร์ `output` จะประกอบด้วย: + +- `index.html` (เอกสารหลัก) +- ไฟล์เพิ่มเติมใด ๆ ที่ไลบรารีสร้างขึ้น (เช่น ภาพ, CSS) + +## ตัวแปรขั้นสูงและกรณีขอบ + +### การบันทึกลง `MemoryStream` สำหรับการประมวลผลในหน่วยความจำ + +หากคุณต้องการ HTML สุดท้ายเป็นสตริงหรือส่งผ่าน HTTP โดยไม่ต้องเขียนลงดิสก์ ให้แทนที่ `MyHandler` ด้วยเวอร์ชันที่คืนค่า `MemoryStream` ที่ใช้ร่วมกัน: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +หลังจาก `htmlDoc.Save(handler)` คุณสามารถอ่าน HTML ได้: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### การจัดการทรัพยากรขนาดใหญ่อย่างปลอดภัย + +เมื่อทำงานกับภาพหรือ PDF ขนาดใหญ่ ควรหลีกเลี่ยงการโหลดไฟล์ทั้งหมดเข้าสู่หน่วยความจำ แทนที่จะทำเช่นนั้น ให้คืนค่า `FileStream` ที่เขียนโดยตรงลงดิสก์ตามที่แสดงไว้ก่อนหน้า วิธีนี้จะป้องกัน `OutOfMemoryException` ในสถานการณ์ที่มีการประมวลผลจำนวนมาก + +### ข้อควรพิจารณาเรื่องความปลอดภัยของเธรด + +อินสแตนซ์ของ `HTMLDocument` **ไม่** ปลอดภัยต่อการทำงานหลายเธรด หากคุณต้องการประมวลผลสตริง HTML หลาย ๆ ตัวพร้อมกัน ให้สร้าง `HTMLDocument` และ `MyHandler` แยกต่างหากต่อเธรด หรือทำการซิงโครไนซ์การเข้าถึงด้วย `lock` + +### การปล่อยสตรีม + +`HTMLDocument.Save` และ `ResourceHandler.HandleResource` อาจคืนค่าสตรีมที่ต้องทำการปล่อย ในตัวอย่างข้างต้น ไลบรารีจะทำการปล่อยสตรีมโดยอัตโนมัติหลังจากเขียนเสร็จ หากคุณจัดการสตรีมด้วยตนเอง (เช่น เปิด `FileStream` ก่อนเรียก `Save`) ให้ห่อหุ้มด้วยคำสั่ง `using` + +## สรุป + +คู่มือนี้แสดงให้คุณเห็นวิธี **load html string** ไปยัง `HTMLDocument`, **create custom handler** เพื่อกำหนดการจัดเก็บทรัพยากร, และ **how to save htmldocument** ด้วย **custom resource handling** ตอนนี้คุณมี: + +1. วิธีที่ชัดเจนในการแปลง HTML ดิบเป็นอ็อบเจ็กต์ DOM +2. `ResourceHandler` subclass ที่สามารถนำกลับมาใช้ใหม่ได้ซึ่งสามารถเขียนทรัพยากรลงในหน่วยความจำ, ดิสก์, หรือการจัดเก็บบนคลาวด์ +3. โปรแกรมที่สมบูรณ์และสามารถรันได้ซึ่งแสดงกระบวนการทำงานทั้งหมด + +## ขั้นตอนต่อไป + +- สำรวจการ override `ResourceHandler` อื่น ๆ เช่น `HandleCss` หรือ `HandleFont` หากไลบรารีของคุณมีให้ +- ผสานวิธีนี้กับขั้นตอนการแปลงเป็น PDF เพื่อสร้างไฟล์ PDF จาก HTML พร้อมการควบคุมเต็มที่ต่อทรัพยากรที่ฝังอยู่ +- ตรวจสอบเอกสารของไลบรารีสำหรับตัวเลือกเพิ่มเติมเช่น *compression*, *caching*, หรือการบันทึกแบบ *asynchronous* + +อย่าลังเลที่จะทดลองกลยุทธ์การจัดเก็บต่าง ๆ และแบ่งปันผลการทดลองของคุณในคอมเมนต์หรือในชุมชนนักพัฒนาที่คุณชื่นชอบ ขอให้เขียนโค้ดอย่างสนุกสนาน! + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบอื่นในโปรเจกต์ของคุณ + +- [วิธีบันทึก HTML ใน C# – คู่มือเต็มด้วยตัวจัดการทรัพยากรแบบกำหนดเอง](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [สร้าง HTML จากสตริงใน C# – คู่มือตัวจัดการทรัพยากรแบบกำหนดเอง](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [วิธีบีบอัด HTML เป็น Zip ใน C# – บันทึก HTML เป็น Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 8dd996b055..be3b2cc9ae 100644 --- a/html/turkish/net/html-extensions-and-conversions/_index.md +++ b/html/turkish/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET yalnızca bir kütüphane değil; web geliştirme dünyası ## HTML Uzantıları ve Dönüşümleri Eğitimleri ### [Aspose.HTML ile .NET'te HTML'yi PDF'ye dönüştürün](./convert-html-to-pdf/) Aspose.HTML for .NET ile HTML'yi zahmetsizce PDF'ye dönüştürün. Adım adım kılavuzumuzu izleyin ve HTML'den PDF'ye dönüştürmenin gücünü serbest bırakın. +### [Aspose.HTML ile .NET'te C#'ta HTML'yi PDF'ye Dönüştür – Yazı Tipi Stilini Programlı Olarak Ayarlama](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Aspose.HTML for .NET kullanarak C# kodunda HTML'yi PDF'ye dönüştürürken yazı tipi stilini programlı olarak ayarlamayı öğrenin. ### [Aspose.HTML ile .NET'te EPUB'ı Görüntüye Dönüştürme](./convert-epub-to-image/) Aspose.HTML for .NET kullanarak EPUB'ı görsellere nasıl dönüştüreceğinizi öğrenin. Kod örnekleri ve özelleştirilebilir seçenekler içeren adım adım eğitim. ### [Aspose.HTML ile .NET'te EPUB'ı PDF'ye dönüştürün](./convert-epub-to-pdf/) diff --git a/html/turkish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/turkish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..95d46e16a2 --- /dev/null +++ b/html/turkish/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: C#'ta HTML'yi PDF'ye tam render kontrolüyle dönüştürün. Yazı tipi stilini + programlı olarak nasıl ayarlayacağınızı, antialiasing'i nasıl etkinleştireceğinizi + ve metin netliğini nasıl artıracağınızı öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: tr +lastmod: 2026-08-03 +og_description: C# ile HTML'yi PDF'ye dönüştürün, ayrıntılı seçeneklerle. Bu kılavuz, + yazı tipi stilini programlı olarak nasıl ayarlayacağınızı, antialiasing'i nasıl + etkinleştireceğinizi ve yüksek kaliteli PDF'ler nasıl üreteceğinizi gösterir. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: C#'de HTML'yi PDF'ye dönüştür – tam render kontrolü +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: C#'de HTML'yi PDF'ye Dönüştür – Yazı Tipi Stilini Programlı Olarak Ayarla +url: /tr/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'yi PDF'ye Dönüştürme C#'ta – Yazı Tipi Stilini Programlı Olarak Ayarlama + +Eğer bir .NET uygulamasında **HTML'yi PDF'ye dönüştürmeniz** gerekiyorsa, bu öğretici size eksiksiz, üretim‑hazır bir çözüm sunar. **Yazı tipi stilini programlı olarak nasıl ayarlayacağınızı**, görüntü işleme kalitesini nasıl artıracağınızı ve metin ipuçlamasını (hinting) nasıl etkinleştireceğinizi C# kodunuzdan çıkmadan göreceksiniz. + +Web sayfalarını PDF'ye dönüştürmek, raporlama, faturalama ve arşivleme gibi senaryolar için yaygın bir gereksinimdir. Bu kılavuz, proje kurulumundan tam çalışan bir örneğe kadar her şeyi kapsar. Makalenin sonunda, düzeni, tipografiyi ve görsel doğruluğu koruyan PDF'ler üretebileceksiniz. + +## Öğrenecekleriniz + +* Gerekli NuGet paketini nasıl ekleyeceğinizi ve ad alanlarını nasıl içe aktaracağınızı. +* `HtmlConversionOptions` sınıfını renderlamayı kontrol edecek şekilde nasıl yapılandıracağınızı. +* `WebFontStyle` bayraklarını kullanarak **yazı tipi stilini programlı olarak nasıl ayarlayacağınızı**. +* Görüntüler için antialiasing'i ve metin için hinting'i nasıl etkinleştireceğinizi. +* `Converter` sınıfını çağırarak nihai PDF dosyasını nasıl üreteceğinizi. + +Bu öğretici, Visual Studio 2022 (veya daha yenisi) ve .NET 6 ya da daha yeni bir sürümün yüklü olduğunu varsayar. Ek bir araç gereksinimi yoktur. + +## Önkoşullar + +| Gereksinim | Sebep | +|---|---| +| .NET 6 SDK veya daha yenisi | C# projesi için çalışma zamanını sağlar. | +| Visual Studio 2022 (veya herhangi bir IDE) | Proje oluşturmayı ve hata ayıklamayı kolaylaştırır. | +| NuGet paketlerini geri yüklemek için internet erişimi | Dönüşüm kütüphanesini indirmek için gereklidir. | +| Basit bir HTML dosyası (`input.html`) | Dönüştürme için kaynak belge olarak hizmet eder. | + +> **İpucu:** HTML dosyasını proje ile aynı klasöre koyun; böylece yol‑ile ilgili sorunlardan kaçınmış olursunuz. + +## Adım 1: Dönüşüm Kütüphanesini Yükleyin + +Kod örneği, `HtmlConversionOptions` ve bir `Converter` sınıfı sunan **GroupDocs.Conversion for .NET** kütüphanesini kullanır. NuGet Package Manager üzerinden şu şekilde yükleyin: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Paket, projenize gerekli tipleri ekler ve tüm bağımlılıkları getirir. + +## Adım 2: Bir C# Konsol Projesi Oluşturun + +Komut istemcisini açın ve şu komutu çalıştırın: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Bu, `HtmlToPdfDemo` adlı minimal bir konsol uygulaması oluşturur. Oluşturulan `Program.cs` dosyasını açın; içeriğini daha sonra tam örnekle değiştireceksiniz. + +## Adım 3: Dönüşüm Seçeneklerini Yapılandırın – Yazı Tipi Stilini Programlı Olarak Ayarlayın + +`HtmlConversionOptions` sınıfı, HTML motorunun sayfayı nasıl renderlayacağını ince ayar yapmanıza olanak tanır. **Yazı tipi stilini programlı olarak ayarlamak** için `WebFontStyle` enum değerlerini bit düzeyinde OR (|) operatörüyle birleştirin: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Neden Önemli:** +* `WebFontStyle.Bold | WebFontStyle.Italic` renderlayıcıya, varsayılan yazı tipini kullanan tüm metinlere hem kalın hem de italik stilini uygulamasını söyler. +* Antialiasing, özellikle ölçeklendirme sırasında raster görüntülerdeki tırtıklı kenarları azaltır. +* Hinting, glif konturlarını piksel ızgaralarına hizalayarak düşük çözünürlüklü ekranlarda ve oluşturulan PDF'de okunabilirliği artırır. + +## Adım 4: Dönüşümü Gerçekleştirin + +Seçenekler hazır olduğunda `Converter` sınıfını çağırın. `Convert` metodu üç argüman alır: kaynak HTML dosya yolu, hedef PDF dosya yolu ve seçenekler nesnesi. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Metot senkron olarak çalışır ve kaynak dosya okunamazsa ya da çıktı yolu geçersizse bir istisna fırlatır. Üretim kodu için çağrıyı bir try‑catch bloğuna alın. + +## Adım 5: Sonucu Doğrulayın + +Program tamamlandıktan sonra `output.pdf` dosyasını herhangi bir PDF görüntüleyiciyle açın. Şunları görmelisiniz: + +* **Kalın ve italik** olarak renderlanmış metin (orijinal HTML bu stilleri belirtmemiş olsa bile). +* Antialiasing sayesinde daha yumuşak görünen görüntüler. +* Hinting sayesinde özellikle küçük punto boyutlarında geliştirilmiş metin netliği. + +PDF beklenen stilleri göstermiyorsa, HTML dosyasının web‑güvenli bir yazı tipine referans verdiğini veya dönüştürücünün yükleyebileceği bir `@font-face` kuralı içerdiğini iki kez kontrol edin. + +## Tam, Çalıştırılabilir Örnek + +Aşağıda, önceki adımların tümünü bir araya getiren bağımsız bir program yer alıyor. Kodu `Program.cs` içine kopyalayın, yanına bir `input.html` dosyası koyun ve `dotnet run` komutunu çalıştırın. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Beklenen konsol çıktısı** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Uygulanan stilleri doğrulamak için oluşturulan PDF'yi açın. + +## Yaygın Kenar Durumlarını Ele Alma + +| Durum | Önerilen yaklaşım | +|---|---| +| **Harici CSS veya yazı tipleri** | CSS dosyalarını ve yazı tipi kaynaklarını `input.html` ile aynı klasöre yerleştirin veya dönüşümün çalıştığı makineden erişilebilen mutlak URL'lerle referans verin. | +| **Büyük HTML belgeleri** | `OutOfMemoryException` ile karşılaşırsanız `ConversionConfig` ayarını değiştirerek varsayılan bellek sınırını artırın. | +| **Dinamik içerik (JavaScript)** | Kütüphane JavaScript çalıştırmaz. Dinamik bölümleri sunucu tarafında ön‑renderleyin veya dönüşümden önce statik bir HTML anlık görüntüsü üretmek için başsız bir tarayıcı kullanın. | +| **Unicode karakterler görüntülenmiyor** | HTML'nin `` bildirdiğinden ve kaynak yazı tiplerinin gerekli glifleri içerdiğinden emin olun. | +| **Yanlış sayfa boyutu** | Tutarlı boyutlar sağlamak için `conversionOptions.PageSize = PageSize.A4` (veya başka bir enum değeri) ayarlayın. | + +## Performans İpuçları + +* Birçok dosya dönüştürürken tek bir `Converter` örneğini yeniden kullanın; bu başlangıç yükünü azaltır. +* Gerekmiyorsa gereksiz renderlama özelliklerini (ör. `EnableHyperlinks`) devre dışı bırakın; bu işlem süresini hızlandırır. +* PDF'yi doğrudan HTTP üzerinden göndermeniz gerektiğinde diske yazmak yerine bir bellek akışına (memory stream) yazın. + +## Sonraki Adımlar + +Artık **HTML'yi PDF'ye dönüştürürken** özel yazı tipi ayarlarını kullanabildiğinize göre, aşağıdaki ilgili konuları keşfedin: + +* **Sayfa kenar boşluklarını programlı olarak ayarlama** – `conversionOptions.Margin` değerini değiştirerek boş alanı kontrol edin. +* **Filigran ekleme** – `PdfConversionOptions` kullanarak metin ya da görüntü üzerine katman ekleyin. +* **Toplu dönüşüm** – bir HTML dosyası koleksiyonu üzerinde döngü kurun ve aynı seçenek nesnesini yeniden kullanın. + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanız ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [HTML'yi .NET'te Aspose.HTML ile PDF'ye Dönüştürme](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Stilize Metinli HTML Belgesi Oluşturma ve PDF'ye Dışa Aktarma – Tam Kılavuz](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [SVG'yi .NET'te Aspose.HTML ile PDF'ye Dönüştürme](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/turkish/net/working-with-html-documents/_index.md b/html/turkish/net/working-with-html-documents/_index.md index 1aee408b6b..290a724a20 100644 --- a/html/turkish/net/working-with-html-documents/_index.md +++ b/html/turkish/net/working-with-html-documents/_index.md @@ -37,6 +37,9 @@ Temelleri kavradığınızda, oluşturma sürecine daha derinlemesine dalacağı Şimdi becerilerinizi bir üst seviyeye taşıyalım. HTML belgelerini düzenlemek web geliştiricileri için yaygın bir görevdir ve Aspose.HTML bu süreci önemli ölçüde basitleştirir. Bu bölümde, belge oluşturma, düzenleme ve biçimlendirmeyi ele alacağız. Web içeriğinizin görünümünü ve işlevselliğini nasıl geliştireceğinizi, onu ilgi çekici ve kullanıcı dostu hale getireceğinizi keşfedeceksiniz. ### [C#'ta HTML Kaydetme – Özel Kaynak İşleyicisi Kullanarak Tam Kılavuz](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) + +### [C#'ta HTML Dizesi Yükleme – Özel İşleyici ile Tam Kılavuz](./load-html-string-in-c-complete-guide-with-custom-handler/) + ### [CSS ve C# ile Başlığı Kalınlaştırma – Tam Adım Adım Kılavuz](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/turkish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..1c872b3ad4 --- /dev/null +++ b/html/turkish/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-03 +description: C#'de HTML dizesini yükleyin ve HTMLDocument'i kaydetmek için özel bir + işleyici oluşturun. Özel kaynak yönetimiyle HTMLDocument'i nasıl kaydedeceğinizi + öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: tr +lastmod: 2026-08-03 +og_description: C#'de HTML dizesini yükleyin ve HTMLDocument'i kaydetmek için özel + bir işleyici kullanın. Bu öğreticide tam uygulama ve en iyi uygulamalar gösterilmektedir. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: C#'de HTML dizesini yükle – adım adım özel işleyici rehberi +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: C#'de HTML dizesini yükleme – özel işleyici ile tam rehber +url: /tr/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta HTML dizesi yükleme – özel işleyici ile tam kılavuz + +Bir C# uygulamasında **html dizesi yüklemeniz** gerekiyorsa, bu öğretici bunu tam olarak nasıl yapacağınızı ve kaynak yönetimi için **özel işleyici oluşturmayı** gösterir. Ayrıca **custom resource handling** kullanarak **htmldocument'i nasıl kaydedeceğinizi** öğreneceksiniz, böylece her resim, CSS dosyası veya betik tam istediğiniz yere yazılır. + +Tam süreci adım adım inceleyeceğiz—ham bir HTML dizesini bir `HTMLDocument` nesnesine dönüştürmekten, her kaynağın nerede saklanacağını kontrol eden bir `ResourceHandler` alt sınıfını uygulamaya kadar. Sonunda, herhangi bir .NET projesine ekleyebileceğiniz, bağımsız ve üretim‑hazır bir örnek elde edeceksiniz. + +## Önkoşullar + +- .NET 6.0 veya üzeri (kod ayrıca .NET Framework 4.7+ üzerinde de çalışır) +- `HTMLDocument`, `ResourceHandler` ve `ResourceInfo` sağlayan kütüphaneye referans (ör. *HtmlRenderer* veya benzeri bir HTML‑to‑PDF/DOM kütüphanesi) +- C# sözdizimi ve akışlar hakkında temel bilgi + +> **Pro tip:** Visual Studio kullanıyorsanız, *nullable reference types* (`enable`) özelliğini etkinleştirerek null‑ile ilgili hataları erken yakalayabilirsiniz. + +## HTMLDocument'e html dizesi nasıl yüklenir + +İlk adım, düz bir HTML dizesini kütüphanenin çalışabileceği bir `HTMLDocument` nesnesine dönüştürmektir. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Neden önemli:** +`HTMLDocument` işaretlemi ayrıştırır, bir DOM ağacı oluşturur ve kaynakları (resimler, stil sayfaları vb.) sonraki kaydetme işlemi için hazırlar. Dizeyi doğrudan geçirmek geçici dosyalara ihtiyaç duyulmasını önler ve iş akışını bellekte tutar. + +### Yaygın tuzaklar + +| Sorun | Neden oluşur | Çözüm | +|-------|----------------|-----| +| `htmlContent` is `null` | Dize değişkenine hiç değer atanmadı. | Belge oluşturulmadan önce doğrulama yapın: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | Kütüphane UTF‑8 varsayar ancak kaynak başka bir kodlama kullanıyor. | Mümkünse açık bir `Encoding` aşırı yüklemesi sağlayın veya dizenin doğru şekilde çözüldüğünden emin olun. | + +## Kaynak yönetimi için özel işleyici oluşturma + +Bir **custom resource handler**, kütüphanenin dış kaynakları (resimler, CSS, fontlar) nasıl yazdığını tam kontrol etmenizi sağlar. Aşağıda her kaynağı bir `MemoryStream`'e yazan minimal bir uygulama bulunmaktadır. Gövdeyi dosya‑sistemi mantığı, bulut depolama veya başka bir hedef ile değiştirebilirsiniz. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Neden özel bir işleyiciye ihtiyacınız var:** +Varsayılan işleyici genellikle kaynakları geçici bir klasöre yazar; bu güvenlik veya performans nedenleriyle istenmeyebilir. `HandleResource` metodunu geçersiz kılarak her baytı tam olarak nerede ve nasıl saklayacağınızı belirleyebilirsiniz. + +### Dosya çıktısı için işleyiciyi genişletme + +Her kaynağı belirli bir klasöre yazmayı tercih ediyorsanız, yöntemi aşağıdaki gibi değiştirin: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Custom handler kullanarak htmldocument'i nasıl kaydedersiniz + +Artık `HTMLDocument` örneği ve `MyHandler` uygulaması elimizde olduğuna göre, belgeyi kalıcı hale getirebiliriz. `Save` metodu herhangi bir `ResourceHandler` alt sınıfını kabul eder ve özel mantığınızı eklemenize olanak tanır. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +When `Save` runs, the library will: + +1. DOM ağacını dolaşır. +2. Dış kaynakları (ör. ``) algılar. +3. Her kaynak için `handler.HandleResource` metodunu çağırır. +4. Kaynak verisini döndürülen akışa yazar. +5. Ana HTML çıktısını tamamlar (genellikle ayrı bir dosya veya akış olarak). + +### Sonucu doğrulama + +`MyHandler`'ın dosya‑sistemi sürümünü kullandıysanız, orijinal HTML dosyası ve referans verilen tüm varlıklarla birlikte bir `output` klasörü görmelisiniz. `MemoryStream` sürümü için, verinin yazıldığını doğrulamak amacıyla akış uzunluğunu inceleyebilirsiniz: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Tam, çalıştırılabilir örnek + +Aşağıda, tüm akışı gösteren tek bir, kopyala‑yapıştır hazır program bulunmaktadır. Hata yönetimi, akışların serbest bırakılması ve her adımı açıklayan yorumlar içerir. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Beklenen çıktı** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Programı çalıştırdıktan sonra, `output` dizini şunları içerir: + +- `index.html` (ana belge) +- Kütüphanenin oluşturduğu ek dosyalar (ör. resimler, CSS) + +## İleri düzey varyasyonlar ve uç durumlar + +### Bellek içi işleme için `MemoryStream`'e kaydetme + +Son HTML'i bir dize olarak ihtiyacınız varsa veya diske dokunmadan HTTP üzerinden göndermek istiyorsanız, `MyHandler`'ı ortak bir `MemoryStream` döndüren bir sürümle değiştirin: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +`htmlDoc.Save(handler)` sonrası, HTML'i okuyabilirsiniz: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Büyük kaynakları güvenli bir şekilde işleme + +Büyük resimler veya PDF'lerle çalışırken, tüm dosyayı belleğe yüklemekten kaçının. Bunun yerine, daha önce gösterildiği gibi doğrudan diske yazan bir `FileStream` döndürün. Bu, yüksek verim senaryolarında `OutOfMemoryException` oluşmasını önler. + +### İş parçacığı güvenliği (Thread‑safety) düşünceleri + +`HTMLDocument` örnekleri **thread‑safe** değildir. Aynı anda birden fazla HTML dizesi işlemek istiyorsanız, her iş parçacığı için ayrı bir `HTMLDocument` ve `MyHandler` oluşturun veya erişimi bir `lock` ile senkronize edin. + +### Akışların serbest bırakılması + +`HTMLDocument.Save` ve `ResourceHandler.HandleResource` her ikisi de serbest bırakılması gereken akışlar döndürebilir. Yukarıdaki örneklerde, kütüphane yazma işleminden sonra akışları otomatik olarak serbest bırakır. Akışları kendiniz yönetiyorsanız (ör. `Save` çağırmadan önce bir `FileStream` açıyorsanız), `using` ifadeleriyle sarmalayın. + +## Özet + +Bu kılavuz, bir `HTMLDocument` içine **html dizesi yüklemeyi**, kaynak depolamayı belirlemek için **custom handler oluşturmayı** ve **custom resource handling** ile **htmldocument'i nasıl kaydedeceğinizi** gösterdi. Artık şunlara sahipsiniz: + +1. Ham HTML'i bir DOM nesnesine dönüştürmenin net bir yolu. +2. Kaynakları belleğe, diske veya bulut depolamaya yazabilen yeniden kullanılabilir bir `ResourceHandler` alt sınıfı. +3. Tam akışı gösteren eksiksiz, çalıştırılabilir bir program. + +## Sonraki adımlar + +- Kütüphaneniz sağlıyorsa, `HandleCss` veya `HandleFont` gibi diğer `ResourceHandler` geçersiz kılmalarını keşfedin. +- Bu yaklaşımı bir PDF dönüşüm adımıyla birleştirerek, gömülü varlıklar üzerinde tam kontrol sağlarken HTML'den PDF oluşturun. +- Kütüphanenin belgelerini *compression*, *caching* veya *asynchronous* kaydetme gibi ek seçenekler için inceleyin. + +Farklı depolama stratejileriyle denemeler yapmaktan çekinmeyin ve bulgularınızı yorumlarda veya favori geliştirici topluluğunuzda paylaşın. Kodlamanın tadını çıkarın! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak adım adım açıklamalı tam çalışan kod örnekleri içerir. + +- [C#'ta HTML Kaydetme – Özel Resource Handler Kullanarak Tam Kılavuz](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [C#'ta Dizeden HTML Oluşturma – Özel Resource Handler Kılavuzu](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [C#'ta HTML'yi Zipleme – HTML'yi Zip'e Kaydetme](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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 169c7624f6..730bc4db9a 100644 --- a/html/vietnamese/net/html-extensions-and-conversions/_index.md +++ b/html/vietnamese/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET không chỉ là một thư viện; mà còn là một côn ## Hướng dẫn về phần mở rộng và chuyển đổi HTML ### [Chuyển đổi HTML sang PDF trong .NET với Aspose.HTML](./convert-html-to-pdf/) Chuyển đổi HTML sang PDF dễ dàng với Aspose.HTML cho .NET. Làm theo hướng dẫn từng bước của chúng tôi và giải phóng sức mạnh của việc chuyển đổi HTML sang PDF. +### [Chuyển đổi HTML sang PDF trong C# – thiết lập kiểu phông chữ bằng mã](./convert-html-to-pdf-in-c-set-font-style-programmatically/) +Thiết lập kiểu phông chữ khi chuyển đổi HTML sang PDF bằng C# và Aspose.HTML. ### [Chuyển đổi EPUB sang hình ảnh trong .NET với Aspose.HTML](./convert-epub-to-image/) Tìm hiểu cách chuyển đổi EPUB sang hình ảnh bằng Aspose.HTML cho .NET. Hướng dẫn từng bước với các ví dụ về mã và tùy chọn có thể tùy chỉnh. ### [Chuyển đổi EPUB sang PDF trong .NET với Aspose.HTML](./convert-epub-to-pdf/) diff --git a/html/vietnamese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md b/html/vietnamese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md new file mode 100644 index 0000000000..04eee0be4c --- /dev/null +++ b/html/vietnamese/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-08-03 +description: Chuyển đổi HTML sang PDF trong C# với khả năng kiểm soát toàn diện quá + trình hiển thị. Tìm hiểu cách thiết lập kiểu phông chữ bằng mã, bật khử răng cưa + và cải thiện độ rõ của văn bản. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- convert html to pdf +- set font style programmatically +language: vi +lastmod: 2026-08-03 +og_description: Chuyển đổi HTML sang PDF trong C# với các tùy chọn chi tiết. Hướng + dẫn này chỉ cách thiết lập kiểu phông chữ bằng mã, bật khử răng cưa và tạo PDF chất + lượng cao. +og_image_alt: Diagram showing conversion of HTML to PDF using C# with font style settings +og_title: Chuyển đổi HTML sang PDF trong C# – kiểm soát đầy đủ việc hiển thị +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Convert HTML to PDF in C# with full rendering control. Learn how to + set font style programmatically, enable antialiasing, and improve text clarity. + headline: Convert HTML to PDF in C# – set font style programmatically + type: TechArticle +tags: +- C# +- PDF conversion +- HTML rendering +title: Chuyển đổi HTML sang PDF trong C# – đặt kiểu phông chữ bằng chương trình +url: /vi/net/html-extensions-and-conversions/convert-html-to-pdf-in-c-set-font-style-programmatically/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển đổi HTML sang PDF trong C# – thiết lập kiểu phông chữ bằng mã + +Nếu bạn cần **chuyển đổi HTML sang PDF** trong một ứng dụng .NET, hướng dẫn này sẽ dẫn bạn qua một giải pháp hoàn chỉnh, sẵn sàng cho môi trường sản xuất. Bạn sẽ thấy cách **thiết lập kiểu phông chữ bằng mã**, cải thiện việc hiển thị hình ảnh và bật hinting cho văn bản — tất cả mà không rời khỏi mã C# của mình. + +Việc chuyển đổi các trang web thành PDF là yêu cầu phổ biến cho báo cáo, lập hoá đơn và lưu trữ. Hướng dẫn này bao gồm mọi thứ từ thiết lập dự án đến một ví dụ đầy đủ, có thể chạy ngay. Khi đọc xong, bạn sẽ tạo ra các PDF giữ nguyên bố cục, kiểu chữ và độ trung thực hình ảnh. + +## Những gì bạn sẽ học + +* Cách thêm gói NuGet cần thiết và nhập không gian tên. +* Cách cấu hình `HtmlConversionOptions` để kiểm soát việc render. +* Cách **thiết lập kiểu phông chữ bằng mã** bằng các cờ `WebFontStyle`. +* Cách bật antialiasing cho hình ảnh và hinting cho văn bản. +* Cách gọi lớp `Converter` để tạo ra tệp PDF cuối cùng. + +Bài hướng dẫn giả định bạn đã cài Visual Studio 2022 (hoặc mới hơn) và .NET 6 hoặc mới hơn. Không cần công cụ bổ sung nào khác. + +## Điều kiện tiên quyết + +| Yêu cầu | Lý do | +|---|---| +| .NET 6 SDK hoặc mới hơn | Cung cấp môi trường chạy cho dự án C#. | +| Visual Studio 2022 (hoặc bất kỳ IDE nào) | Giúp tạo dự án và gỡ lỗi dễ dàng. | +| Kết nối Internet để khôi phục các gói NuGet | Cần để tải thư viện chuyển đổi. | +| Một tệp HTML đơn giản (`input.html`) | Đóng vai trò là tài liệu nguồn để chuyển đổi. | + +> **Mẹo chuyên nghiệp:** Giữ tệp HTML trong cùng thư mục với dự án để tránh các vấn đề liên quan đến đường dẫn. + +## Bước 1: Cài đặt thư viện chuyển đổi + +Mẫu mã sử dụng thư viện **GroupDocs.Conversion for .NET**, cung cấp `HtmlConversionOptions` và lớp `Converter`. Cài đặt nó qua Trình quản lý gói NuGet: + +```bash +dotnet add package GroupDocs.Conversion +``` + +Gói này sẽ thêm các kiểu cần thiết vào dự án của bạn và kéo các phụ thuộc liên quan. + +## Bước 2: Tạo dự án console C# + +Mở command prompt và chạy: + +```bash +dotnet new console -n HtmlToPdfDemo +cd HtmlToPdfDemo +``` + +Lệnh này sẽ tạo một ứng dụng console tối thiểu có tên `HtmlToPdfDemo`. Mở tệp `Program.cs` được tạo; bạn sẽ thay thế nội dung của nó bằng ví dụ đầy đủ sau này. + +## Bước 3: Cấu hình tùy chọn chuyển đổi – thiết lập kiểu phông chữ bằng mã + +Lớp `HtmlConversionOptions` cho phép bạn tinh chỉnh cách engine HTML render trang. Để **thiết lập kiểu phông chữ bằng mã**, kết hợp các giá trị enum `WebFontStyle` bằng toán tử OR bitwise: + +```csharp +using GroupDocs.Conversion.Options.Convert; +using GroupDocs.Conversion.Options.Load; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options; +using GroupDocs.Conversion.Options.Pdf; + +// Step 3: Build conversion options with custom font style +var conversionOptions = new HtmlConversionOptions(); + +// Choose bold and italic simultaneously +conversionOptions.FontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Enable antialiasing for smoother images +conversionOptions.ImageRenderingOptions.UseAntialiasing = true; + +// Turn on hinting for clearer glyph rendering +conversionOptions.TextOptions.UseHinting = true; +``` + +**Tại sao điều này quan trọng:** +* `WebFontStyle.Bold | WebFontStyle.Italic` báo cho renderer áp dụng cả hai kiểu cho bất kỳ văn bản nào sử dụng phông chữ mặc định. +* Antialiasing giảm các cạnh răng cưa trên hình ảnh raster, đặc biệt khi phóng to/thu nhỏ. +* Hinting căn chỉnh đường viền glyph vào lưới pixel, cải thiện khả năng đọc trên màn hình độ phân giải thấp và trong PDF kết quả. + +## Bước 4: Thực hiện chuyển đổi + +Với các tùy chọn đã chuẩn bị, gọi lớp `Converter`. Phương thức `Convert` nhận ba đối số: đường dẫn tệp HTML nguồn, đường dẫn tệp PDF đích và đối tượng tùy chọn. + +```csharp +// Step 4: Convert the HTML file to PDF using the configured options +string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); +string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + +// Create the converter and execute the conversion +new Converter().Convert(inputPath, outputPath, conversionOptions); +``` + +Phương thức chạy đồng bộ và ném ngoại lệ nếu không thể đọc tệp nguồn hoặc đường dẫn đầu ra không hợp lệ. Hãy bọc lời gọi trong khối try‑catch cho mã sản xuất. + +## Bước 5: Kiểm tra kết quả + +Sau khi chương trình kết thúc, mở `output.pdf` bằng bất kỳ trình xem PDF nào. Bạn sẽ thấy: + +* Văn bản được render **in đậm và nghiêng** (ngay cả khi HTML gốc không chỉ định các kiểu này). +* Hình ảnh trông mượt hơn nhờ antialiasing. +* Độ rõ nét của văn bản được cải thiện bởi hinting, đặc biệt với kích thước phông chữ nhỏ. + +Nếu PDF không phản ánh các kiểu mong muốn, hãy kiểm tra lại tệp HTML đã tham chiếu một phông chữ web‑safe hoặc bao gồm quy tắc `@font-face` mà trình chuyển đổi có thể tải. + +## Ví dụ đầy đủ, có thể chạy + +Dưới đây là một chương trình tự chứa tích hợp tất cả các bước trước. Sao chép mã vào `Program.cs`, đặt tệp `input.html` bên cạnh và chạy `dotnet run`. + +```csharp +// Program.cs +using System; +using System.IO; +using GroupDocs.Conversion; +using GroupDocs.Conversion.Options.Convert; + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // Paths for source HTML and target PDF + string inputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "input.html"); + string outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.pdf"); + + // Ensure the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Configure conversion options + var conversionOptions = new HtmlConversionOptions + { + // Combine bold and italic styles programmatically + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Improve image rendering quality + ImageRenderingOptions = { UseAntialiasing = true }, + + // Enhance text clarity + TextOptions = { UseHinting = true } + }; + + try + { + // Perform the conversion + new Converter().Convert(inputPath, outputPath, conversionOptions); + Console.WriteLine($"Conversion succeeded. PDF saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } + } +} +``` + +**Kết quả console dự kiến** + +``` +Conversion succeeded. PDF saved to: C:\Path\To\Your\App\output.pdf +``` + +Mở PDF đã tạo để xác nhận các kiểu đã được áp dụng. + +## Xử lý các trường hợp phổ biến + +| Tình huống | Cách tiếp cận đề xuất | +|---|---| +| **CSS hoặc phông chữ bên ngoài** | Đặt các tệp CSS và tài nguyên phông chữ trong cùng thư mục với `input.html` hoặc tham chiếu chúng bằng URL tuyệt đối có thể truy cập được từ máy thực hiện chuyển đổi. | +| **Tài liệu HTML lớn** | Tăng giới hạn bộ nhớ mặc định bằng cách điều chỉnh `ConversionConfig` nếu gặp `OutOfMemoryException`. | +| **Nội dung động (JavaScript)** | Thư viện không thực thi JavaScript. Hãy render trước các phần động ở phía server hoặc dùng trình duyệt headless để tạo ảnh chụp HTML tĩnh trước khi chuyển đổi. | +| **Ký tự Unicode không hiển thị** | Đảm bảo HTML khai báo `` và phông chữ nguồn chứa các glyph cần thiết. | +| **Kích thước trang không đúng** | Đặt `conversionOptions.PageSize = PageSize.A4` (hoặc giá trị enum khác) để đảm bảo kích thước đồng nhất. | + +## Mẹo tối ưu hiệu năng + +* Tái sử dụng một thể hiện `Converter` duy nhất khi chuyển đổi nhiều tệp; điều này giảm chi phí khởi động. +* Tắt các tính năng render không cần thiết (ví dụ, `EnableHyperlinks`) nếu bạn không cần chúng, giúp tăng tốc xử lý. +* Ghi PDF vào một memory stream khi bạn cần gửi trực tiếp qua HTTP thay vì ghi ra đĩa. + +## Các bước tiếp theo + +Bây giờ bạn đã có thể **chuyển đổi HTML sang PDF** với cài đặt phông chữ tùy chỉnh, hãy khám phá các chủ đề liên quan sau: + +* **Thiết lập lề trang bằng mã** – điều chỉnh `conversionOptions.Margin` để kiểm soát khoảng trắng. +* **Thêm watermark** – dùng `PdfConversionOptions` để chồng lên văn bản hoặc hình ảnh. +* **Chuyển đổi hàng loạt** – lặp qua một tập hợp các tệp HTML và tái sử dụng cùng một đối tượng tùy chọn. + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong bài viết này. Mỗi tài nguyên bao gồm mã mẫu đầy đủ với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Chuyển đổi HTML sang PDF trong .NET với Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-pdf/) +- [Tạo tài liệu HTML với văn bản có kiểu và xuất ra PDF – Hướng dẫn đầy đủ](/html/english/net/html-extensions-and-conversions/create-html-document-with-styled-text-and-export-to-pdf-full/) +- [Chuyển đổi SVG sang PDF trong .NET với Aspose.HTML](/html/english/net/canvas-and-image-manipulation/convert-svg-to-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/vietnamese/net/working-with-html-documents/_index.md b/html/vietnamese/net/working-with-html-documents/_index.md index ce506e2888..8a5c918e78 100644 --- a/html/vietnamese/net/working-with-html-documents/_index.md +++ b/html/vietnamese/net/working-with-html-documents/_index.md @@ -38,6 +38,10 @@ Bây giờ, hãy đưa kỹ năng của bạn lên một tầm cao mới. Chỉn ### [Cách lưu HTML trong C# – Hướng dẫn đầy đủ sử dụng Trình xử lý tài nguyên tùy chỉnh](./how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +### [Tải chuỗi HTML trong C# – hướng dẫn đầy đủ với trình xử lý tùy chỉnh](./load-html-string-in-c-complete-guide-with-custom-handler/) + +Hướng dẫn chi tiết cách tải một chuỗi HTML trong C# bằng Aspose.HTML sử dụng trình xử lý tùy chỉnh. + ### [Cách làm tiêu đề đậm bằng CSS & C# – Hướng dẫn chi tiết từng bước](./how-to-bold-heading-with-css-c-complete-step-by-step-guide/) Hướng dẫn chi tiết cách sử dụng CSS và C# để làm tiêu đề in đậm, kèm ví dụ mã và các bước thực hiện cụ thể. diff --git a/html/vietnamese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md b/html/vietnamese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md new file mode 100644 index 0000000000..d978e243bb --- /dev/null +++ b/html/vietnamese/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-03 +description: Tải chuỗi HTML trong C# và tạo bộ xử lý tùy chỉnh để lưu HTMLDocument. + Tìm hiểu cách lưu HTMLDocument với việc xử lý tài nguyên tùy chỉnh. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- load html string +- create custom handler +- how to save htmldocument +- custom resource handling +language: vi +lastmod: 2026-08-03 +og_description: Tải chuỗi HTML trong C# và sử dụng trình xử lý tùy chỉnh để lưu HTMLDocument. + Hướng dẫn này trình bày đầy đủ việc triển khai và các thực tiễn tốt nhất. +og_image_alt: Screenshot showing load html string code with custom handler in C# +og_title: Tải chuỗi HTML trong C# – hướng dẫn xử lý tùy chỉnh từng bước +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + headline: Load html string in C# – complete guide with custom handler + type: TechArticle +- description: Load html string in C# and create custom handler to save HTMLDocument. + Learn how to save HTMLDocument with custom resource handling. + name: Load html string in C# – complete guide with custom handler + steps: + - name: Common pitfalls + text: '| Issue | Why it happens | Fix | |-------|----------------|-----| | `htmlContent` + is `null` | The string variable was never assigned. | Validate before creating + the document: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` + | | Encoding problems | The library assumes ' + - name: Extending the handler for file output + text: 'If you prefer to write each resource to a specific folder, modify the method + as follows:' + - name: Verifying the result + text: 'If you used the file‑system version of `MyHandler`, you should see an `output` + folder with the original HTML file and any referenced assets. For the `MemoryStream` + version, you can inspect the stream length to confirm data was written:' + - name: Saving to a `MemoryStream` for in‑memory processing + text: 'If you need the final HTML as a string or want to send it over HTTP without + touching disk, replace `MyHandler` with a version that returns a shared `MemoryStream`:' + - name: Handling large resources safely + text: When dealing with large images or PDFs, avoid loading the entire file into + memory. Instead, return a `FileStream` that writes directly to disk, as shown + earlier. This prevents `OutOfMemoryException` in high‑throughput scenarios. + - name: Thread‑safety considerations + text: '`HTMLDocument` instances are **not** thread‑safe. If you need to process + multiple HTML strings concurrently, create a separate `HTMLDocument` and `MyHandler` + per thread, or synchronize access with a `lock`.' + - name: Disposing streams + text: Both `HTMLDocument.Save` and `ResourceHandler.HandleResource` may return + streams that need disposal. In the examples above, the library disposes the + streams automatically after writing. If you manage streams yourself (e.g., opening + a `FileStream` before calling `Save`), wrap them in `using` statemen + type: HowTo +tags: +- HTMLDocument +- C# +- resource handling +title: Tải chuỗi HTML trong C# – hướng dẫn đầy đủ với trình xử lý tùy chỉnh +url: /vi/net/working-with-html-documents/load-html-string-in-c-complete-guide-with-custom-handler/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tải chuỗi html trong C# – hướng dẫn đầy đủ với trình xử lý tùy chỉnh + +Nếu bạn cần **load html string** trong một ứng dụng C#, hướng dẫn này sẽ cho bạn biết chính xác cách thực hiện và cách **create custom handler** để quản lý tài nguyên. Bạn cũng sẽ học **how to save htmldocument** bằng **custom resource handling** sao cho mỗi hình ảnh, tệp CSS hoặc script được ghi đúng nơi bạn muốn. + +Chúng tôi sẽ hướng dẫn toàn bộ quá trình — từ việc chuyển một chuỗi HTML thô thành đối tượng `HTMLDocument`, đến việc triển khai một lớp con `ResourceHandler` kiểm soát nơi lưu trữ mỗi tài nguyên. Khi kết thúc, bạn sẽ có một ví dụ tự chứa, sẵn sàng cho môi trường production mà bạn có thể đưa vào bất kỳ dự án .NET nào. + +## Yêu cầu trước + +- .NET 6.0 hoặc mới hơn (mã cũng hoạt động trên .NET Framework 4.7+) +- Tham chiếu tới thư viện cung cấp `HTMLDocument`, `ResourceHandler`, và `ResourceInfo` (ví dụ: *HtmlRenderer* hoặc một thư viện HTML‑to‑PDF/DOM tương tự) +- Kiến thức cơ bản về cú pháp C# và streams + +> **Mẹo chuyên nghiệp:** Nếu bạn sử dụng Visual Studio, bật *nullable reference types* (`enable`) để phát hiện sớm các lỗi liên quan đến null. + +## Cách tải chuỗi html vào HTMLDocument + +Bước đầu tiên là chuyển một chuỗi HTML thuần thành đối tượng `HTMLDocument` mà thư viện có thể làm việc. + +```csharp +using System; +using System.IO; + +// Assume the library namespace is HtmlProcessing +using HtmlProcessing; // <-- replace with the actual namespace + +// 1️⃣ Load the HTML string +string htmlContent = "

Hello, World!

"; + +// 2️⃣ Create the document instance from the string +HTMLDocument htmlDoc = new HTMLDocument(htmlContent); +``` + +**Tại sao điều này quan trọng:** +`HTMLDocument` phân tích markup, xây dựng cây DOM, và chuẩn bị các tài nguyên (hình ảnh, stylesheet, v.v.) để lưu sau. Truyền trực tiếp một chuỗi giúp tránh việc tạo file tạm và giữ quy trình trong bộ nhớ. + +### Những cạm bẫy thường gặp + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|-------|----------------|-----| +| `htmlContent` is `null` | Biến chuỗi chưa được gán giá trị. | Kiểm tra trước khi tạo tài liệu: `if (htmlContent == null) throw new ArgumentNullException(nameof(htmlContent));` | +| Encoding problems | Thư viện giả định UTF‑8 nhưng nguồn sử dụng mã hoá khác. | Cung cấp overload `Encoding` rõ ràng nếu có, hoặc đảm bảo chuỗi được giải mã đúng. | + +## Tạo trình xử lý tùy chỉnh cho việc quản lý tài nguyên + +Một **custom resource handler** cho phép bạn kiểm soát hoàn toàn cách thư viện ghi các tài nguyên bên ngoài (hình ảnh, CSS, phông chữ). Dưới đây là một triển khai tối thiểu ghi mỗi tài nguyên vào `MemoryStream`. Bạn có thể thay thế phần thân bằng logic hệ thống tệp, lưu trữ đám mây, hoặc bất kỳ đích nào khác. + +```csharp +/// +/// Custom handler that writes each resource into a memory stream. +/// +class MyHandler : ResourceHandler +{ + /// + /// Called by HTMLDocument for every external resource. + /// + /// Metadata about the resource (e.g., URL, MIME type). + /// A writable stream where the resource data will be stored. + public override Stream HandleResource(ResourceInfo info) + { + // For demonstration we use a MemoryStream. + // In real scenarios you might open a FileStream or upload to cloud storage. + return new MemoryStream(); + } +} +``` + +**Tại sao bạn cần một custom handler:** +Trình xử lý mặc định thường ghi tài nguyên vào thư mục tạm, điều này có thể không mong muốn vì lý do bảo mật hoặc hiệu năng. Bằng cách ghi đè `HandleResource`, bạn quyết định chính xác nơi và cách mỗi byte được lưu trữ. + +### Mở rộng trình xử lý để xuất ra tệp + +Nếu bạn muốn ghi mỗi tài nguyên vào một thư mục cụ thể, hãy sửa đổi phương thức như sau: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + + // Generate a safe file name based on the resource URL. + string fileName = Path.GetFileName(new Uri(info.Uri).LocalPath); + string filePath = Path.Combine(outputDir, fileName); + + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); +} +``` + +## Cách lưu htmldocument bằng trình xử lý tùy chỉnh + +Bây giờ chúng ta đã có cả đối tượng `HTMLDocument` và triển khai `MyHandler`, chúng ta có thể lưu tài liệu. Phương thức `Save` chấp nhận bất kỳ lớp con `ResourceHandler` nào, cho phép bạn tích hợp logic tùy chỉnh của mình. + +```csharp +// 3️⃣ Instantiate the custom handler +var handler = new MyHandler(); + +// 4️⃣ Save the document; the handler decides where resources go +htmlDoc.Save(handler); +``` + +Khi `Save` được thực thi, thư viện sẽ: + +1. Duyệt cây DOM. +2. Phát hiện các tài nguyên bên ngoài (ví dụ, ``). +3. Gọi `handler.HandleResource` cho mỗi tài nguyên. +4. Ghi dữ liệu tài nguyên vào stream được trả về. +5. Hoàn thiện đầu ra HTML chính (thường là một tệp hoặc stream riêng). + +### Xác minh kết quả + +Nếu bạn sử dụng phiên bản hệ thống tệp của `MyHandler`, bạn sẽ thấy một thư mục `output` chứa tệp HTML gốc và mọi tài nguyên được tham chiếu. Đối với phiên bản `MemoryStream`, bạn có thể kiểm tra độ dài của stream để xác nhận dữ liệu đã được ghi: + +```csharp +using (var stream = handler.HandleResource(new ResourceInfo { Uri = "data:," })) +{ + Console.WriteLine($"Stream length after save: {stream.Length} bytes"); +} +``` + +## Ví dụ đầy đủ, có thể chạy được + +Dưới đây là một chương trình duy nhất, sẵn sàng sao chép‑dán, minh họa toàn bộ quy trình. Nó bao gồm xử lý lỗi, giải phóng streams, và các chú thích giải thích từng bước. + +```csharp +using System; +using System.IO; +using HtmlProcessing; // Replace with the actual namespace of your HTML library + +namespace HtmlStringDemo +{ + /// + /// Custom handler that saves each resource to the local "output" directory. + /// + class MyHandler : ResourceHandler + { + private readonly string _outputDir; + + public MyHandler() + { + _outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(_outputDir); + } + + public override Stream HandleResource(ResourceInfo info) + { + // Derive a safe file name from the resource URI. + string fileName = Path.GetFileName(new Uri(info.Uri, UriKind.RelativeOrAbsolute).LocalPath); + if (string.IsNullOrWhiteSpace(fileName)) + fileName = Guid.NewGuid().ToString() + ".bin"; + + string filePath = Path.Combine(_outputDir, fileName); + // Return a FileStream that the library will write into. + return new FileStream(filePath, FileMode.Create, FileAccess.Write); + } + } + + class Program + { + static void Main() + { + // 1️⃣ Load the HTML string. + string htmlContent = "

Hello, World!

"; + if (string.IsNullOrWhiteSpace(htmlContent)) + throw new ArgumentException("HTML content cannot be empty.", nameof(htmlContent)); + + // 2️⃣ Create the HTMLDocument from the string. + HTMLDocument htmlDoc = new HTMLDocument(htmlContent); + + // 3️⃣ Create the custom resource handler. + var handler = new MyHandler(); + + // 4️⃣ Save the document using the custom handler. + htmlDoc.Save(handler); + + Console.WriteLine("HTML document and resources have been saved to the \"output\" folder."); + } + } +} +``` + +**Kết quả mong đợi** + +``` +HTML document and resources have been saved to the "output" folder. +``` + +Sau khi chạy chương trình, thư mục `output` sẽ chứa: + +- `index.html` (tài liệu chính) +- Bất kỳ tệp bổ sung nào mà thư viện tạo ra (ví dụ, hình ảnh, CSS) + +## Các biến thể nâng cao và trường hợp đặc biệt + +### Lưu vào `MemoryStream` để xử lý trong bộ nhớ + +Nếu bạn cần HTML cuối cùng dưới dạng chuỗi hoặc muốn gửi qua HTTP mà không ghi vào đĩa, hãy thay thế `MyHandler` bằng một phiên bản trả về một `MemoryStream` chung: + +```csharp +class InMemoryHandler : ResourceHandler +{ + private readonly MemoryStream _mainStream = new MemoryStream(); + + public MemoryStream MainStream => _mainStream; + + public override Stream HandleResource(ResourceInfo info) + { + // All resources go into the same memory buffer. + return _mainStream; + } +} +``` + +Sau khi gọi `htmlDoc.Save(handler)`, bạn có thể đọc HTML: + +```csharp +handler.MainStream.Position = 0; +string resultHtml = new StreamReader(handler.MainStream).ReadToEnd(); +Console.WriteLine(resultHtml); +``` + +### Xử lý tài nguyên lớn một cách an toàn + +Khi làm việc với hình ảnh hoặc PDF lớn, tránh tải toàn bộ tệp vào bộ nhớ. Thay vào đó, trả về một `FileStream` ghi trực tiếp vào đĩa, như đã minh họa ở trên. Điều này ngăn `OutOfMemoryException` trong các kịch bản tải cao. + +### Các lưu ý về an toàn đa luồng + +Các thể hiện `HTMLDocument` **không** an toàn đa luồng. Nếu bạn cần xử lý nhiều chuỗi HTML đồng thời, hãy tạo một `HTMLDocument` và `MyHandler` riêng cho mỗi luồng, hoặc đồng bộ truy cập bằng `lock`. + +### Giải phóng streams + +Cả `HTMLDocument.Save` và `ResourceHandler.HandleResource` có thể trả về streams cần được giải phóng. Trong các ví dụ trên, thư viện tự động giải phóng streams sau khi ghi. Nếu bạn tự quản lý streams (ví dụ, mở một `FileStream` trước khi gọi `Save`), hãy bao bọc chúng bằng câu lệnh `using`. + +## Tóm tắt + +Hướng dẫn này đã chỉ cho bạn cách **load html string** vào `HTMLDocument`, **create custom handler** để quyết định cách lưu trữ tài nguyên, và **how to save htmldocument** với **custom resource handling**. Bây giờ bạn có: + +1. Cách rõ ràng để chuyển HTML thô thành đối tượng DOM. +2. Một lớp con `ResourceHandler` có thể tái sử dụng, có thể ghi tài nguyên vào bộ nhớ, đĩa, hoặc lưu trữ đám mây. +3. Một chương trình đầy đủ, có thể chạy được, minh họa toàn bộ quy trình. + +## Các bước tiếp theo + +- Khám phá các override khác của `ResourceHandler` như `HandleCss` hoặc `HandleFont` nếu thư viện của bạn cung cấp. +- Kết hợp cách tiếp cận này với bước chuyển đổi PDF để tạo PDF từ HTML đồng thời giữ toàn quyền kiểm soát các tài nguyên nhúng. +- Xem lại tài liệu của thư viện để biết các tùy chọn bổ sung như *compression*, *caching*, hoặc lưu *asynchronous*. + +Bạn có thể tự do thử nghiệm các chiến lược lưu trữ khác nhau, và chia sẻ kết quả của mình trong phần bình luận hoặc trên cộng đồng nhà phát triển yêu thích. Chúc lập trình vui vẻ! + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh, có hướng dẫn từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách Lưu HTML trong C# – Hướng Dẫn Đầy Đủ Sử Dụng Trình Xử Lý Tài Nguyên Tùy Chỉnh](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Tạo HTML từ Chuỗi trong C# – Hướng Dẫn Trình Xử Lý Tài Nguyên Tùy Chỉnh](/html/english/net/html-document-manipulation/create-html-from-string-in-c-custom-resource-handler-guide/) +- [Cách Nén HTML thành Zip trong C# – Lưu HTML vào Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) + +{{< /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